LCOV - differential code coverage report
Current view: top level - src/backend/commands - repack.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: f76c13edadc2b319036e0d238703ed56bb23f934 vs 9e17d25e79d4756be08b4a5521b4b58450217137 Lines: 91.6 % 1224 1121 103 2 1119 2
Current Date: 2026-09-20 14:13:17 +0900 Functions: 97.7 % 43 42 1 1 41
Baseline: lcov-20260920-baseline Branches: 65.7 % 883 580 1 302 1 579
Baseline Date: 2026-09-20 14:13:13 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 83.3 % 72 60 12 2 58
(7,30] days: 91.7 % 12 11 1 11
(30,360] days: 91.8 % 808 742 66 742
(360..) days: 92.8 % 332 308 24 308
Function coverage date bins:
(1,7] days: 100.0 % 2 2 2
(30,360] days: 97.2 % 36 35 1 1 34
(360..) days: 100.0 % 5 5 5
Branch coverage date bins:
(1,7] days: 56.2 % 48 27 1 20 1 26
(7,30] days: 60.0 % 20 12 8 12
(30,360] days: 68.9 % 547 377 170 377
(360..) days: 61.2 % 268 164 104 164

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * repack.c
                                  4                 :                :  *    REPACK a table; formerly known as CLUSTER.  VACUUM FULL also uses
                                  5                 :                :  *    parts of this code.
                                  6                 :                :  *
                                  7                 :                :  * There are two somewhat different ways to rewrite a table.  In non-
                                  8                 :                :  * concurrent mode, it's easy: take AccessExclusiveLock, create a new
                                  9                 :                :  * transient relation, copy the tuples over to the relfilenode of the new
                                 10                 :                :  * relation, swap the relfilenodes, then drop the old relation.
                                 11                 :                :  *
                                 12                 :                :  * In concurrent mode, we lock the table with only ShareUpdateExclusiveLock,
                                 13                 :                :  * then do an initial copy as above.  However, while the tuples are being
                                 14                 :                :  * copied, concurrent transactions could modify the table. To cope with those
                                 15                 :                :  * changes, we rely on logical decoding to obtain them from WAL.  A bgworker
                                 16                 :                :  * consumes WAL while the initial copy is ongoing (to prevent excessive WAL
                                 17                 :                :  * from being reserved), and accumulates the changes in a file.  Once the
                                 18                 :                :  * initial copy is complete, we read the changes from the file and re-apply
                                 19                 :                :  * them on the new heap.  Then we upgrade our ShareUpdateExclusiveLock to
                                 20                 :                :  * AccessExclusiveLock and swap the relfilenodes.  This way, the time we hold
                                 21                 :                :  * a strong lock on the table is much reduced, and the bloat is eliminated.
                                 22                 :                :  *
                                 23                 :                :  *
                                 24                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                 25                 :                :  * Portions Copyright (c) 1994-5, Regents of the University of California
                                 26                 :                :  *
                                 27                 :                :  *
                                 28                 :                :  * IDENTIFICATION
                                 29                 :                :  *    src/backend/commands/repack.c
                                 30                 :                :  *
                                 31                 :                :  *-------------------------------------------------------------------------
                                 32                 :                :  */
                                 33                 :                : #include "postgres.h"
                                 34                 :                : 
                                 35                 :                : #include "access/amapi.h"
                                 36                 :                : #include "access/heapam.h"
                                 37                 :                : #include "access/multixact.h"
                                 38                 :                : #include "access/relscan.h"
                                 39                 :                : #include "access/tableam.h"
                                 40                 :                : #include "access/toast_internals.h"
                                 41                 :                : #include "access/transam.h"
                                 42                 :                : #include "access/xact.h"
                                 43                 :                : #include "access/xlog.h"
                                 44                 :                : #include "catalog/catalog.h"
                                 45                 :                : #include "catalog/dependency.h"
                                 46                 :                : #include "catalog/heap.h"
                                 47                 :                : #include "catalog/index.h"
                                 48                 :                : #include "catalog/namespace.h"
                                 49                 :                : #include "catalog/objectaccess.h"
                                 50                 :                : #include "catalog/pg_am.h"
                                 51                 :                : #include "catalog/pg_attrdef.h"
                                 52                 :                : #include "catalog/pg_constraint.h"
                                 53                 :                : #include "catalog/pg_inherits.h"
                                 54                 :                : #include "catalog/toasting.h"
                                 55                 :                : #include "commands/defrem.h"
                                 56                 :                : #include "commands/progress.h"
                                 57                 :                : #include "commands/repack.h"
                                 58                 :                : #include "commands/repack_internal.h"
                                 59                 :                : #include "commands/tablecmds.h"
                                 60                 :                : #include "commands/vacuum.h"
                                 61                 :                : #include "executor/executor.h"
                                 62                 :                : #include "libpq/pqformat.h"
                                 63                 :                : #include "libpq/pqmq.h"
                                 64                 :                : #include "miscadmin.h"
                                 65                 :                : #include "optimizer/optimizer.h"
                                 66                 :                : #include "parser/parse_relation.h"
                                 67                 :                : #include "pgstat.h"
                                 68                 :                : #include "replication/logicalrelation.h"
                                 69                 :                : #include "storage/bufmgr.h"
                                 70                 :                : #include "storage/ipc.h"
                                 71                 :                : #include "storage/lmgr.h"
                                 72                 :                : #include "storage/predicate.h"
                                 73                 :                : #include "storage/proc.h"
                                 74                 :                : #include "utils/acl.h"
                                 75                 :                : #include "utils/fmgroids.h"
                                 76                 :                : #include "utils/guc.h"
                                 77                 :                : #include "utils/injection_point.h"
                                 78                 :                : #include "utils/inval.h"
                                 79                 :                : #include "utils/lsyscache.h"
                                 80                 :                : #include "utils/memutils.h"
                                 81                 :                : #include "utils/pg_rusage.h"
                                 82                 :                : #include "utils/relmapper.h"
                                 83                 :                : #include "utils/snapmgr.h"
                                 84                 :                : #include "utils/syscache.h"
                                 85                 :                : #include "utils/wait_event_types.h"
                                 86                 :                : 
                                 87                 :                : /*
                                 88                 :                :  * This struct is used to pass around the information on tables to be
                                 89                 :                :  * clustered. We need this so we can make a list of them when invoked without
                                 90                 :                :  * a specific table/index pair.
                                 91                 :                :  */
                                 92                 :                : typedef struct
                                 93                 :                : {
                                 94                 :                :     Oid         tableOid;
                                 95                 :                :     Oid         indexOid;
                                 96                 :                : } RelToCluster;
                                 97                 :                : 
                                 98                 :                : /*
                                 99                 :                :  * The first file exported by the decoding worker must contain a snapshot, the
                                100                 :                :  * following ones contain the data changes.
                                101                 :                :  */
                                102                 :                : #define WORKER_FILE_SNAPSHOT    0
                                103                 :                : 
                                104                 :                : /*
                                105                 :                :  * Information needed to apply concurrent data changes.
                                106                 :                :  */
                                107                 :                : typedef struct ChangeContext
                                108                 :                : {
                                109                 :                :     /* The relation the changes are applied to. */
                                110                 :                :     Relation    cc_rel;
                                111                 :                : 
                                112                 :                :     /* Needed to update indexes of cc_rel. */
                                113                 :                :     ResultRelInfo *cc_rri;
                                114                 :                :     EState     *cc_estate;
                                115                 :                : 
                                116                 :                :     /*
                                117                 :                :      * Existing tuples to UPDATE and DELETE are located via this index. We
                                118                 :                :      * keep the scankey in partially initialized state to avoid repeated work.
                                119                 :                :      * sk_argument is completed on the fly.
                                120                 :                :      */
                                121                 :                :     Relation    cc_ident_index;
                                122                 :                :     ScanKey     cc_ident_key;
                                123                 :                :     int         cc_ident_key_nentries;
                                124                 :                : 
                                125                 :                :     /* The latest column we need to deform to have the tuple identity */
                                126                 :                :     AttrNumber  cc_last_key_attno;
                                127                 :                : 
                                128                 :                :     /* Sequential number of the file containing the changes. */
                                129                 :                :     int         cc_file_seq;
                                130                 :                : } ChangeContext;
                                131                 :                : 
                                132                 :                : /*
                                133                 :                :  * Backend-local information to control the decoding worker.
                                134                 :                :  */
                                135                 :                : typedef struct DecodingWorker
                                136                 :                : {
                                137                 :                :     /* The worker. */
                                138                 :                :     BackgroundWorkerHandle *handle;
                                139                 :                : 
                                140                 :                :     /* DecodingWorkerShared is in this segment. */
                                141                 :                :     dsm_segment *seg;
                                142                 :                : 
                                143                 :                :     /* Handle of the error queue. */
                                144                 :                :     shm_mq_handle *error_mqh;
                                145                 :                : } DecodingWorker;
                                146                 :                : 
                                147                 :                : /* Pointer to currently running decoding worker. */
                                148                 :                : static DecodingWorker *decoding_worker = NULL;
                                149                 :                : 
                                150                 :                : /*
                                151                 :                :  * Is there a message sent by a repack worker that the backend needs to
                                152                 :                :  * receive?
                                153                 :                :  */
                                154                 :                : volatile sig_atomic_t RepackMessagePending = false;
                                155                 :                : 
                                156                 :                : static LOCKMODE RepackLockLevel(bool concurrent);
                                157                 :                : static bool cluster_rel_recheck(RepackCommand cmd, Relation OldHeap,
                                158                 :                :                                 Oid indexOid, Oid userid, LOCKMODE lmode,
                                159                 :                :                                 int options);
                                160                 :                : static void check_concurrent_repack_requirements(Relation rel,
                                161                 :                :                                                  Oid *ident_idx_p);
                                162                 :                : static void check_index_requirements(Relation rel, RepackCommand cmd);
                                163                 :                : static void rebuild_relation(Relation OldHeap, Relation index, bool verbose,
                                164                 :                :                              Oid ident_idx);
                                165                 :                : static void copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex,
                                166                 :                :                             Snapshot snapshot,
                                167                 :                :                             bool verbose,
                                168                 :                :                             bool *pSwapToastByContent,
                                169                 :                :                             TransactionId *pFreezeXid,
                                170                 :                :                             MultiXactId *pCutoffMulti);
                                171                 :                : static List *get_tables_to_repack(RepackCommand cmd, bool usingindex,
                                172                 :                :                                   MemoryContext permcxt);
                                173                 :                : static List *get_tables_to_repack_partitioned(RepackStmt *stmt,
                                174                 :                :                                               Relation rel,
                                175                 :                :                                               MemoryContext permcxt);
                                176                 :                : static bool repack_is_permitted_for_relation(RepackCommand cmd,
                                177                 :                :                                              Oid relid, Oid userid,
                                178                 :                :                                              bool already_locked);
                                179                 :                : 
                                180                 :                : static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
                                181                 :                : static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
                                182                 :                :                                     ChangeContext *chgcxt);
                                183                 :                : static void apply_concurrent_update(Relation rel, TupleTableSlot *spilled_tuple,
                                184                 :                :                                     TupleTableSlot *ondisk_tuple,
                                185                 :                :                                     ChangeContext *chgcxt);
                                186                 :                : static void apply_concurrent_delete(Relation rel, TupleTableSlot *slot);
                                187                 :                : static void restore_tuple(BufFile *file, Relation relation,
                                188                 :                :                           TupleTableSlot *slot);
                                189                 :                : static void adjust_toast_pointers(Relation relation, TupleTableSlot *dest,
                                190                 :                :                                   TupleTableSlot *src);
                                191                 :                : static bool find_target_tuple(Relation rel, ChangeContext *chgcxt,
                                192                 :                :                               TupleTableSlot *locator,
                                193                 :                :                               TupleTableSlot *retrieved);
                                194                 :                : static bool identity_key_equal(ChangeContext *chgcxt,
                                195                 :                :                                TupleTableSlot *locator,
                                196                 :                :                                TupleTableSlot *candidate);
                                197                 :                : static void process_concurrent_changes(XLogRecPtr end_of_wal,
                                198                 :                :                                        ChangeContext *chgcxt,
                                199                 :                :                                        bool done);
                                200                 :                : static void initialize_change_context(ChangeContext *chgcxt,
                                201                 :                :                                       Relation relation,
                                202                 :                :                                       Oid ident_index_id);
                                203                 :                : static void release_change_context(ChangeContext *chgcxt);
                                204                 :                : static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
                                205                 :                :                                                Oid identIdx,
                                206                 :                :                                                TransactionId frozenXid,
                                207                 :                :                                                MultiXactId cutoffMulti);
                                208                 :                : static List *build_new_indexes(Relation NewHeap, Relation OldHeap, List *OldIndexes);
                                209                 :                : static void copy_index_constraints(Relation old_index, Oid new_index_id,
                                210                 :                :                                    Oid new_heap_id);
                                211                 :                : static void copy_attribute_defaults(Oid old_heap_oid, Oid new_heap_oid);
                                212                 :                : static Relation process_single_relation(RepackStmt *stmt,
                                213                 :                :                                         LOCKMODE lockmode,
                                214                 :                :                                         bool isTopLevel,
                                215                 :                :                                         ClusterParams *params);
                                216                 :                : static Oid  determine_clustered_index(Relation rel, bool usingindex,
                                217                 :                :                                       const char *indexname);
                                218                 :                : 
                                219                 :                : static void start_repack_decoding_worker(Oid relid);
                                220                 :                : static void wait_for_repack_decoding_worker(void);
                                221                 :                : static void stop_repack_decoding_worker(void);
                                222                 :                : static void stop_repack_decoding_worker_cb(int code, Datum arg);
                                223                 :                : static Snapshot get_initial_snapshot(DecodingWorker *worker);
                                224                 :                : 
                                225                 :                : static void ProcessRepackMessage(StringInfo msg);
                                226                 :                : static const char *RepackCommandAsString(RepackCommand cmd);
                                227                 :                : 
                                228                 :                : 
                                229                 :                : /*
                                230                 :                :  * The repack code allows for processing multiple tables at once. Because
                                231                 :                :  * of this, we cannot just run everything on a single transaction, or we
                                232                 :                :  * would be forced to acquire exclusive locks on all the tables being
                                233                 :                :  * clustered, simultaneously --- very likely leading to deadlock.
                                234                 :                :  *
                                235                 :                :  * To solve this we follow a similar strategy to VACUUM code, processing each
                                236                 :                :  * relation in a separate transaction. For this to work, we need to:
                                237                 :                :  *
                                238                 :                :  *  - provide a separate memory context so that we can pass information in
                                239                 :                :  *    a way that survives across transactions
                                240                 :                :  *  - start a new transaction every time a new relation is clustered
                                241                 :                :  *  - check for validity of the information on to-be-clustered relations,
                                242                 :                :  *    as someone might have deleted a relation behind our back, or
                                243                 :                :  *    clustered one on a different index
                                244                 :                :  *  - end the transaction
                                245                 :                :  *
                                246                 :                :  * The single-relation case does not have any such overhead.
                                247                 :                :  *
                                248                 :                :  * We also allow a relation to be repacked following an index, but without
                                249                 :                :  * naming a specific one.  In that case, the indisclustered bit will be
                                250                 :                :  * looked up, and an ERROR will be thrown if no so-marked index is found.
                                251                 :                :  */
                                252                 :                : void
  194 alvherre@kurilemu.de      253                 :CBC         265 : ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
                                254                 :                : {
 2071 michael@paquier.xyz       255                 :            265 :     ClusterParams params = {0};
 1632 alvherre@alvh.no-ip.      256                 :            265 :     Relation    rel = NULL;
                                257                 :                :     MemoryContext repack_context;
                                258                 :                :     LOCKMODE    lockmode;
                                259                 :                :     List       *rtcs;
  125 fujii@postgresql.org      260                 :            265 :     bool        verbose = false;
                                261                 :            265 :     bool        analyze = false;
                                262                 :            265 :     bool        concurrently = false;
                                263                 :                : 
                                264                 :                :     /* Parse option list */
  194 alvherre@kurilemu.de      265   [ +  +  +  +  :            576 :     foreach_node(DefElem, opt, stmt->params)
                                              +  + ]
                                266                 :                :     {
 2117 michael@paquier.xyz       267         [ +  + ]:             46 :         if (strcmp(opt->defname, "verbose") == 0)
  125 fujii@postgresql.org      268                 :              9 :             verbose = defGetBoolean(opt);
  194 alvherre@kurilemu.de      269         [ +  + ]:             37 :         else if (strcmp(opt->defname, "analyze") == 0 ||
                                270         [ -  + ]:             21 :                  strcmp(opt->defname, "analyse") == 0)
                                271                 :                :         {
   38 nathan@postgresql.or      272         [ -  + ]:             16 :             if (stmt->command != REPACK_COMMAND_REPACK)
   38 nathan@postgresql.or      273         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                274                 :                :                         errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                275                 :                :                         errmsg("ANALYZE option not supported for %s",
                                276                 :                :                                RepackCommandAsString(stmt->command)));
  125 fujii@postgresql.org      277                 :CBC          16 :             analyze = defGetBoolean(opt);
                                278                 :                :         }
                                279         [ +  - ]:             21 :         else if (strcmp(opt->defname, "concurrently") == 0)
                                280                 :                :         {
  167 alvherre@kurilemu.de      281         [ -  + ]:             21 :             if (stmt->command != REPACK_COMMAND_REPACK)
  167 alvherre@kurilemu.de      282         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                283                 :                :                         errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                284                 :                :                         errmsg("CONCURRENTLY option not supported for %s",
                                285                 :                :                                RepackCommandAsString(stmt->command)));
  125 fujii@postgresql.org      286                 :CBC          21 :             concurrently = defGetBoolean(opt);
                                287                 :                :         }
                                288                 :                :         else
 2117 michael@paquier.xyz       289         [ #  # ]:UBC           0 :             ereport(ERROR,
                                290                 :                :                     errcode(ERRCODE_SYNTAX_ERROR),
                                291                 :                :                     errmsg("unrecognized %s option \"%s\"",
                                292                 :                :                            RepackCommandAsString(stmt->command),
                                293                 :                :                            opt->defname),
                                294                 :                :                     parser_errposition(pstate, opt->location));
                                295                 :                :     }
                                296                 :                : 
  125 fujii@postgresql.org      297                 :CBC         530 :     params.options |=
                                298                 :            530 :         (verbose ? CLUOPT_VERBOSE : 0) |
                                299         [ +  + ]:            265 :         (analyze ? CLUOPT_ANALYZE : 0) |
                                300         [ +  + ]:            265 :         (concurrently ? CLUOPT_CONCURRENT : 0);
                                301                 :                : 
                                302                 :                :     /* Determine the lock mode to use. */
  167 alvherre@kurilemu.de      303                 :            265 :     lockmode = RepackLockLevel((params.options & CLUOPT_CONCURRENT) != 0);
                                304                 :                : 
                                305         [ +  + ]:            265 :     if ((params.options & CLUOPT_CONCURRENT) != 0)
                                306                 :                :     {
                                307                 :                :         /*
                                308                 :                :          * In concurrent mode, make sure we're not in a transaction block.
                                309                 :                :          *
                                310                 :                :          * The reason is that repack_setup_logical_decoding() could wait
                                311                 :                :          * indefinitely for our XID to complete. (The deadlock detector would
                                312                 :                :          * not recognize it because we'd be waiting for ourselves, i.e. no
                                313                 :                :          * real lock conflict.) It would be possible to run in a transaction
                                314                 :                :          * block if we had no XID, but this restriction is simpler for users
                                315                 :                :          * to understand and we don't lose any functionality.
                                316                 :                :          */
                                317                 :             21 :         PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
                                318                 :                :     }
   12                           319         [ +  + ]:            244 :     else if ((params.options & CLUOPT_ANALYZE) != 0)
                                320                 :                :     {
                                321                 :                :         /*
                                322                 :                :          * With ANALYZE, process_single_relation() would commit the current
                                323                 :                :          * transaction and start a new one, which would break our state if
                                324                 :                :          * we're in a transaction block or PL-execution environment.  Reject
                                325                 :                :          * the option in that case.  It may be possible to remove this
                                326                 :                :          * restriction in the future.
                                327                 :                :          */
                                328                 :             16 :         PreventInTransactionBlock(isTopLevel, "REPACK (ANALYZE)");
                                329                 :                :     }
                                330                 :                : 
                                331                 :                :     /*
                                332                 :                :      * If a single relation is specified, process it and we're done ... unless
                                333                 :                :      * the relation is a partitioned table, in which case we fall through.
                                334                 :                :      */
 8665 tgl@sss.pgh.pa.us         335         [ +  + ]:            257 :     if (stmt->relation != NULL)
                                336                 :                :     {
  167 alvherre@kurilemu.de      337                 :            239 :         rel = process_single_relation(stmt, lockmode, isTopLevel, &params);
  194                           338         [ +  + ]:            190 :         if (rel == NULL)
                                339                 :            157 :             return;             /* all done */
                                340                 :                :     }
                                341                 :                : 
                                342                 :                :     /*
                                343                 :                :      * Don't allow ANALYZE in the multiple-relation case for now.  Maybe we
                                344                 :                :      * can add support for this later.
                                345                 :                :      */
                                346         [ -  + ]:             51 :     if (params.options & CLUOPT_ANALYZE)
  194 alvherre@kurilemu.de      347         [ #  # ]:UBC           0 :         ereport(ERROR,
                                348                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                349                 :                :                 errmsg("cannot execute %s on multiple tables",
                                350                 :                :                        "REPACK (ANALYZE)"));
                                351                 :                : 
                                352                 :                :     /*
                                353                 :                :      * By here, we know we are in a multi-table situation.
                                354                 :                :      *
                                355                 :                :      * Concurrent processing is currently considered rather special (e.g. in
                                356                 :                :      * terms of resources consumed) so it is not performed in bulk.
                                357                 :                :      */
  167 alvherre@kurilemu.de      358         [ +  + ]:CBC          51 :     if (params.options & CLUOPT_CONCURRENT)
                                359                 :                :     {
                                360         [ +  - ]:              1 :         if (rel != NULL)
                                361                 :                :         {
                                362         [ -  + ]:              1 :             Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
                                363         [ +  - ]:              1 :             ereport(ERROR,
                                364                 :                :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                365                 :                :                     errmsg("%s is not supported for partitioned tables",
                                366                 :                :                            "REPACK (CONCURRENTLY)"),
                                367                 :                :                     errhint("Consider running the command on individual partitions."));
                                368                 :                :         }
                                369                 :                :         else
  167 alvherre@kurilemu.de      370         [ #  # ]:UBC           0 :             ereport(ERROR,
                                371                 :                :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                372                 :                :                     errmsg("%s requires an explicit table name",
                                373                 :                :                            "REPACK (CONCURRENTLY)"));
                                374                 :                :     }
                                375                 :                : 
                                376                 :                :     /*
                                377                 :                :      * In order to avoid holding locks for too long, we want to process each
                                378                 :                :      * table in its own transaction.  This forces us to disallow running
                                379                 :                :      * inside a user transaction block.
                                380                 :                :      */
  194 alvherre@kurilemu.de      381                 :CBC          50 :     PreventInTransactionBlock(isTopLevel, RepackCommandAsString(stmt->command));
                                382                 :                : 
                                383                 :                :     /* Also, we need a memory context to hold our list of relations */
                                384                 :             50 :     repack_context = AllocSetContextCreate(PortalContext,
                                385                 :                :                                            "Repack",
                                386                 :                :                                            ALLOCSET_DEFAULT_SIZES);
                                387                 :                : 
                                388                 :                :     /*
                                389                 :                :      * Since we open a new transaction for each relation, we have to check
                                390                 :                :      * that the relation still is what we think it is.
                                391                 :                :      *
                                392                 :                :      * In single-transaction CLUSTER, we don't need the overhead.
                                393                 :                :      */
                                394                 :             50 :     params.options |= CLUOPT_RECHECK;
                                395                 :                : 
                                396                 :                :     /*
                                397                 :                :      * If we don't have a relation yet, determine a relation list.  If we do,
                                398                 :                :      * then it must be a partitioned table, and we want to process its
                                399                 :                :      * partitions.  Note that we don't acquire any locks on these tables, so
                                400                 :                :      * the returned list must be treated with suspicion.
                                401                 :                :      */
                                402         [ +  + ]:             50 :     if (rel == NULL)
                                403                 :                :     {
                                404         [ -  + ]:             18 :         Assert(stmt->indexname == NULL);
                                405                 :             18 :         rtcs = get_tables_to_repack(stmt->command, stmt->usingindex,
                                406                 :                :                                     repack_context);
                                407                 :             18 :         params.options |= CLUOPT_RECHECK_ISCLUSTERED;
                                408                 :                :     }
                                409                 :                :     else
                                410                 :                :     {
   62                           411                 :             32 :         rtcs = get_tables_to_repack_partitioned(stmt, rel, repack_context);
                                412                 :             20 :         rel = NULL;             /* clobber no longer valid pointer */
                                413                 :                :     }
                                414                 :                : 
                                415                 :                :     /* Commit to get out of starting transaction */
 1632 alvherre@alvh.no-ip.      416                 :             38 :     PopActiveSnapshot();
                                417                 :             38 :     CommitTransactionCommand();
                                418                 :                : 
                                419                 :                :     /* Cluster the tables, each in a separate transaction */
  194 alvherre@kurilemu.de      420         [ -  + ]:             38 :     Assert(rel == NULL);
                                421   [ +  +  +  +  :            128 :     foreach_ptr(RelToCluster, rtc, rtcs)
                                              +  + ]
                                422                 :                :     {
                                423                 :                :         /* Start a new transaction for each relation. */
 8530 tgl@sss.pgh.pa.us         424                 :             52 :         StartTransactionCommand();
                                425                 :                : 
                                426                 :                :         /*
                                427                 :                :          * Open the target table.  It may have been dropped or replaced with
                                428                 :                :          * something different, in which case silently skip it.
                                429                 :                :          */
   72 alvherre@kurilemu.de      430                 :             52 :         rel = try_relation_open(rtc->tableOid, lockmode);
  194                           431         [ -  + ]:             52 :         if (rel == NULL)
                                432                 :                :         {
  194 alvherre@kurilemu.de      433                 :UBC           0 :             CommitTransactionCommand();
                                434                 :              0 :             continue;
                                435                 :                :         }
   72 alvherre@kurilemu.de      436         [ -  + ]:CBC          52 :         if (rel->rd_rel->relkind != RELKIND_RELATION &&
   72 alvherre@kurilemu.de      437         [ #  # ]:UBC           0 :             rel->rd_rel->relkind != RELKIND_MATVIEW)
                                438                 :                :         {
                                439                 :              0 :             relation_close(rel, lockmode);
                                440                 :              0 :             CommitTransactionCommand();
                                441                 :              0 :             continue;
                                442                 :                :         }
                                443                 :                : 
                                444                 :                :         /* functions in indexes may want a snapshot set */
 1632 alvherre@alvh.no-ip.      445                 :CBC          52 :         PushActiveSnapshot(GetTransactionSnapshot());
                                446                 :                : 
                                447                 :                :         /* Process this table */
  167 alvherre@kurilemu.de      448                 :             52 :         cluster_rel(stmt->command, rel, rtc->indexOid, &params, isTopLevel);
                                449                 :                :         /* cluster_rel closes the relation, but keeps lock */
                                450                 :                : 
 1632 alvherre@alvh.no-ip.      451                 :             52 :         PopActiveSnapshot();
                                452                 :             52 :         CommitTransactionCommand();
                                453                 :                :     }
                                454                 :                : 
                                455                 :                :     /* Start a new transaction for the cleanup work. */
  194 alvherre@kurilemu.de      456                 :             38 :     StartTransactionCommand();
                                457                 :                : 
                                458                 :                :     /* Clean up working storage */
                                459                 :             38 :     MemoryContextDelete(repack_context);
                                460                 :                : }
                                461                 :                : 
                                462                 :                : /*
                                463                 :                :  * In the non-concurrent case, we obtain AccessExclusiveLock throughout the
                                464                 :                :  * operation to avoid any lock-upgrade hazards.  In the concurrent case, we
                                465                 :                :  * grab ShareUpdateExclusiveLock (just like VACUUM) for most of the
                                466                 :                :  * processing and only acquire AccessExclusiveLock at the end, to swap the
                                467                 :                :  * relation -- supposedly for a short time.
                                468                 :                :  */
                                469                 :                : static LOCKMODE
  167                           470                 :           1603 : RepackLockLevel(bool concurrent)
                                471                 :                : {
                                472         [ +  + ]:           1603 :     if (concurrent)
                                473                 :             59 :         return ShareUpdateExclusiveLock;
                                474                 :                :     else
                                475                 :           1544 :         return AccessExclusiveLock;
                                476                 :                : }
                                477                 :                : 
                                478                 :                : /*
                                479                 :                :  * cluster_rel
                                480                 :                :  *
                                481                 :                :  * This clusters the table by creating a new, clustered table and
                                482                 :                :  * swapping the relfilenumbers of the new table and the old table, so
                                483                 :                :  * the OID of the original table is preserved.  Thus we do not lose
                                484                 :                :  * GRANT, inheritance nor references to this table.
                                485                 :                :  *
                                486                 :                :  * Indexes are rebuilt too, via REINDEX. Since we are effectively bulk-loading
                                487                 :                :  * the new table, it's better to create the indexes afterwards than to fill
                                488                 :                :  * them incrementally while we load the table.
                                489                 :                :  *
                                490                 :                :  * If indexOid is InvalidOid, the table will be rewritten in physical order
                                491                 :                :  * instead of index order.
                                492                 :                :  *
                                493                 :                :  * Note that, in the concurrent case, the function releases the lock at some
                                494                 :                :  * point, in order to get AccessExclusiveLock for the final steps (i.e. to
                                495                 :                :  * swap the relation files). To make things simpler, the caller should expect
                                496                 :                :  * OldHeap to be closed on return, regardless CLUOPT_CONCURRENT. (The
                                497                 :                :  * AccessExclusiveLock is kept till the end of the transaction.)
                                498                 :                :  *
                                499                 :                :  * 'cmd' indicates which command is being executed, to be used for error
                                500                 :                :  * messages.
                                501                 :                :  */
                                502                 :                : void
  194                           503                 :            462 : cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
                                504                 :                :             ClusterParams *params, bool isTopLevel)
                                505                 :                : {
  618 alvherre@alvh.no-ip.      506                 :            462 :     Oid         tableOid = RelationGetRelid(OldHeap);
                                507                 :                :     Relation    index;
                                508                 :                :     LOCKMODE    lmode;
                                509                 :                :     Oid         save_userid;
                                510                 :                :     int         save_sec_context;
                                511                 :                :     int         save_nestlevel;
 2071 michael@paquier.xyz       512                 :            462 :     bool        verbose = ((params->options & CLUOPT_VERBOSE) != 0);
                                513                 :            462 :     bool        recheck = ((params->options & CLUOPT_RECHECK) != 0);
  167 alvherre@kurilemu.de      514                 :            462 :     bool        concurrent = ((params->options & CLUOPT_CONCURRENT) != 0);
                                515                 :            462 :     Oid         ident_idx = InvalidOid;
   10 fujii@postgresql.org      516                 :            462 :     const int   progress_index[] = {
                                517                 :                :         PROGRESS_REPACK_COMMAND,
                                518                 :                :         PROGRESS_REPACK_INDEX_RELID
                                519                 :                :     };
                                520                 :            462 :     const int64 progress_values[] = {cmd, indexOid};
                                521                 :                : 
                                522                 :                :     /* Determine the lock mode to use. */
  167 alvherre@kurilemu.de      523                 :            462 :     lmode = RepackLockLevel(concurrent);
                                524                 :                : 
                                525                 :                :     /*
                                526                 :                :      * Check some preconditions in the concurrent case.  This also obtains the
                                527                 :                :      * replica index OID.
                                528                 :                :      */
                                529         [ +  + ]:            462 :     if (concurrent)
                                530                 :             20 :         check_concurrent_repack_requirements(OldHeap, &ident_idx);
                                531                 :                : 
                                532                 :                :     /*
                                533                 :                :      * Also check the state of indexes; this can abort the command for REPACK.
                                534                 :                :      * Historically this hasn't affected CLUSTER or VACUUM FULL, so don't do
                                535                 :                :      * it for those commands.
                                536                 :                :      */
    7                           537         [ +  + ]:            452 :     if (cmd == REPACK_COMMAND_REPACK)
                                538                 :             83 :         check_index_requirements(OldHeap, cmd);
                                539                 :                : 
                                540                 :                :     /* Check for user-requested abort. */
 8710 bruce@momjian.us          541         [ -  + ]:            450 :     CHECK_FOR_INTERRUPTS();
                                542                 :                : 
  194 alvherre@kurilemu.de      543                 :            450 :     pgstat_progress_start_command(PROGRESS_COMMAND_REPACK, tableOid);
                                544                 :                :     /* Report the ordering index even when using a sequential scan and sort. */
   10 fujii@postgresql.org      545                 :            450 :     pgstat_progress_update_multi_param(2, progress_index, progress_values);
                                546                 :                : 
                                547                 :                :     /*
                                548                 :                :      * Switch to the table owner's userid, so that any index functions are run
                                549                 :                :      * as that user.  Also lock down security-restricted operations and
                                550                 :                :      * arrange to make GUC variable changes local to this command.
                                551                 :                :      */
 1595 noah@leadboat.com         552                 :            450 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
                                553                 :            450 :     SetUserIdAndSecContext(OldHeap->rd_rel->relowner,
                                554                 :                :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
                                555                 :            450 :     save_nestlevel = NewGUCNestLevel();
  930 jdavis@postgresql.or      556                 :            450 :     RestrictSearchPath();
                                557                 :                : 
                                558                 :                :     /*
                                559                 :                :      * Recheck that the relation is still what it was when we started.
                                560                 :                :      *
                                561                 :                :      * Note that it's critical to skip this in single-relation CLUSTER;
                                562                 :                :      * otherwise, we would reject an attempt to cluster using a
                                563                 :                :      * not-previously-clustered index.
                                564                 :                :      */
  194 alvherre@kurilemu.de      565         [ +  + ]:            450 :     if (recheck &&
                                566         [ -  + ]:             52 :         !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid,
  167                           567                 :             52 :                              lmode, params->options))
  194 alvherre@kurilemu.de      568                 :UBC           0 :         goto out;
                                569                 :                : 
                                570                 :                :     /*
                                571                 :                :      * We allow repacking shared catalogs only when not using an index. It
                                572                 :                :      * would work to use an index in most respects, but the index would only
                                573                 :                :      * get marked as indisclustered in the current database, leading to
                                574                 :                :      * unexpected behavior if CLUSTER were later invoked in another database.
                                575                 :                :      */
 6069 tgl@sss.pgh.pa.us         576   [ +  +  -  + ]:CBC         450 :     if (OidIsValid(indexOid) && OldHeap->rd_rel->relisshared)
 6069 tgl@sss.pgh.pa.us         577         [ #  # ]:UBC           0 :         ereport(ERROR,
                                578                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                579                 :                :         /*- translator: first %s is name of a SQL command, eg. REPACK */
                                580                 :                :                 errmsg("cannot execute %s on a shared catalog",
                                581                 :                :                        RepackCommandAsString(cmd)));
                                582                 :                : 
                                583                 :                :     /*
                                584                 :                :      * The CONCURRENTLY case should have been rejected earlier because it does
                                585                 :                :      * not support system catalogs.
                                586                 :                :      */
  167 alvherre@kurilemu.de      587   [ +  +  -  + ]:CBC         450 :     Assert(!(OldHeap->rd_rel->relisshared && concurrent));
                                588                 :                : 
                                589                 :                :     /*
                                590                 :                :      * Don't process temp tables of other backends ... their local buffer
                                591                 :                :      * manager is not going to cope.
                                592                 :                :      */
 6069 tgl@sss.pgh.pa.us         593   [ +  +  -  + ]:            450 :     if (RELATION_IS_OTHER_TEMP(OldHeap))
  194 alvherre@kurilemu.de      594         [ #  # ]:UBC           0 :         ereport(ERROR,
                                595                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                596                 :                :         /*- translator: first %s is name of a SQL command, eg. REPACK */
                                597                 :                :                 errmsg("cannot execute %s on temporary tables of other sessions",
                                598                 :                :                        RepackCommandAsString(cmd)));
                                599                 :                : 
                                600                 :                :     /*
                                601                 :                :      * Also check for active uses of the relation in the current transaction,
                                602                 :                :      * including open scans and pending AFTER trigger events.
                                603                 :                :      */
  194 alvherre@kurilemu.de      604                 :CBC         450 :     CheckTableNotInUse(OldHeap, RepackCommandAsString(cmd));
                                605                 :                : 
                                606                 :                :     /* Check heap and index are valid to cluster on */
 6069 tgl@sss.pgh.pa.us         607         [ +  + ]:            450 :     if (OidIsValid(indexOid))
                                608                 :                :     {
                                609                 :                :         /* verify the index is good and lock it */
  167 alvherre@kurilemu.de      610                 :            159 :         check_index_is_clusterable(OldHeap, indexOid, lmode);
                                611                 :                :         /* also open it */
  618 alvherre@alvh.no-ip.      612                 :            159 :         index = index_open(indexOid, NoLock);
                                613                 :                :     }
                                614                 :                :     else
                                615                 :            291 :         index = NULL;
                                616                 :                : 
                                617                 :                :     /*
                                618                 :                :      * When allow_system_table_mods is turned off, we disallow repacking a
                                619                 :                :      * catalog on a particular index unless that's already the clustered index
                                620                 :                :      * for that catalog.
                                621                 :                :      *
                                622                 :                :      * XXX We don't check for this in CLUSTER, because it's historically been
                                623                 :                :      * allowed.
                                624                 :                :      */
  194 alvherre@kurilemu.de      625         [ +  + ]:            450 :     if (cmd != REPACK_COMMAND_CLUSTER &&
                                626   [ +  -  +  + ]:            318 :         !allowSystemTableMods && OidIsValid(indexOid) &&
                                627   [ +  +  +  - ]:             27 :         IsCatalogRelation(OldHeap) && !index->rd_index->indisclustered)
                                628         [ +  - ]:              4 :         ereport(ERROR,
                                629                 :                :                 errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                                630                 :                :                 errmsg("permission denied: \"%s\" is a system catalog",
                                631                 :                :                        RelationGetRelationName(OldHeap)),
                                632                 :                :                 errdetail("System catalogs can only be clustered by the index they're already clustered on, if any, unless \"%s\" is enabled.",
                                633                 :                :                           "allow_system_table_mods"));
                                634                 :                : 
                                635                 :                :     /*
                                636                 :                :      * Quietly ignore the request if this is a materialized view which has not
                                637                 :                :      * been populated from its query. No harm is done because there is no data
                                638                 :                :      * to deal with, and we don't want to throw an error if this is part of a
                                639                 :                :      * multi-relation request -- for example, CLUSTER was run on the entire
                                640                 :                :      * database.
                                641                 :                :      */
 4949 kgrittn@postgresql.o      642         [ +  + ]:            446 :     if (OldHeap->rd_rel->relkind == RELKIND_MATVIEW &&
 4885 tgl@sss.pgh.pa.us         643         [ +  - ]:              8 :         !RelationIsPopulated(OldHeap))
                                644                 :                :     {
  167 alvherre@kurilemu.de      645         [ +  - ]:              8 :         if (index)
                                646                 :              8 :             index_close(index, lmode);
                                647                 :              8 :         relation_close(OldHeap, lmode);
 1595 noah@leadboat.com         648                 :              8 :         goto out;
                                649                 :                :     }
                                650                 :                : 
 1632 alvherre@alvh.no-ip.      651   [ +  +  +  -  :            438 :     Assert(OldHeap->rd_rel->relkind == RELKIND_RELATION ||
                                              -  + ]
                                652                 :                :            OldHeap->rd_rel->relkind == RELKIND_MATVIEW ||
                                653                 :                :            OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE);
                                654                 :                : 
                                655                 :                :     /*
                                656                 :                :      * All predicate locks on the tuples or pages are about to be made
                                657                 :                :      * invalid, because we move tuples around.  Promote them to relation
                                658                 :                :      * locks.  Predicate locks on indexes will be promoted when they are
                                659                 :                :      * reindexed.
                                660                 :                :      *
                                661                 :                :      * During concurrent processing, the heap as well as its indexes stay in
                                662                 :                :      * operation, so we postpone this step until they are locked using
                                663                 :                :      * AccessExclusiveLock near the end of the processing.
                                664                 :                :      */
  167 alvherre@kurilemu.de      665         [ +  + ]:            438 :     if (!concurrent)
                                666                 :            429 :         TransferPredicateLocksToHeapRelation(OldHeap);
                                667                 :                : 
                                668                 :                :     /*
                                669                 :                :      * rebuild_relation does all the dirty work, and closes OldHeap and index,
                                670                 :                :      * if valid.
                                671                 :                :      *
                                672                 :                :      * In concurrent mode, make sure the worker terminates; normally it does
                                673                 :                :      * so by itself, but a PG_ENSURE_ERROR_CLEANUP callback ensures that this
                                674                 :                :      * happens even in case this backend dies early on a FATAL exit.  Normal
                                675                 :                :      * mode doesn't need that overhead.
                                676                 :                :      */
  124                           677         [ +  + ]:            438 :     if (concurrent)
                                678                 :                :     {
                                679         [ +  - ]:              9 :         PG_ENSURE_ERROR_CLEANUP(stop_repack_decoding_worker_cb, 0);
                                680                 :                :         {
                                681                 :              9 :             rebuild_relation(OldHeap, index, verbose, ident_idx);
                                682                 :                :         }
                                683         [ -  + ]:              9 :         PG_END_ENSURE_ERROR_CLEANUP(stop_repack_decoding_worker_cb, 0);
                                684                 :              9 :         stop_repack_decoding_worker();
                                685                 :                :     }
                                686                 :                :     else
                                687                 :            429 :         rebuild_relation(OldHeap, index, verbose, ident_idx);
                                688                 :                : 
 1595 noah@leadboat.com         689                 :            442 : out:
                                690                 :                :     /* Roll back any GUC changes executed by index functions */
                                691                 :            442 :     AtEOXact_GUC(false, save_nestlevel);
                                692                 :                : 
                                693                 :                :     /* Restore userid and security context */
                                694                 :            442 :     SetUserIdAndSecContext(save_userid, save_sec_context);
                                695                 :                : 
 2736 rhaas@postgresql.org      696                 :            442 :     pgstat_progress_end_command();
 8172 tgl@sss.pgh.pa.us         697                 :            442 : }
                                698                 :                : 
                                699                 :                : /*
                                700                 :                :  * Check if the table (and its index) still meets the requirements of
                                701                 :                :  * cluster_rel().
                                702                 :                :  */
                                703                 :                : static bool
  194 alvherre@kurilemu.de      704                 :             52 : cluster_rel_recheck(RepackCommand cmd, Relation OldHeap, Oid indexOid,
                                705                 :                :                     Oid userid, LOCKMODE lmode, int options)
                                706                 :                : {
                                707                 :             52 :     Oid         tableOid = RelationGetRelid(OldHeap);
                                708                 :                : 
   72                           709         [ -  + ]:             52 :     Assert(CheckRelationLockedByMe(OldHeap, lmode, false));
                                710                 :                : 
                                711                 :                :     /* Check that the user still has privileges for the relation */
   32                           712         [ -  + ]:             52 :     if (!repack_is_permitted_for_relation(cmd, tableOid, userid, true))
                                713                 :                :     {
  167 alvherre@kurilemu.de      714                 :UBC           0 :         relation_close(OldHeap, lmode);
  194                           715                 :              0 :         return false;
                                716                 :                :     }
                                717                 :                : 
                                718                 :                :     /*
                                719                 :                :      * Silently skip a temp table for a remote session.  Only doing this check
                                720                 :                :      * in the "recheck" case is appropriate (which currently means somebody is
                                721                 :                :      * executing a database-wide CLUSTER or on a partitioned table), because
                                722                 :                :      * there is another check in cluster() which will stop any attempt to
                                723                 :                :      * cluster remote temp tables by name.  There is another check in
                                724                 :                :      * cluster_rel which is redundant, but we leave it for extra safety.
                                725                 :                :      */
  194 alvherre@kurilemu.de      726   [ -  +  -  - ]:CBC          52 :     if (RELATION_IS_OTHER_TEMP(OldHeap))
                                727                 :                :     {
  167 alvherre@kurilemu.de      728                 :UBC           0 :         relation_close(OldHeap, lmode);
  194                           729                 :              0 :         return false;
                                730                 :                :     }
                                731                 :                : 
  194 alvherre@kurilemu.de      732         [ +  + ]:CBC          52 :     if (OidIsValid(indexOid))
                                733                 :                :     {
                                734                 :                :         /*
                                735                 :                :          * Check that the index still exists
                                736                 :                :          */
                                737         [ -  + ]:             32 :         if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(indexOid)))
                                738                 :                :         {
  167 alvherre@kurilemu.de      739                 :UBC           0 :             relation_close(OldHeap, lmode);
  194                           740                 :              0 :             return false;
                                741                 :                :         }
                                742                 :                : 
                                743                 :                :         /*
                                744                 :                :          * Check that the index is still the one with indisclustered set, if
                                745                 :                :          * needed.
                                746                 :                :          */
  194 alvherre@kurilemu.de      747         [ +  + ]:CBC          32 :         if ((options & CLUOPT_RECHECK_ISCLUSTERED) != 0 &&
                                748         [ -  + ]:              4 :             !get_index_isclustered(indexOid))
                                749                 :                :         {
  167 alvherre@kurilemu.de      750                 :UBC           0 :             relation_close(OldHeap, lmode);
  194                           751                 :              0 :             return false;
                                752                 :                :         }
                                753                 :                :     }
                                754                 :                : 
  194 alvherre@kurilemu.de      755                 :CBC          52 :     return true;
                                756                 :                : }
                                757                 :                : 
                                758                 :                : /*
                                759                 :                :  * Verify that the specified heap and index are valid to cluster on
                                760                 :                :  *
                                761                 :                :  * Side effect: obtains lock on the index.  The caller may
                                762                 :                :  * in some cases already have a lock of the same strength on the table, but
                                763                 :                :  * not in all cases so we can't rely on the table-level lock for
                                764                 :                :  * protection here.
                                765                 :                :  */
                                766                 :                : void
 1621 michael@paquier.xyz       767                 :            357 : check_index_is_clusterable(Relation OldHeap, Oid indexOid, LOCKMODE lockmode)
                                768                 :                : {
                                769                 :                :     Relation    OldIndex;
                                770                 :                : 
 5897 simon@2ndQuadrant.co      771                 :            357 :     OldIndex = index_open(indexOid, lockmode);
                                772                 :                : 
                                773                 :                :     /*
                                774                 :                :      * Check that index is in fact an index on the given relation
                                775                 :                :      */
 8806 tgl@sss.pgh.pa.us         776         [ +  - ]:            357 :     if (OldIndex->rd_index == NULL ||
 8172                           777         [ +  + ]:            357 :         OldIndex->rd_index->indrelid != RelationGetRelid(OldHeap))
 8463                           778         [ +  - ]:              4 :         ereport(ERROR,
                                779                 :                :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                                780                 :                :                  errmsg("\"%s\" is not an index for table \"%s\"",
                                781                 :                :                         RelationGetRelationName(OldIndex),
                                782                 :                :                         RelationGetRelationName(OldHeap))));
                                783                 :                : 
                                784                 :                :     /* Index AM must allow clustering */
 2799 andres@anarazel.de        785         [ +  + ]:            353 :     if (!OldIndex->rd_indam->amclusterable)
 6069 tgl@sss.pgh.pa.us         786         [ +  - ]:              4 :         ereport(ERROR,
                                787                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                788                 :                :                  errmsg("cannot cluster on index \"%s\" because access method does not support clustering",
                                789                 :                :                         RelationGetRelationName(OldIndex))));
                                790                 :                : 
                                791                 :                :     /*
                                792                 :                :      * Disallow clustering on incomplete indexes (those that might not index
                                793                 :                :      * every row of the relation).  We could relax this by making a separate
                                794                 :                :      * seqscan pass over the table to copy the missing rows, but that seems
                                795                 :                :      * expensive and tedious.
                                796                 :                :      */
 3098 andrew@dunslane.net       797         [ +  + ]:            349 :     if (!heap_attisnull(OldIndex->rd_indextuple, Anum_pg_index_indpred, NULL))
 8463 tgl@sss.pgh.pa.us         798         [ +  - ]:              4 :         ereport(ERROR,
                                799                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                800                 :                :                  errmsg("cannot cluster on partial index \"%s\"",
                                801                 :                :                         RelationGetRelationName(OldIndex))));
                                802                 :                : 
                                803                 :                :     /*
                                804                 :                :      * Disallow if index is left over from a failed CREATE INDEX CONCURRENTLY;
                                805                 :                :      * it might well not contain entries for every heap row, or might not even
                                806                 :                :      * be internally consistent.  (But note that we don't check indcheckxmin;
                                807                 :                :      * the worst consequence of following broken HOT chains would be that we
                                808                 :                :      * might put recently-dead tuples out-of-order in the new table, and there
                                809                 :                :      * is little harm in that.)
                                810                 :                :      */
 2824 peter_e@gmx.net           811         [ +  + ]:            345 :     if (!OldIndex->rd_index->indisvalid)
 6931 tgl@sss.pgh.pa.us         812         [ +  - ]:              4 :         ereport(ERROR,
                                813                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                814                 :                :                  errmsg("cannot cluster on invalid index \"%s\"",
                                815                 :                :                         RelationGetRelationName(OldIndex))));
                                816                 :                : 
                                817                 :                :     /* Drop relcache refcnt on OldIndex, but keep lock */
 7356                           818                 :            341 :     index_close(OldIndex, NoLock);
 8702 bruce@momjian.us          819                 :            341 : }
                                820                 :                : 
                                821                 :                : /*
                                822                 :                :  * mark_index_clustered: mark the specified index as the one clustered on
                                823                 :                :  *
                                824                 :                :  * With indexOid == InvalidOid, will mark all indexes of rel not-clustered.
                                825                 :                :  */
                                826                 :                : void
 4935 rhaas@postgresql.org      827                 :            194 : mark_index_clustered(Relation rel, Oid indexOid, bool is_internal)
                                828                 :                : {
                                829                 :                :     HeapTuple   indexTuple;
                                830                 :                :     Form_pg_index indexForm;
                                831                 :                :     Relation    pg_index;
                                832                 :                :     ListCell   *index;
                                833                 :                : 
  188 michael@paquier.xyz       834         [ -  + ]:            194 :     Assert(rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
                                835                 :                : 
                                836                 :                :     /*
                                837                 :                :      * If the index is already marked clustered, no need to do anything.
                                838                 :                :      */
 8170 tgl@sss.pgh.pa.us         839         [ +  + ]:            194 :     if (OidIsValid(indexOid))
                                840                 :                :     {
 2358 michael@paquier.xyz       841         [ +  + ]:            186 :         if (get_index_isclustered(indexOid))
 8170 tgl@sss.pgh.pa.us         842                 :             39 :             return;
                                843                 :                :     }
                                844                 :                : 
                                845                 :                :     /*
                                846                 :                :      * Check each index of the relation and set/clear the bit as needed.
                                847                 :                :      */
 2799 andres@anarazel.de        848                 :            155 :     pg_index = table_open(IndexRelationId, RowExclusiveLock);
                                849                 :                : 
 8170 tgl@sss.pgh.pa.us         850   [ +  -  +  +  :            464 :     foreach(index, RelationGetIndexList(rel))
                                              +  + ]
                                851                 :                :     {
 8057 bruce@momjian.us          852                 :            309 :         Oid         thisIndexOid = lfirst_oid(index);
                                853                 :                : 
 6062 rhaas@postgresql.org      854                 :            309 :         indexTuple = SearchSysCacheCopy1(INDEXRELID,
                                855                 :                :                                          ObjectIdGetDatum(thisIndexOid));
 8170 tgl@sss.pgh.pa.us         856         [ -  + ]:            309 :         if (!HeapTupleIsValid(indexTuple))
 8170 tgl@sss.pgh.pa.us         857         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
 8170 tgl@sss.pgh.pa.us         858                 :CBC         309 :         indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
                                859                 :                : 
                                860                 :                :         /*
                                861                 :                :          * Unset the bit if set.  We know it's wrong because we checked this
                                862                 :                :          * earlier.
                                863                 :                :          */
                                864         [ +  + ]:            309 :         if (indexForm->indisclustered)
                                865                 :                :         {
                                866                 :             20 :             indexForm->indisclustered = false;
 3519 alvherre@alvh.no-ip.      867                 :             20 :             CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
                                868                 :                :         }
 8170 tgl@sss.pgh.pa.us         869         [ +  + ]:            289 :         else if (thisIndexOid == indexOid)
                                870                 :                :         {
                                871                 :                :             /* this was checked earlier, but let's be real sure */
 2824 peter_e@gmx.net           872         [ -  + ]:            147 :             if (!indexForm->indisvalid)
 5044 tgl@sss.pgh.pa.us         873         [ #  # ]:UBC           0 :                 elog(ERROR, "cannot cluster on invalid index %u", indexOid);
 8170 tgl@sss.pgh.pa.us         874                 :CBC         147 :             indexForm->indisclustered = true;
 3519 alvherre@alvh.no-ip.      875                 :            147 :             CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
                                876                 :                :         }
                                877                 :                : 
 4935 rhaas@postgresql.org      878         [ -  + ]:            309 :         InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
                                879                 :                :                                      InvalidOid, is_internal);
                                880                 :                : 
 8170 tgl@sss.pgh.pa.us         881                 :            309 :         heap_freetuple(indexTuple);
                                882                 :                :     }
                                883                 :                : 
 2799 andres@anarazel.de        884                 :            155 :     table_close(pg_index, RowExclusiveLock);
                                885                 :                : }
                                886                 :                : 
                                887                 :                : /*
                                888                 :                :  * check_index_requirements: verify index state on relation being processed
                                889                 :                :  *
                                890                 :                :  * Throw an error if any incompletely-built indexes are found.
                                891                 :                :  *
                                892                 :                :  * Indexes that are not ready for inserts, such as ones left behind by failed
                                893                 :                :  * CREATE INDEX CONCURRENTLY, are not maintained by DML.  Indexes that aren't
                                894                 :                :  * marked valid could have been in the middle of validation when their build
                                895                 :                :  * failed, and thus it's not certain that they could be built.  In both cases,
                                896                 :                :  * attempting to rebuild may fail altogether.  Throwing an error here forces
                                897                 :                :  * the user to take action on these indexes separately from the table
                                898                 :                :  * reconstruction, which prevents perpetuating them for no reason.
                                899                 :                :  */
                                900                 :                : static void
    7 alvherre@kurilemu.de      901                 :             83 : check_index_requirements(Relation rel, RepackCommand cmd)
                                902                 :                : {
                                903                 :                :     Relation    indrel;
                                904                 :                :     SysScanDesc indscan;
                                905                 :                :     ScanKeyData skey;
                                906                 :                :     HeapTuple   htup;
                                907                 :             83 :     int         num_invalid_idxs = 0;
                                908                 :                :     StringInfoData dest;
                                909                 :                : 
                                910                 :             83 :     initStringInfo(&dest);
                                911                 :                : 
                                912                 :                :     /* Prepare to scan pg_index for entries having indrelid = this rel. */
                                913                 :             83 :     ScanKeyInit(&skey,
                                914                 :                :                 Anum_pg_index_indrelid,
                                915                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                                916                 :                :                 ObjectIdGetDatum(RelationGetRelid(rel)));
                                917                 :                : 
                                918                 :             83 :     indrel = table_open(IndexRelationId, AccessShareLock);
                                919                 :             83 :     indscan = systable_beginscan(indrel, IndexIndrelidIndexId, true,
                                920                 :                :                                  NULL, 1, &skey);
                                921                 :                : 
                                922         [ +  + ]:            334 :     while (HeapTupleIsValid(htup = systable_getnext(indscan)))
                                923                 :                :     {
                                924                 :            168 :         Form_pg_index index = (Form_pg_index) GETSTRUCT(htup);
                                925                 :                : 
    5                           926         [ +  + ]:            168 :         if (!index->indisvalid)
                                927                 :                :         {
    7                           928         [ +  + ]:              4 :             if (num_invalid_idxs == 0)
                                929                 :              2 :                 appendStringInfo(&dest, _("\"%s\""), get_rel_name(index->indexrelid));
                                930                 :                :             else
                                931                 :              2 :                 appendStringInfo(&dest, _(", \"%s\""), get_rel_name(index->indexrelid));
                                932                 :              4 :             num_invalid_idxs++;
                                933                 :                :         }
                                934                 :                :     }
                                935                 :             83 :     systable_endscan(indscan);
                                936                 :             83 :     table_close(indrel, AccessShareLock);
                                937                 :                : 
                                938         [ +  + ]:             83 :     if (num_invalid_idxs > 0)
                                939         [ +  - ]:              2 :         ereport(ERROR,
                                940                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                941                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                                942                 :                :                        RepackCommandAsString(cmd), RelationGetRelationName(rel)),
                                943                 :                :                 errdetail_plural("An invalid index cannot be processed correctly: %s.",
                                944                 :                :                                  "Some invalid indexes cannot be processed correctly: %s.",
                                945                 :                :                                  num_invalid_idxs,
                                946                 :                :                                  dest.data),
                                947                 :                :                 errhint("Use DROP INDEX or REINDEX."));
                                948                 :             81 : }
                                949                 :                : 
                                950                 :                : /*
                                951                 :                :  * Check if the CONCURRENTLY option is legal for the relation.
                                952                 :                :  *
                                953                 :                :  * *Ident_idx_p receives OID of the identity index.
                                954                 :                :  */
                                955                 :                : static void
  167                           956                 :             20 : check_concurrent_repack_requirements(Relation rel, Oid *ident_idx_p)
                                957                 :                : {
                                958                 :                :     char        relpersistence,
                                959                 :                :                 replident;
                                960                 :                :     Oid         ident_idx;
                                961                 :                : 
  115                           962         [ -  + ]:             20 :     if (wal_level < WAL_LEVEL_REPLICA)
  115 alvherre@kurilemu.de      963         [ #  # ]:UBC           0 :         ereport(ERROR,
                                964                 :                :                 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                965                 :                :                 errmsg("cannot execute %s in this configuration",
                                966                 :                :                        "REPACK (CONCURRENTLY)"),
                                967                 :                :                 errdetail("This operation requires \"wal_level\" to be set to \"replica\" or higher."));
                                968                 :                : 
                                969                 :                :     /*
                                970                 :                :      * A table AM that doesn't support logical decoding would cause REPACK
                                971                 :                :      * (CONCURRENTLY) to silently lose the changes made during the rewrite.
                                972                 :                :      * Nothing in TableAmRoutine tells us whether it does, so for now restrict
                                973                 :                :      * to heap. Check the routine rather than the AM OID, so that an AM
                                974                 :                :      * reusing the heap handler still works.
                                975                 :                :      */
   12 msawada@postgresql.o      976         [ -  + ]:CBC          20 :     if (rel->rd_tableam != GetHeapamTableAmRoutine())
   12 msawada@postgresql.o      977         [ #  # ]:UBC           0 :         ereport(ERROR,
                                978                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                979                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                                980                 :                :                        "REPACK (CONCURRENTLY)", RelationGetRelationName(rel)),
                                981                 :                :                 errdetail("This operation is only supported for the \"heap\" access method."));
                                982                 :                : 
                                983                 :                :     /* Data changes in system relations are not logically decoded. */
  167 alvherre@kurilemu.de      984         [ +  + ]:CBC          20 :     if (IsCatalogRelation(rel))
                                985         [ +  - ]:              1 :         ereport(ERROR,
                                986                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                987                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                                988                 :                :                        "REPACK (CONCURRENTLY)", RelationGetRelationName(rel)),
                                989                 :                :                 errdetail("This operation is not supported for system catalogs."));
                                990                 :                : 
                                991                 :                :     /*
                                992                 :                :      * REPACK (CONCURRENTLY) is not MVCC-safe; it doesn't preserve visibility
                                993                 :                :      * information, which logical decoding needs because it reads user catalog
                                994                 :                :      * tables under a historic snapshot. Removing this check requires making
                                995                 :                :      * it MVCC-safe and logical rewrite mappings.
                                996                 :                :      */
   12 msawada@postgresql.o      997   [ +  +  -  +  :             19 :     if (RelationIsUsedAsCatalogTable(rel))
                                        -  -  +  + ]
                                998         [ +  - ]:              1 :         ereport(ERROR,
                                999                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1000                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                               1001                 :                :                        "REPACK (CONCURRENTLY)", RelationGetRelationName(rel)),
                               1002                 :                :                 errdetail("This operation is not supported for user catalog tables."));
                               1003                 :                : 
                               1004                 :                :     /*
                               1005                 :                :      * reorderbuffer.c does not seem to handle processing of TOAST relation
                               1006                 :                :      * alone.
                               1007                 :                :      */
  167 alvherre@kurilemu.de     1008         [ +  + ]:             18 :     if (IsToastRelation(rel))
                               1009         [ +  - ]:              1 :         ereport(ERROR,
                               1010                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1011                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                               1012                 :                :                        "REPACK (CONCURRENTLY)", RelationGetRelationName(rel)),
                               1013                 :                :                 errdetail("This operation is not supported for TOAST tables."));
                               1014                 :                : 
                               1015                 :             17 :     relpersistence = rel->rd_rel->relpersistence;
                               1016         [ +  + ]:             17 :     if (relpersistence != RELPERSISTENCE_PERMANENT)
                               1017         [ +  - ]:              2 :         ereport(ERROR,
                               1018                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1019                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                               1020                 :                :                        "REPACK (CONCURRENTLY)", RelationGetRelationName(rel)),
                               1021                 :                :                 errdetail("This operation is only supported for permanent relations."));
                               1022                 :                : 
                               1023                 :                :     /* A materialized view produces no logically decoded changes. */
   11                          1024         [ +  + ]:             15 :     if (rel->rd_rel->relkind == RELKIND_MATVIEW)
                               1025         [ +  - ]:              1 :         ereport(ERROR,
                               1026                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1027                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                               1028                 :                :                        "REPACK (CONCURRENTLY)", RelationGetRelationName(rel)),
                               1029                 :                :                 errdetail_relkind_not_supported(rel->rd_rel->relkind));
                               1030                 :                : 
                               1031                 :                :     /*
                               1032                 :                :      * With NOTHING, WAL does not contain the old tuple; FULL is not yet
                               1033                 :                :      * supported.
                               1034                 :                :      */
  167                          1035                 :             14 :     replident = rel->rd_rel->relreplident;
  115                          1036   [ +  +  -  + ]:             14 :     if (replident == REPLICA_IDENTITY_NOTHING ||
                               1037                 :                :         replident == REPLICA_IDENTITY_FULL)
  167                          1038   [ +  -  +  - ]:              1 :         ereport(ERROR,
                               1039                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1040                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                               1041                 :                :                        "REPACK (CONCURRENTLY)", RelationGetRelationName(rel)),
                               1042                 :                :                 errdetail("This operation does not support tables with %s.",
                               1043                 :                :                           replident == REPLICA_IDENTITY_NOTHING ?
                               1044                 :                :                           "REPLICA IDENTITY NOTHING" : "REPLICA IDENTITY FULL"));
                               1045                 :                : 
                               1046                 :                :     /*
                               1047                 :                :      * Obtain the replica identity index to use.  If there isn't one, the
                               1048                 :                :      * table cannot be repacked concurrently.  (Replica identity FULL is not
                               1049                 :                :      * supported yet.)
                               1050                 :                :      */
    9                          1051                 :             13 :     ident_idx = RelationGetReplicaIndex(rel);
  167                          1052         [ +  + ]:             13 :     if (!OidIsValid(ident_idx))
                               1053                 :                :     {
                               1054                 :                :         /* This special case warrants its own error message */
  115                          1055   [ +  +  +  + ]:              3 :         if (OidIsValid(rel->rd_pkindex) && rel->rd_ispkdeferrable)
                               1056         [ +  - ]:              1 :             ereport(ERROR,
                               1057                 :                :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1058                 :                :                     errmsg("cannot execute %s on relation \"%s\"",
                               1059                 :                :                            "REPACK (CONCURRENTLY)",
                               1060                 :                :                            RelationGetRelationName(rel)),
                               1061                 :                :                     errdetail("This operation does not support deferrable primary keys."),
                               1062                 :                :                     errhint("Use ALTER TABLE ... REPLICA IDENTITY USING INDEX to designate another index as replica identity."));
                               1063                 :                : 
  167                          1064         [ +  - ]:              2 :         ereport(ERROR,
                               1065                 :                :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               1066                 :                :                 errmsg("cannot execute %s on relation \"%s\"",
                               1067                 :                :                        "REPACK (CONCURRENTLY)", RelationGetRelationName(rel)),
                               1068                 :                :                 errdetail("Relation \"%s\" has no identity index.",
                               1069                 :                :                           RelationGetRelationName(rel)));
                               1070                 :                :     }
                               1071                 :                : 
                               1072                 :             10 :     *ident_idx_p = ident_idx;
                               1073                 :             10 : }
                               1074                 :                : 
                               1075                 :                : 
                               1076                 :                : /*
                               1077                 :                :  * rebuild_relation: rebuild an existing relation in index or physical order
                               1078                 :                :  *
                               1079                 :                :  * OldHeap: table to rebuild.  See cluster_rel() for comments on the required
                               1080                 :                :  * lock strength.
                               1081                 :                :  *
                               1082                 :                :  * index: index to cluster by, or NULL to rewrite in physical order.
                               1083                 :                :  *
                               1084                 :                :  * ident_idx: identity index, to handle replaying of concurrent data changes
                               1085                 :                :  * to the new heap. InvalidOid if there's no CONCURRENTLY option.
                               1086                 :                :  *
                               1087                 :                :  * On entry, heap and index (if one is given) must be open, and the
                               1088                 :                :  * appropriate lock held on them -- AccessExclusiveLock for exclusive
                               1089                 :                :  * processing and ShareUpdateExclusiveLock for concurrent processing.
                               1090                 :                :  *
                               1091                 :                :  * On exit, they are closed, but still locked with AccessExclusiveLock.
                               1092                 :                :  * (The function handles the lock upgrade if 'concurrent' is true.)
                               1093                 :                :  */
                               1094                 :                : static void
                               1095                 :            438 : rebuild_relation(Relation OldHeap, Relation index, bool verbose,
                               1096                 :                :                  Oid ident_idx)
                               1097                 :                : {
 8665 tgl@sss.pgh.pa.us        1098                 :            438 :     Oid         tableOid = RelationGetRelid(OldHeap);
 1880 michael@paquier.xyz      1099                 :            438 :     Oid         accessMethod = OldHeap->rd_rel->relam;
 8106 tgl@sss.pgh.pa.us        1100                 :            438 :     Oid         tableSpace = OldHeap->rd_rel->reltablespace;
                               1101                 :                :     Oid         OIDNewHeap;
                               1102                 :                :     Relation    NewHeap;
                               1103                 :                :     char        relpersistence;
                               1104                 :                :     bool        swap_toast_by_content;
                               1105                 :                :     TransactionId frozenXid;
                               1106                 :                :     MultiXactId cutoffMulti;
  167 alvherre@kurilemu.de     1107                 :            438 :     bool        concurrent = OidIsValid(ident_idx);
                               1108                 :            438 :     Snapshot    snapshot = NULL;
                               1109                 :                : #if USE_ASSERT_CHECKING
                               1110                 :                :     LOCKMODE    lmode;
                               1111                 :                : 
                               1112                 :            438 :     lmode = RepackLockLevel(concurrent);
                               1113                 :                : 
                               1114         [ -  + ]:            438 :     Assert(CheckRelationLockedByMe(OldHeap, lmode, false));
                               1115   [ +  +  -  + ]:            438 :     Assert(index == NULL || CheckRelationLockedByMe(index, lmode, false));
                               1116                 :                : #endif
                               1117                 :                : 
                               1118         [ +  + ]:            438 :     if (concurrent)
                               1119                 :                :     {
                               1120                 :                :         /*
                               1121                 :                :          * The worker needs to be member of the locking group we're the leader
                               1122                 :                :          * of. We ought to become the leader before the worker starts. The
                               1123                 :                :          * worker will join the group as soon as it starts.
                               1124                 :                :          *
                               1125                 :                :          * This is to make sure that the deadlock described below is
                               1126                 :                :          * detectable by deadlock.c: if the worker waits for a transaction to
                               1127                 :                :          * complete and we are waiting for the worker output, then effectively
                               1128                 :                :          * we (i.e. this backend) are waiting for that transaction.
                               1129                 :                :          */
                               1130                 :              9 :         BecomeLockGroupLeader();
                               1131                 :                : 
                               1132                 :                :         /*
                               1133                 :                :          * Start the worker that decodes data changes applied while we're
                               1134                 :                :          * copying the table contents.
                               1135                 :                :          *
                               1136                 :                :          * Note that the worker has to wait for all transactions with XID
                               1137                 :                :          * already assigned to finish. If some of those transactions is
                               1138                 :                :          * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
                               1139                 :                :          * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
                               1140                 :                :          * Not sure this risk is worth unlocking/locking the table (and its
                               1141                 :                :          * clustering index) and checking again if it's still eligible for
                               1142                 :                :          * REPACK CONCURRENTLY.
                               1143                 :                :          */
                               1144                 :              9 :         start_repack_decoding_worker(tableOid);
                               1145                 :                : 
                               1146                 :                :         /*
                               1147                 :                :          * Wait until the worker has the initial snapshot and retrieve it.
                               1148                 :                :          */
                               1149                 :              9 :         snapshot = get_initial_snapshot(decoding_worker);
                               1150                 :                : 
                               1151                 :              9 :         PushActiveSnapshot(snapshot);
                               1152                 :                :     }
                               1153                 :                : 
                               1154                 :                :     /* for CLUSTER or REPACK USING INDEX, mark the index as the one to use */
  194                          1155         [ +  + ]:            438 :     if (index != NULL)
  618 alvherre@alvh.no-ip.     1156                 :            147 :         mark_index_clustered(OldHeap, RelationGetRelid(index), true);
                               1157                 :                : 
                               1158                 :                :     /* Remember info about rel before closing OldHeap */
 3487 tgl@sss.pgh.pa.us        1159                 :            438 :     relpersistence = OldHeap->rd_rel->relpersistence;
                               1160                 :                : 
                               1161                 :                :     /*
                               1162                 :                :      * Create the transient table that will receive the re-ordered data.
                               1163                 :                :      *
                               1164                 :                :      * OldHeap is already locked, so no need to lock it again.  make_new_heap
                               1165                 :                :      * obtains AccessExclusiveLock on the new heap and its toast table.
                               1166                 :                :      */
 4412 alvherre@alvh.no-ip.     1167                 :            438 :     OIDNewHeap = make_new_heap(tableOid, tableSpace,
                               1168                 :                :                                accessMethod,
                               1169                 :                :                                relpersistence,
                               1170                 :                :                                NoLock);
  618                          1171         [ -  + ]:            438 :     Assert(CheckRelationOidLockedByMe(OIDNewHeap, AccessExclusiveLock, false));
                               1172                 :            438 :     NewHeap = table_open(OIDNewHeap, NoLock);
                               1173                 :                : 
                               1174                 :                :     /*
                               1175                 :                :      * In concurrent mode, create a copy of the attribute defaults on the temp
                               1176                 :                :      * table, which the executor needs when replaying concurrent data changes.
                               1177                 :                :      */
   79 alvherre@kurilemu.de     1178         [ +  + ]:            438 :     if (concurrent)
                               1179                 :              9 :         copy_attribute_defaults(tableOid, OIDNewHeap);
                               1180                 :                : 
                               1181                 :                :     /* Copy the heap data into the new table in the desired order */
  167                          1182                 :            438 :     copy_table_data(NewHeap, OldHeap, index, snapshot, verbose,
                               1183                 :                :                     &swap_toast_by_content, &frozenXid, &cutoffMulti);
                               1184                 :                : 
                               1185                 :                :     /* The historic snapshot won't be needed anymore. */
                               1186         [ +  + ]:            438 :     if (snapshot)
                               1187                 :                :     {
                               1188                 :              9 :         PopActiveSnapshot();
                               1189                 :              9 :         UpdateActiveSnapshotCommandId();
                               1190                 :                :     }
                               1191                 :                : 
                               1192         [ +  + ]:            438 :     if (concurrent)
                               1193                 :                :     {
                               1194         [ -  + ]:              9 :         Assert(!swap_toast_by_content);
                               1195                 :                : 
                               1196                 :                :         /*
                               1197                 :                :          * Close the index, but keep the lock. Both heaps will be closed by
                               1198                 :                :          * the following call.
                               1199                 :                :          */
                               1200         [ +  + ]:              9 :         if (index)
                               1201                 :              3 :             index_close(index, NoLock);
                               1202                 :                : 
                               1203                 :              9 :         rebuild_relation_finish_concurrent(NewHeap, OldHeap, ident_idx,
                               1204                 :                :                                            frozenXid, cutoffMulti);
                               1205                 :                : 
                               1206                 :              9 :         pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                               1207                 :                :                                      PROGRESS_REPACK_PHASE_FINAL_CLEANUP);
                               1208                 :                :     }
                               1209                 :                :     else
                               1210                 :                :     {
                               1211                 :            429 :         bool        is_system_catalog = IsSystemRelation(OldHeap);
                               1212                 :                : 
                               1213                 :                :         /* Close relcache entries, but keep lock until transaction commit */
                               1214                 :            429 :         table_close(OldHeap, NoLock);
                               1215         [ +  + ]:            429 :         if (index)
                               1216                 :            144 :             index_close(index, NoLock);
                               1217                 :                : 
                               1218                 :                :         /*
                               1219                 :                :          * Close the new relation so it can be dropped as soon as the storage
                               1220                 :                :          * is swapped. The relation is not visible to others, so no need to
                               1221                 :                :          * unlock it explicitly.
                               1222                 :                :          */
                               1223                 :            429 :         table_close(NewHeap, NoLock);
                               1224                 :                : 
                               1225                 :                :         /*
                               1226                 :                :          * Swap the physical files of the target and transient tables, then
                               1227                 :                :          * rebuild the target's indexes and throw away the transient table.
                               1228                 :                :          */
                               1229                 :            429 :         finish_heap_swap(tableOid, OIDNewHeap, is_system_catalog,
                               1230                 :                :                          swap_toast_by_content, false, true,
                               1231                 :                :                          true,  /* reindex */
                               1232                 :                :                          frozenXid, cutoffMulti,
                               1233                 :                :                          relpersistence);
                               1234                 :                :     }
11030 scrappy@hub.org          1235                 :            434 : }
                               1236                 :                : 
                               1237                 :                : 
                               1238                 :                : /*
                               1239                 :                :  * Create the transient table that will be filled with new data during
                               1240                 :                :  * CLUSTER, ALTER TABLE, and similar operations.  The transient table
                               1241                 :                :  * duplicates the logical structure of the OldHeap; but will have the
                               1242                 :                :  * specified physical storage properties NewTableSpace, NewAccessMethod, and
                               1243                 :                :  * relpersistence.
                               1244                 :                :  *
                               1245                 :                :  * After this, the caller should load the new heap with transferred/modified
                               1246                 :                :  * data, then call finish_heap_swap to complete the operation.
                               1247                 :                :  */
                               1248                 :                : Oid
 1880 michael@paquier.xyz      1249                 :           1598 : make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, Oid NewAccessMethod,
                               1250                 :                :               char relpersistence, LOCKMODE lockmode)
                               1251                 :                : {
                               1252                 :                :     TupleDesc   OldHeapDesc;
                               1253                 :                :     char        NewHeapName[NAMEDATALEN];
                               1254                 :                :     Oid         OIDNewHeap;
                               1255                 :                :     Oid         toastid;
                               1256                 :                :     Relation    OldHeap;
                               1257                 :                :     HeapTuple   tuple;
                               1258                 :                :     Datum       reloptions;
                               1259                 :                :     bool        isNull;
                               1260                 :                :     Oid         namespaceid;
                               1261                 :                : 
 2799 andres@anarazel.de       1262                 :           1598 :     OldHeap = table_open(OIDOldHeap, lockmode);
10246 bruce@momjian.us         1263                 :           1598 :     OldHeapDesc = RelationGetDescr(OldHeap);
                               1264                 :                : 
                               1265                 :                :     /*
                               1266                 :                :      * Note that the NewHeap will not receive any of the defaults or
                               1267                 :                :      * constraints associated with the OldHeap; we don't need 'em, and there's
                               1268                 :                :      * no reason to spend cycles inserting them into the catalogs only to
                               1269                 :                :      * delete them.
                               1270                 :                :      */
                               1271                 :                : 
                               1272                 :                :     /*
                               1273                 :                :      * But we do want to use reloptions of the old heap for new heap.
                               1274                 :                :      */
 6062 rhaas@postgresql.org     1275                 :           1598 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(OIDOldHeap));
 7384 tgl@sss.pgh.pa.us        1276         [ -  + ]:           1598 :     if (!HeapTupleIsValid(tuple))
 7384 tgl@sss.pgh.pa.us        1277         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", OIDOldHeap);
 7384 tgl@sss.pgh.pa.us        1278                 :CBC        1598 :     reloptions = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
                               1279                 :                :                                  &isNull);
                               1280         [ +  + ]:           1598 :     if (isNull)
                               1281                 :           1481 :         reloptions = (Datum) 0;
                               1282                 :                : 
 4412 alvherre@alvh.no-ip.     1283         [ +  + ]:           1598 :     if (relpersistence == RELPERSISTENCE_TEMP)
 4814 kgrittn@postgresql.o     1284                 :             98 :         namespaceid = LookupCreationNamespace("pg_temp");
                               1285                 :                :     else
                               1286                 :           1500 :         namespaceid = RelationGetNamespace(OldHeap);
                               1287                 :                : 
                               1288                 :                :     /*
                               1289                 :                :      * Create the new heap, using a temporary name in the same namespace as
                               1290                 :                :      * the existing table.  NOTE: there is some risk of collision with user
                               1291                 :                :      * relnames.  Working around this seems more trouble than it's worth; in
                               1292                 :                :      * particular, we can't create the new heap in a different namespace from
                               1293                 :                :      * the old, or we will have problems with the TEMP status of temp tables.
                               1294                 :                :      *
                               1295                 :                :      * Note: the new heap is not a shared relation, even if we are rebuilding
                               1296                 :                :      * a shared rel.  However, we do make the new heap mapped if the source is
                               1297                 :                :      * mapped.  This simplifies swap_relation_files, and is absolutely
                               1298                 :                :      * necessary for rebuilding pg_class, for reasons explained there.
                               1299                 :                :      */
 6072 tgl@sss.pgh.pa.us        1300                 :           1598 :     snprintf(NewHeapName, sizeof(NewHeapName), "pg_temp_%u", OIDOldHeap);
                               1301                 :                : 
                               1302                 :           1598 :     OIDNewHeap = heap_create_with_catalog(NewHeapName,
                               1303                 :                :                                           namespaceid,
                               1304                 :                :                                           NewTableSpace,
                               1305                 :                :                                           InvalidOid,
                               1306                 :                :                                           InvalidOid,
                               1307                 :                :                                           InvalidOid,
 7695                          1308                 :           1598 :                                           OldHeap->rd_rel->relowner,
                               1309                 :                :                                           NewAccessMethod,
                               1310                 :                :                                           OldHeapDesc,
                               1311                 :                :                                           NIL,
                               1312                 :                :                                           RELKIND_RELATION,
                               1313                 :                :                                           relpersistence,
                               1314                 :                :                                           false,
 6069                          1315   [ +  +  +  -  :           1598 :                                           RelationIsMapped(OldHeap),
                                     +  -  +  +  +  
                                           -  +  + ]
                               1316                 :                :                                           ONCOMMIT_NOOP,
                               1317                 :                :                                           reloptions,
                               1318                 :                :                                           false,
                               1319                 :                :                                           true,
                               1320                 :                :                                           true,
                               1321                 :                :                                           OIDOldHeap,
 4219 alvherre@alvh.no-ip.     1322                 :           1598 :                                           NULL);
 5901 rhaas@postgresql.org     1323         [ -  + ]:           1598 :     Assert(OIDNewHeap != InvalidOid);
                               1324                 :                : 
 7385 bruce@momjian.us         1325                 :           1598 :     ReleaseSysCache(tuple);
                               1326                 :                : 
                               1327                 :                :     /*
                               1328                 :                :      * Advance command counter so that the newly-created relation's catalog
                               1329                 :                :      * tuples will be visible to table_open.
                               1330                 :                :      */
 9393 tgl@sss.pgh.pa.us        1331                 :           1598 :     CommandCounterIncrement();
                               1332                 :                : 
                               1333                 :                :     /*
                               1334                 :                :      * If necessary, create a TOAST table for the new relation.
                               1335                 :                :      *
                               1336                 :                :      * If the relation doesn't have a TOAST table already, we can't need one
                               1337                 :                :      * for the new relation.  The other way around is possible though: if some
                               1338                 :                :      * wide columns have been dropped, NewHeapCreateToastTable can decide that
                               1339                 :                :      * no TOAST table is needed for the new table.
                               1340                 :                :      *
                               1341                 :                :      * Note that NewHeapCreateToastTable ends with CommandCounterIncrement, so
                               1342                 :                :      * that the TOAST table will be visible for insertion.
                               1343                 :                :      */
 6439 alvherre@alvh.no-ip.     1344                 :           1598 :     toastid = OldHeap->rd_rel->reltoastrelid;
                               1345         [ +  + ]:           1598 :     if (OidIsValid(toastid))
                               1346                 :                :     {
                               1347                 :                :         /* keep the existing toast table's reloptions, if any */
 6062 rhaas@postgresql.org     1348                 :            595 :         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
 6439 alvherre@alvh.no-ip.     1349         [ -  + ]:            595 :         if (!HeapTupleIsValid(tuple))
 6439 alvherre@alvh.no-ip.     1350         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for relation %u", toastid);
 6439 alvherre@alvh.no-ip.     1351                 :CBC         595 :         reloptions = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
                               1352                 :                :                                      &isNull);
                               1353         [ +  - ]:            595 :         if (isNull)
                               1354                 :            595 :             reloptions = (Datum) 0;
                               1355                 :                : 
 1852 akapila@postgresql.o     1356                 :            595 :         NewHeapCreateToastTable(OIDNewHeap, reloptions, lockmode, toastid);
                               1357                 :                : 
 6439 alvherre@alvh.no-ip.     1358                 :            595 :         ReleaseSysCache(tuple);
                               1359                 :                :     }
                               1360                 :                : 
 2799 andres@anarazel.de       1361                 :           1598 :     table_close(OldHeap, NoLock);
                               1362                 :                : 
 9447 tgl@sss.pgh.pa.us        1363                 :           1598 :     return OIDNewHeap;
                               1364                 :                : }
                               1365                 :                : 
                               1366                 :                : /*
                               1367                 :                :  * Do the physical copying of table data.
                               1368                 :                :  *
                               1369                 :                :  * 'snapshot' and 'decoding_ctx': see table_relation_copy_for_cluster(). Pass
                               1370                 :                :  * iff concurrent processing is required.
                               1371                 :                :  *
                               1372                 :                :  * There are three output parameters:
                               1373                 :                :  * *pSwapToastByContent is set true if toast tables must be swapped by content.
                               1374                 :                :  * *pFreezeXid receives the TransactionId used as freeze cutoff point.
                               1375                 :                :  * *pCutoffMulti receives the MultiXactId used as a cutoff point.
                               1376                 :                :  */
                               1377                 :                : static void
  167 alvherre@kurilemu.de     1378                 :            438 : copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex,
                               1379                 :                :                 Snapshot snapshot, bool verbose, bool *pSwapToastByContent,
                               1380                 :                :                 TransactionId *pFreezeXid, MultiXactId *pCutoffMulti)
                               1381                 :                : {
                               1382                 :                :     Relation    relRelation;
                               1383                 :                :     HeapTuple   reltup;
                               1384                 :                :     Form_pg_class relform;
                               1385                 :                :     TupleDesc   oldTupDesc PG_USED_FOR_ASSERTS_ONLY;
                               1386                 :                :     TupleDesc   newTupDesc PG_USED_FOR_ASSERTS_ONLY;
                               1387                 :                :     VacuumParams params;
                               1388                 :                :     struct VacuumCutoffs cutoffs;
                               1389                 :                :     bool        use_sort;
 5827 tgl@sss.pgh.pa.us        1390                 :            438 :     double      num_tuples = 0,
                               1391                 :            438 :                 tups_vacuumed = 0,
                               1392                 :            438 :                 tups_recently_dead = 0;
                               1393                 :                :     BlockNumber num_pages;
                               1394         [ +  + ]:            438 :     int         elevel = verbose ? INFO : DEBUG2;
                               1395                 :                :     PGRUsage    ru0;
                               1396                 :                :     char       *nspname;
  167 alvherre@kurilemu.de     1397                 :            438 :     bool        concurrent = snapshot != NULL;
                               1398                 :                :     LOCKMODE    lmode;
                               1399                 :                : 
                               1400                 :            438 :     lmode = RepackLockLevel(concurrent);
                               1401                 :                : 
 5827 tgl@sss.pgh.pa.us        1402                 :            438 :     pg_rusage_init(&ru0);
                               1403                 :                : 
                               1404                 :                :     /* Store a copy of the namespace name for logging purposes */
 1861 dgustafsson@postgres     1405                 :            438 :     nspname = get_namespace_name(RelationGetNamespace(OldHeap));
                               1406                 :                : 
                               1407                 :                :     /*
                               1408                 :                :      * Their tuple descriptors should be exactly alike, but here we only need
                               1409                 :                :      * assume that they have the same number of columns.
                               1410                 :                :      */
 7896 tgl@sss.pgh.pa.us        1411                 :            438 :     oldTupDesc = RelationGetDescr(OldHeap);
                               1412                 :            438 :     newTupDesc = RelationGetDescr(NewHeap);
                               1413         [ -  + ]:            438 :     Assert(newTupDesc->natts == oldTupDesc->natts);
                               1414                 :                : 
                               1415                 :                :     /*
                               1416                 :                :      * If the OldHeap has a toast table, get lock on the toast table to keep
                               1417                 :                :      * it from being vacuumed.  This is needed because autovacuum processes
                               1418                 :                :      * toast tables independently of their main tables, with no lock on the
                               1419                 :                :      * latter.  If an autovacuum were to start on the toast table after we
                               1420                 :                :      * compute our OldestXmin below, it would use a later OldestXmin, and then
                               1421                 :                :      * possibly remove as DEAD toast tuples belonging to main tuples we think
                               1422                 :                :      * are only RECENTLY_DEAD.  Then we'd fail while trying to copy those
                               1423                 :                :      * tuples.
                               1424                 :                :      *
                               1425                 :                :      * We don't need to open the toast relation here, just lock it.  The lock
                               1426                 :                :      * will be held till end of transaction.
                               1427                 :                :      */
 5621                          1428         [ +  + ]:            438 :     if (OldHeap->rd_rel->reltoastrelid)
  167 alvherre@kurilemu.de     1429                 :            167 :         LockRelationOid(OldHeap->rd_rel->reltoastrelid, lmode);
                               1430                 :                : 
                               1431                 :                :     /*
                               1432                 :                :      * If both tables have TOAST tables, perform toast swap by content.  It is
                               1433                 :                :      * possible that the old table has a toast table but the new one doesn't,
                               1434                 :                :      * if toastable columns have been dropped.  In that case we have to do
                               1435                 :                :      * swap by links.  This is okay because swap by content is only essential
                               1436                 :                :      * for system catalogs, and we don't support schema changes for them.
                               1437                 :                :      */
                               1438   [ +  +  +  - ]:            438 :     if (OldHeap->rd_rel->reltoastrelid && NewHeap->rd_rel->reltoastrelid &&
                               1439         [ +  + ]:            167 :         !concurrent)
                               1440                 :                :     {
 6072 tgl@sss.pgh.pa.us        1441                 :            162 :         *pSwapToastByContent = true;
                               1442                 :                : 
                               1443                 :                :         /*
                               1444                 :                :          * When doing swap by content, any toast pointers written into NewHeap
                               1445                 :                :          * must use the old toast table's OID, because that's where the toast
                               1446                 :                :          * data will eventually be found.  Set this up by setting rd_toastoid.
                               1447                 :                :          * This also tells toast_save_datum() to preserve the toast value
                               1448                 :                :          * OIDs, which we want so as not to invalidate toast pointers in
                               1449                 :                :          * system catalog caches, and to avoid making multiple copies of a
                               1450                 :                :          * single toast value.
                               1451                 :                :          *
                               1452                 :                :          * Note that we must hold NewHeap open until we are done writing data,
                               1453                 :                :          * since the relcache will not guarantee to remember this setting once
                               1454                 :                :          * the relation is closed.  Also, this technique depends on the fact
                               1455                 :                :          * that no one will try to read from the NewHeap until after we've
                               1456                 :                :          * finished writing it and swapping the rels --- otherwise they could
                               1457                 :                :          * follow the toast pointers to the wrong place.  (It would actually
                               1458                 :                :          * work for values copied over from the old toast table, but not for
                               1459                 :                :          * any values that we toast which were previously not toasted.)
                               1460                 :                :          *
                               1461                 :                :          * This would not work with CONCURRENTLY because we may need to delete
                               1462                 :                :          * TOASTed tuples from the new heap. With this hack, we'd delete them
                               1463                 :                :          * from the old heap.
                               1464                 :                :          */
                               1465                 :            162 :         NewHeap->rd_toastoid = OldHeap->rd_rel->reltoastrelid;
                               1466                 :                :     }
                               1467                 :                :     else
                               1468                 :            276 :         *pSwapToastByContent = false;
                               1469                 :                : 
                               1470                 :                :     /*
                               1471                 :                :      * Compute xids used to freeze and weed out dead tuples and multixacts.
                               1472                 :                :      * Since we're going to rewrite the whole table anyway, there's no reason
                               1473                 :                :      * not to be aggressive about this.
                               1474                 :                :      */
 1397 pg@bowt.ie               1475                 :            438 :     memset(&params, 0, sizeof(VacuumParams));
  173 nathan@postgresql.or     1476                 :            438 :     vacuum_get_cutoffs(OldHeap, &params, &cutoffs);
                               1477                 :                : 
                               1478                 :                :     /*
                               1479                 :                :      * FreezeXid will become the table's new relfrozenxid, and that mustn't go
                               1480                 :                :      * backwards, so take the max.
                               1481                 :                :      */
                               1482                 :                :     {
  874 noah@leadboat.com        1483                 :            438 :         TransactionId relfrozenxid = OldHeap->rd_rel->relfrozenxid;
                               1484                 :                : 
                               1485   [ +  -  +  + ]:            876 :         if (TransactionIdIsValid(relfrozenxid) &&
                               1486                 :            438 :             TransactionIdPrecedes(cutoffs.FreezeLimit, relfrozenxid))
                               1487                 :             41 :             cutoffs.FreezeLimit = relfrozenxid;
                               1488                 :                :     }
                               1489                 :                : 
                               1490                 :                :     /*
                               1491                 :                :      * MultiXactCutoff, similarly, shouldn't go backwards either.
                               1492                 :                :      */
                               1493                 :                :     {
                               1494                 :            438 :         MultiXactId relminmxid = OldHeap->rd_rel->relminmxid;
                               1495                 :                : 
                               1496   [ +  -  -  + ]:            876 :         if (MultiXactIdIsValid(relminmxid) &&
                               1497                 :            438 :             MultiXactIdPrecedes(cutoffs.MultiXactCutoff, relminmxid))
  874 noah@leadboat.com        1498                 :UBC           0 :             cutoffs.MultiXactCutoff = relminmxid;
                               1499                 :                :     }
                               1500                 :                : 
                               1501                 :                :     /*
                               1502                 :                :      * Decide whether to use an indexscan or seqscan-and-optional-sort to scan
                               1503                 :                :      * the OldHeap.  If the index is a btree, ask the planner to choose via
                               1504                 :                :      * normal path cost comparison.
                               1505                 :                :      *
                               1506                 :                :      * The underlying tuplesort.c code doesn't support AMs other than btree,
                               1507                 :                :      * so we must always use a normal indexscan if a non-btree index is
                               1508                 :                :      * specified -- or an unsorted seqscan if no index is given.
                               1509                 :                :      */
 5827 tgl@sss.pgh.pa.us        1510   [ +  +  +  + ]:CBC         438 :     if (OldIndex != NULL && OldIndex->rd_rel->relam == BTREE_AM_OID)
  618 alvherre@alvh.no-ip.     1511                 :            145 :         use_sort = plan_cluster_use_sort(RelationGetRelid(OldHeap),
                               1512                 :                :                                          RelationGetRelid(OldIndex));
                               1513                 :                :     else
 5827 tgl@sss.pgh.pa.us        1514                 :            293 :         use_sort = false;
                               1515                 :                : 
                               1516                 :                :     /* Log what we're doing */
 2733 andres@anarazel.de       1517   [ +  +  +  + ]:            438 :     if (OldIndex != NULL && !use_sort)
 5827 tgl@sss.pgh.pa.us        1518         [ -  + ]:             62 :         ereport(elevel,
                               1519                 :                :                 errmsg("repacking \"%s.%s\" using index scan on \"%s\"",
                               1520                 :                :                        nspname,
                               1521                 :                :                        RelationGetRelationName(OldHeap),
                               1522                 :                :                        RelationGetRelationName(OldIndex)));
 2733 andres@anarazel.de       1523         [ +  + ]:            376 :     else if (use_sort)
 5827 tgl@sss.pgh.pa.us        1524         [ -  + ]:             85 :         ereport(elevel,
                               1525                 :                :                 errmsg("repacking \"%s.%s\" using sequential scan and sort",
                               1526                 :                :                        nspname,
                               1527                 :                :                        RelationGetRelationName(OldHeap)));
                               1528                 :                :     else
                               1529         [ +  + ]:            291 :         ereport(elevel,
                               1530                 :                :                 errmsg("repacking \"%s.%s\" in physical order",
                               1531                 :                :                        nspname,
                               1532                 :                :                        RelationGetRelationName(OldHeap)));
                               1533                 :                : 
                               1534                 :                :     /*
                               1535                 :                :      * Hand off the actual copying to AM specific function, the generic code
                               1536                 :                :      * cannot know how to deal with visibility across AMs. Note that this
                               1537                 :                :      * routine is allowed to set FreezeXid / MultiXactCutoff to different
                               1538                 :                :      * values (e.g. because the AM doesn't use freezing).
                               1539                 :                :      */
 2733 andres@anarazel.de       1540                 :            438 :     table_relation_copy_for_cluster(OldHeap, NewHeap, OldIndex, use_sort,
                               1541                 :                :                                     cutoffs.OldestXmin, snapshot,
                               1542                 :                :                                     &cutoffs.FreezeLimit,
                               1543                 :                :                                     &cutoffs.MultiXactCutoff,
                               1544                 :                :                                     &num_tuples, &tups_vacuumed,
                               1545                 :                :                                     &tups_recently_dead);
                               1546                 :                : 
                               1547                 :                :     /* return selected values to caller, get set as relfrozenxid/minmxid */
 1368 pg@bowt.ie               1548                 :            438 :     *pFreezeXid = cutoffs.FreezeLimit;
                               1549                 :            438 :     *pCutoffMulti = cutoffs.MultiXactCutoff;
                               1550                 :                : 
                               1551                 :                :     /*
                               1552                 :                :      * Reset rd_toastoid just to be tidy --- it shouldn't be looked at again.
                               1553                 :                :      * In the CONCURRENTLY case, we need to set it again before applying the
                               1554                 :                :      * concurrent changes.
                               1555                 :                :      */
 6072 tgl@sss.pgh.pa.us        1556                 :            438 :     NewHeap->rd_toastoid = InvalidOid;
                               1557                 :                : 
 3189 teodor@sigaev.ru         1558                 :            438 :     num_pages = RelationGetNumberOfBlocks(NewHeap);
                               1559                 :                : 
                               1560                 :                :     /* Log what we did */
 5827 tgl@sss.pgh.pa.us        1561         [ +  + ]:            438 :     ereport(elevel,
                               1562                 :                :             (errmsg("\"%s.%s\": found %.0f removable, %.0f nonremovable row versions in %u pages",
                               1563                 :                :                     nspname,
                               1564                 :                :                     RelationGetRelationName(OldHeap),
                               1565                 :                :                     tups_vacuumed, num_tuples,
                               1566                 :                :                     RelationGetNumberOfBlocks(OldHeap)),
                               1567                 :                :              errdetail("%.0f dead row versions cannot be removed yet.\n"
                               1568                 :                :                        "%s.",
                               1569                 :                :                        tups_recently_dead,
                               1570                 :                :                        pg_rusage_show(&ru0))));
                               1571                 :                : 
                               1572                 :                :     /* Update pg_class to reflect the correct values of pages and tuples. */
 2799 andres@anarazel.de       1573                 :            438 :     relRelation = table_open(RelationRelationId, RowExclusiveLock);
                               1574                 :                : 
  618 alvherre@alvh.no-ip.     1575                 :            438 :     reltup = SearchSysCacheCopy1(RELOID,
                               1576                 :                :                                  ObjectIdGetDatum(RelationGetRelid(NewHeap)));
 3189 teodor@sigaev.ru         1577         [ -  + ]:            438 :     if (!HeapTupleIsValid(reltup))
  618 alvherre@alvh.no-ip.     1578         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u",
                               1579                 :                :              RelationGetRelid(NewHeap));
 3189 teodor@sigaev.ru         1580                 :CBC         438 :     relform = (Form_pg_class) GETSTRUCT(reltup);
                               1581                 :                : 
                               1582                 :            438 :     relform->relpages = num_pages;
                               1583                 :            438 :     relform->reltuples = num_tuples;
                               1584                 :                : 
                               1585                 :                :     /* Don't update the stats for pg_class.  See swap_relation_files. */
  618 alvherre@alvh.no-ip.     1586         [ +  + ]:            438 :     if (RelationGetRelid(OldHeap) != RelationRelationId)
 3189 teodor@sigaev.ru         1587                 :            415 :         CatalogTupleUpdate(relRelation, &reltup->t_self, reltup);
                               1588                 :                :     else
                               1589                 :             23 :         CacheInvalidateRelcacheByTuple(reltup);
                               1590                 :                : 
                               1591                 :                :     /* Clean up. */
                               1592                 :            438 :     heap_freetuple(reltup);
 2799 andres@anarazel.de       1593                 :            438 :     table_close(relRelation, RowExclusiveLock);
                               1594                 :                : 
                               1595                 :                :     /* Make the update visible */
 3189 teodor@sigaev.ru         1596                 :            438 :     CommandCounterIncrement();
11030 scrappy@hub.org          1597                 :            438 : }
                               1598                 :                : 
                               1599                 :                : /*
                               1600                 :                :  * Swap the physical files of two given relations.
                               1601                 :                :  *
                               1602                 :                :  * We swap the physical identity (reltablespace, relfilenumber) while keeping
                               1603                 :                :  * the same logical identities of the two relations.  relpersistence is also
                               1604                 :                :  * swapped, which is critical since it determines where buffers live for each
                               1605                 :                :  * relation.
                               1606                 :                :  *
                               1607                 :                :  * We can swap associated TOAST data in either of two ways: recursively swap
                               1608                 :                :  * the physical content of the toast tables (and their indexes), or swap the
                               1609                 :                :  * TOAST links in the given relations' pg_class entries.  The former is needed
                               1610                 :                :  * to manage rewrites of shared catalogs (where we cannot change the pg_class
                               1611                 :                :  * links) while the latter is the only way to handle cases in which a toast
                               1612                 :                :  * table is added or removed altogether.
                               1613                 :                :  *
                               1614                 :                :  * Additionally, the first relation is marked with relfrozenxid set to
                               1615                 :                :  * frozenXid.  It seems a bit ugly to have this here, but the caller would
                               1616                 :                :  * have to do it anyway, so having it here saves a heap_update.  Note: in
                               1617                 :                :  * the swap-toast-links case, we assume we don't need to change the toast
                               1618                 :                :  * table's relfrozenxid: the new version of the toast table should already
                               1619                 :                :  * have relfrozenxid set to RecentXmin, which is good enough.
                               1620                 :                :  *
                               1621                 :                :  * Lastly, if r2 and its toast table and toast index (if any) are mapped,
                               1622                 :                :  * their OIDs are emitted into mapped_tables[].  This is hacky but beats
                               1623                 :                :  * having to look the information up again later in finish_heap_swap.
                               1624                 :                :  */
                               1625                 :                : static void
 6069 tgl@sss.pgh.pa.us        1626                 :           1807 : swap_relation_files(Oid r1, Oid r2, bool target_is_pg_class,
                               1627                 :                :                     bool swap_toast_by_content,
                               1628                 :                :                     bool is_internal,
                               1629                 :                :                     TransactionId frozenXid,
                               1630                 :                :                     MultiXactId cutoffMulti,
                               1631                 :                :                     Oid *mapped_tables)
                               1632                 :                : {
                               1633                 :                :     Relation    relRelation;
                               1634                 :                :     HeapTuple   reltup1,
                               1635                 :                :                 reltup2;
                               1636                 :                :     Form_pg_class relform1,
                               1637                 :                :                 relform2;
                               1638                 :                :     RelFileNumber relfilenumber1,
                               1639                 :                :                 relfilenumber2;
                               1640                 :                :     RelFileNumber swaptemp;
                               1641                 :                :     char        swptmpchr;
                               1642                 :                :     Oid         relam1,
                               1643                 :                :                 relam2;
                               1644                 :                : 
                               1645                 :                :     /* We need writable copies of both pg_class tuples. */
 2799 andres@anarazel.de       1646                 :           1807 :     relRelation = table_open(RelationRelationId, RowExclusiveLock);
                               1647                 :                : 
 6062 rhaas@postgresql.org     1648                 :           1807 :     reltup1 = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(r1));
 8806 tgl@sss.pgh.pa.us        1649         [ -  + ]:           1807 :     if (!HeapTupleIsValid(reltup1))
 8463 tgl@sss.pgh.pa.us        1650         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", r1);
 8806 tgl@sss.pgh.pa.us        1651                 :CBC        1807 :     relform1 = (Form_pg_class) GETSTRUCT(reltup1);
                               1652                 :                : 
 6062 rhaas@postgresql.org     1653                 :           1807 :     reltup2 = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(r2));
 8806 tgl@sss.pgh.pa.us        1654         [ -  + ]:           1807 :     if (!HeapTupleIsValid(reltup2))
 8463 tgl@sss.pgh.pa.us        1655         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for relation %u", r2);
 8806 tgl@sss.pgh.pa.us        1656                 :CBC        1807 :     relform2 = (Form_pg_class) GETSTRUCT(reltup2);
                               1657                 :                : 
 1537 rhaas@postgresql.org     1658                 :           1807 :     relfilenumber1 = relform1->relfilenode;
                               1659                 :           1807 :     relfilenumber2 = relform2->relfilenode;
 1178 michael@paquier.xyz      1660                 :           1807 :     relam1 = relform1->relam;
                               1661                 :           1807 :     relam2 = relform2->relam;
                               1662                 :                : 
 1537 rhaas@postgresql.org     1663   [ +  +  +  - ]:           1807 :     if (RelFileNumberIsValid(relfilenumber1) &&
                               1664                 :                :         RelFileNumberIsValid(relfilenumber2))
                               1665                 :                :     {
                               1666                 :                :         /*
                               1667                 :                :          * Normal non-mapped relations: swap relfilenumbers, reltablespaces,
                               1668                 :                :          * relpersistence
                               1669                 :                :          */
 6069 tgl@sss.pgh.pa.us        1670         [ -  + ]:           1718 :         Assert(!target_is_pg_class);
                               1671                 :                : 
                               1672                 :           1718 :         swaptemp = relform1->relfilenode;
                               1673                 :           1718 :         relform1->relfilenode = relform2->relfilenode;
                               1674                 :           1718 :         relform2->relfilenode = swaptemp;
                               1675                 :                : 
                               1676                 :           1718 :         swaptemp = relform1->reltablespace;
                               1677                 :           1718 :         relform1->reltablespace = relform2->reltablespace;
                               1678                 :           1718 :         relform2->reltablespace = swaptemp;
                               1679                 :                : 
 1880 michael@paquier.xyz      1680                 :           1718 :         swaptemp = relform1->relam;
                               1681                 :           1718 :         relform1->relam = relform2->relam;
                               1682                 :           1718 :         relform2->relam = swaptemp;
                               1683                 :                : 
 4412 alvherre@alvh.no-ip.     1684                 :           1718 :         swptmpchr = relform1->relpersistence;
                               1685                 :           1718 :         relform1->relpersistence = relform2->relpersistence;
                               1686                 :           1718 :         relform2->relpersistence = swptmpchr;
                               1687                 :                : 
                               1688                 :                :         /* Also swap toast links, if we're swapping by links */
 6069 tgl@sss.pgh.pa.us        1689         [ +  + ]:           1718 :         if (!swap_toast_by_content)
                               1690                 :                :         {
                               1691                 :           1292 :             swaptemp = relform1->reltoastrelid;
                               1692                 :           1292 :             relform1->reltoastrelid = relform2->reltoastrelid;
                               1693                 :           1292 :             relform2->reltoastrelid = swaptemp;
                               1694                 :                :         }
                               1695                 :                :     }
                               1696                 :                :     else
                               1697                 :                :     {
                               1698                 :                :         /*
                               1699                 :                :          * Mapped-relation case.  Here we have to swap the relation mappings
                               1700                 :                :          * instead of modifying the pg_class columns.  Both must be mapped.
                               1701                 :                :          */
 1537 rhaas@postgresql.org     1702   [ +  -  -  + ]:             89 :         if (RelFileNumberIsValid(relfilenumber1) ||
                               1703                 :                :             RelFileNumberIsValid(relfilenumber2))
 6069 tgl@sss.pgh.pa.us        1704         [ #  # ]:UBC           0 :             elog(ERROR, "cannot swap mapped relation \"%s\" with non-mapped relation",
                               1705                 :                :                  NameStr(relform1->relname));
                               1706                 :                : 
                               1707                 :                :         /*
                               1708                 :                :          * We can't change the tablespace nor persistence of a mapped rel, and
                               1709                 :                :          * we can't handle toast link swapping for one either, because we must
                               1710                 :                :          * not apply any critical changes to its pg_class row.  These cases
                               1711                 :                :          * should be prevented by upstream permissions tests, so these checks
                               1712                 :                :          * are non-user-facing emergency backstop.
                               1713                 :                :          */
 6069 tgl@sss.pgh.pa.us        1714         [ -  + ]:CBC          89 :         if (relform1->reltablespace != relform2->reltablespace)
 6069 tgl@sss.pgh.pa.us        1715         [ #  # ]:UBC           0 :             elog(ERROR, "cannot change tablespace of mapped relation \"%s\"",
                               1716                 :                :                  NameStr(relform1->relname));
 4412 alvherre@alvh.no-ip.     1717         [ -  + ]:CBC          89 :         if (relform1->relpersistence != relform2->relpersistence)
 4412 alvherre@alvh.no-ip.     1718         [ #  # ]:UBC           0 :             elog(ERROR, "cannot change persistence of mapped relation \"%s\"",
                               1719                 :                :                  NameStr(relform1->relname));
 1880 michael@paquier.xyz      1720         [ -  + ]:CBC          89 :         if (relform1->relam != relform2->relam)
 1880 michael@paquier.xyz      1721         [ #  # ]:UBC           0 :             elog(ERROR, "cannot change access method of mapped relation \"%s\"",
                               1722                 :                :                  NameStr(relform1->relname));
 6069 tgl@sss.pgh.pa.us        1723         [ +  + ]:CBC          89 :         if (!swap_toast_by_content &&
                               1724   [ +  -  -  + ]:             29 :             (relform1->reltoastrelid || relform2->reltoastrelid))
 6069 tgl@sss.pgh.pa.us        1725         [ #  # ]:UBC           0 :             elog(ERROR, "cannot swap toast by links for mapped relation \"%s\"",
                               1726                 :                :                  NameStr(relform1->relname));
                               1727                 :                : 
                               1728                 :                :         /*
                               1729                 :                :          * Fetch the mappings --- shouldn't fail, but be paranoid
                               1730                 :                :          */
 1537 rhaas@postgresql.org     1731                 :CBC          89 :         relfilenumber1 = RelationMapOidToFilenumber(r1, relform1->relisshared);
                               1732         [ -  + ]:             89 :         if (!RelFileNumberIsValid(relfilenumber1))
 6069 tgl@sss.pgh.pa.us        1733         [ #  # ]:UBC           0 :             elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
                               1734                 :                :                  NameStr(relform1->relname), r1);
 1537 rhaas@postgresql.org     1735                 :CBC          89 :         relfilenumber2 = RelationMapOidToFilenumber(r2, relform2->relisshared);
                               1736         [ -  + ]:             89 :         if (!RelFileNumberIsValid(relfilenumber2))
 6069 tgl@sss.pgh.pa.us        1737         [ #  # ]:UBC           0 :             elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
                               1738                 :                :                  NameStr(relform2->relname), r2);
                               1739                 :                : 
                               1740                 :                :         /*
                               1741                 :                :          * Send replacement mappings to relmapper.  Note these won't actually
                               1742                 :                :          * take effect until CommandCounterIncrement.
                               1743                 :                :          */
 1537 rhaas@postgresql.org     1744                 :CBC          89 :         RelationMapUpdateMap(r1, relfilenumber2, relform1->relisshared, false);
                               1745                 :             89 :         RelationMapUpdateMap(r2, relfilenumber1, relform2->relisshared, false);
                               1746                 :                : 
                               1747                 :                :         /* Pass OIDs of mapped r2 tables back to caller */
 6069 tgl@sss.pgh.pa.us        1748                 :             89 :         *mapped_tables++ = r2;
                               1749                 :                :     }
                               1750                 :                : 
                               1751                 :                :     /*
                               1752                 :                :      * Recognize that rel1's relfilenumber (swapped from rel2) is new in this
                               1753                 :                :      * subtransaction. The rel2 storage (swapped from rel1) may or may not be
                               1754                 :                :      * new.
                               1755                 :                :      */
                               1756                 :                :     {
                               1757                 :                :         Relation    rel1,
                               1758                 :                :                     rel2;
                               1759                 :                : 
 2360 noah@leadboat.com        1760                 :           1807 :         rel1 = relation_open(r1, NoLock);
                               1761                 :           1807 :         rel2 = relation_open(r2, NoLock);
                               1762                 :           1807 :         rel2->rd_createSubid = rel1->rd_createSubid;
 1537 rhaas@postgresql.org     1763                 :           1807 :         rel2->rd_newRelfilelocatorSubid = rel1->rd_newRelfilelocatorSubid;
                               1764                 :           1807 :         rel2->rd_firstRelfilelocatorSubid = rel1->rd_firstRelfilelocatorSubid;
                               1765                 :           1807 :         RelationAssumeNewRelfilelocator(rel1);
 2360 noah@leadboat.com        1766                 :           1807 :         relation_close(rel1, NoLock);
                               1767                 :           1807 :         relation_close(rel2, NoLock);
                               1768                 :                :     }
                               1769                 :                : 
                               1770                 :                :     /*
                               1771                 :                :      * In the case of a shared catalog, these next few steps will only affect
                               1772                 :                :      * our own database's pg_class row; but that's okay, because they are all
                               1773                 :                :      * noncritical updates.  That's also an important fact for the case of a
                               1774                 :                :      * mapped catalog, because it's possible that we'll commit the map change
                               1775                 :                :      * and then fail to commit the pg_class update.
                               1776                 :                :      */
                               1777                 :                : 
                               1778                 :                :     /* set rel1's frozen Xid and minimum MultiXid */
 6072 tgl@sss.pgh.pa.us        1779         [ +  + ]:           1807 :     if (relform1->relkind != RELKIND_INDEX)
                               1780                 :                :     {
 2707 andres@anarazel.de       1781   [ +  -  -  + ]:           1635 :         Assert(!TransactionIdIsValid(frozenXid) ||
                               1782                 :                :                TransactionIdIsNormal(frozenXid));
 6072 tgl@sss.pgh.pa.us        1783                 :           1635 :         relform1->relfrozenxid = frozenXid;
 4752 alvherre@alvh.no-ip.     1784                 :           1635 :         relform1->relminmxid = cutoffMulti;
                               1785                 :                :     }
                               1786                 :                : 
                               1787                 :                :     /* swap size statistics too, since new rel has freshly-updated stats */
                               1788                 :                :     {
                               1789                 :                :         int32       swap_pages;
                               1790                 :                :         float4      swap_tuples;
                               1791                 :                :         int32       swap_allvisible;
                               1792                 :                :         int32       swap_allfrozen;
                               1793                 :                : 
 8723 tgl@sss.pgh.pa.us        1794                 :           1807 :         swap_pages = relform1->relpages;
                               1795                 :           1807 :         relform1->relpages = relform2->relpages;
                               1796                 :           1807 :         relform2->relpages = swap_pages;
                               1797                 :                : 
                               1798                 :           1807 :         swap_tuples = relform1->reltuples;
                               1799                 :           1807 :         relform1->reltuples = relform2->reltuples;
                               1800                 :           1807 :         relform2->reltuples = swap_tuples;
                               1801                 :                : 
 5455                          1802                 :           1807 :         swap_allvisible = relform1->relallvisible;
                               1803                 :           1807 :         relform1->relallvisible = relform2->relallvisible;
                               1804                 :           1807 :         relform2->relallvisible = swap_allvisible;
                               1805                 :                : 
  566 melanieplageman@gmai     1806                 :           1807 :         swap_allfrozen = relform1->relallfrozen;
                               1807                 :           1807 :         relform1->relallfrozen = relform2->relallfrozen;
                               1808                 :           1807 :         relform2->relallfrozen = swap_allfrozen;
                               1809                 :                :     }
                               1810                 :                : 
                               1811                 :                :     /*
                               1812                 :                :      * Update the tuples in pg_class --- unless the target relation of the
                               1813                 :                :      * swap is pg_class itself.  In that case, there is zero point in making
                               1814                 :                :      * changes because we'd be updating the old data that we're about to throw
                               1815                 :                :      * away.  Because the real work being done here for a mapped relation is
                               1816                 :                :      * just to change the relation map settings, it's all right to not update
                               1817                 :                :      * the pg_class rows in this case. The most important changes will instead
                               1818                 :                :      * performed later, in finish_heap_swap() itself.
                               1819                 :                :      */
 6069 tgl@sss.pgh.pa.us        1820         [ +  + ]:           1807 :     if (!target_is_pg_class)
                               1821                 :                :     {
                               1822                 :                :         CatalogIndexState indstate;
                               1823                 :                : 
                               1824                 :           1784 :         indstate = CatalogOpenIndexes(relRelation);
 3518                          1825                 :           1784 :         CatalogTupleUpdateWithInfo(relRelation, &reltup1->t_self, reltup1,
                               1826                 :                :                                    indstate);
                               1827                 :           1784 :         CatalogTupleUpdateWithInfo(relRelation, &reltup2->t_self, reltup2,
                               1828                 :                :                                    indstate);
 6069                          1829                 :           1784 :         CatalogCloseIndexes(indstate);
                               1830                 :                :     }
                               1831                 :                :     else
                               1832                 :                :     {
                               1833                 :                :         /* no update ... but we do still need relcache inval */
                               1834                 :             23 :         CacheInvalidateRelcacheByTuple(reltup1);
                               1835                 :             23 :         CacheInvalidateRelcacheByTuple(reltup2);
                               1836                 :                :     }
                               1837                 :                : 
                               1838                 :                :     /*
                               1839                 :                :      * Now that pg_class has been updated with its relevant information for
                               1840                 :                :      * the swap, update the dependency of the relations to point to their new
                               1841                 :                :      * table AM, if it has changed.
                               1842                 :                :      */
 1178 michael@paquier.xyz      1843         [ +  + ]:           1807 :     if (relam1 != relam2)
                               1844                 :                :     {
                               1845         [ -  + ]:             24 :         if (changeDependencyFor(RelationRelationId,
                               1846                 :                :                                 r1,
                               1847                 :                :                                 AccessMethodRelationId,
                               1848                 :                :                                 relam1,
                               1849                 :                :                                 relam2) != 1)
 1168 michael@paquier.xyz      1850         [ #  # ]:UBC           0 :             elog(ERROR, "could not change access method dependency for relation \"%s.%s\"",
                               1851                 :                :                  get_namespace_name(get_rel_namespace(r1)),
                               1852                 :                :                  get_rel_name(r1));
 1178 michael@paquier.xyz      1853         [ -  + ]:CBC          24 :         if (changeDependencyFor(RelationRelationId,
                               1854                 :                :                                 r2,
                               1855                 :                :                                 AccessMethodRelationId,
                               1856                 :                :                                 relam2,
                               1857                 :                :                                 relam1) != 1)
 1168 michael@paquier.xyz      1858         [ #  # ]:UBC           0 :             elog(ERROR, "could not change access method dependency for relation \"%s.%s\"",
                               1859                 :                :                  get_namespace_name(get_rel_namespace(r2)),
                               1860                 :                :                  get_rel_name(r2));
                               1861                 :                :     }
                               1862                 :                : 
                               1863                 :                :     /*
                               1864                 :                :      * Post alter hook for modified relations. The change to r2 is always
                               1865                 :                :      * internal, but r1 depends on the invocation context.
                               1866                 :                :      */
 4935 rhaas@postgresql.org     1867         [ -  + ]:CBC        1807 :     InvokeObjectPostAlterHookArg(RelationRelationId, r1, 0,
                               1868                 :                :                                  InvalidOid, is_internal);
                               1869         [ -  + ]:           1807 :     InvokeObjectPostAlterHookArg(RelationRelationId, r2, 0,
                               1870                 :                :                                  InvalidOid, true);
                               1871                 :                : 
                               1872                 :                :     /*
                               1873                 :                :      * If we have toast tables associated with the relations being swapped,
                               1874                 :                :      * deal with them too.
                               1875                 :                :      */
 8806 tgl@sss.pgh.pa.us        1876   [ +  +  +  + ]:           1807 :     if (relform1->reltoastrelid || relform2->reltoastrelid)
                               1877                 :                :     {
 6072                          1878         [ +  + ]:            566 :         if (swap_toast_by_content)
                               1879                 :                :         {
                               1880   [ +  -  +  - ]:            162 :             if (relform1->reltoastrelid && relform2->reltoastrelid)
                               1881                 :                :             {
                               1882                 :                :                 /* Recursively swap the contents of the toast tables */
                               1883                 :            162 :                 swap_relation_files(relform1->reltoastrelid,
                               1884                 :                :                                     relform2->reltoastrelid,
                               1885                 :                :                                     target_is_pg_class,
                               1886                 :                :                                     swap_toast_by_content,
                               1887                 :                :                                     is_internal,
                               1888                 :                :                                     frozenXid,
                               1889                 :                :                                     cutoffMulti,
                               1890                 :                :                                     mapped_tables);
                               1891                 :                :             }
                               1892                 :                :             else
                               1893                 :                :             {
                               1894                 :                :                 /* caller messed up */
 6072 tgl@sss.pgh.pa.us        1895         [ #  # ]:UBC           0 :                 elog(ERROR, "cannot swap toast files by content when there's only one");
                               1896                 :                :             }
                               1897                 :                :         }
                               1898                 :                :         else
                               1899                 :                :         {
                               1900                 :                :             /*
                               1901                 :                :              * We swapped the ownership links, so we need to change dependency
                               1902                 :                :              * data to match.
                               1903                 :                :              *
                               1904                 :                :              * NOTE: it is possible that only one table has a toast table.
                               1905                 :                :              *
                               1906                 :                :              * NOTE: at present, a TOAST table's only dependency is the one on
                               1907                 :                :              * its owning table.  If more are ever created, we'd need to use
                               1908                 :                :              * something more selective than deleteDependencyRecordsFor() to
                               1909                 :                :              * get rid of just the link we want.
                               1910                 :                :              */
                               1911                 :                :             ObjectAddress baseobject,
                               1912                 :                :                         toastobject;
                               1913                 :                :             long        count;
                               1914                 :                : 
                               1915                 :                :             /*
                               1916                 :                :              * We disallow this case for system catalogs, to avoid the
                               1917                 :                :              * possibility that the catalog we're rebuilding is one of the
                               1918                 :                :              * ones the dependency changes would change.  It's too late to be
                               1919                 :                :              * making any data changes to the target catalog.
                               1920                 :                :              */
 4679 rhaas@postgresql.org     1921         [ -  + ]:CBC         404 :             if (IsSystemClass(r1, relform1))
 6069 tgl@sss.pgh.pa.us        1922         [ #  # ]:UBC           0 :                 elog(ERROR, "cannot swap toast files by links for system catalogs");
                               1923                 :                : 
                               1924                 :                :             /* Delete old dependencies */
 6072 tgl@sss.pgh.pa.us        1925         [ +  + ]:CBC         404 :             if (relform1->reltoastrelid)
                               1926                 :                :             {
                               1927                 :            383 :                 count = deleteDependencyRecordsFor(RelationRelationId,
                               1928                 :                :                                                    relform1->reltoastrelid,
                               1929                 :                :                                                    false);
                               1930         [ -  + ]:            383 :                 if (count != 1)
 6072 tgl@sss.pgh.pa.us        1931         [ #  # ]:UBC           0 :                     elog(ERROR, "expected one dependency record for TOAST table, found %ld",
                               1932                 :                :                          count);
                               1933                 :                :             }
 6072 tgl@sss.pgh.pa.us        1934         [ +  - ]:CBC         404 :             if (relform2->reltoastrelid)
                               1935                 :                :             {
                               1936                 :            404 :                 count = deleteDependencyRecordsFor(RelationRelationId,
                               1937                 :                :                                                    relform2->reltoastrelid,
                               1938                 :                :                                                    false);
                               1939         [ -  + ]:            404 :                 if (count != 1)
 6072 tgl@sss.pgh.pa.us        1940         [ #  # ]:UBC           0 :                     elog(ERROR, "expected one dependency record for TOAST table, found %ld",
                               1941                 :                :                          count);
                               1942                 :                :             }
                               1943                 :                : 
                               1944                 :                :             /* Register new dependencies */
 6072 tgl@sss.pgh.pa.us        1945                 :CBC         404 :             baseobject.classId = RelationRelationId;
                               1946                 :            404 :             baseobject.objectSubId = 0;
                               1947                 :            404 :             toastobject.classId = RelationRelationId;
                               1948                 :            404 :             toastobject.objectSubId = 0;
                               1949                 :                : 
                               1950         [ +  + ]:            404 :             if (relform1->reltoastrelid)
                               1951                 :                :             {
                               1952                 :            383 :                 baseobject.objectId = r1;
                               1953                 :            383 :                 toastobject.objectId = relform1->reltoastrelid;
                               1954                 :            383 :                 recordDependencyOn(&toastobject, &baseobject,
                               1955                 :                :                                    DEPENDENCY_INTERNAL);
                               1956                 :                :             }
                               1957                 :                : 
                               1958         [ +  - ]:            404 :             if (relform2->reltoastrelid)
                               1959                 :                :             {
                               1960                 :            404 :                 baseobject.objectId = r2;
                               1961                 :            404 :                 toastobject.objectId = relform2->reltoastrelid;
                               1962                 :            404 :                 recordDependencyOn(&toastobject, &baseobject,
                               1963                 :                :                                    DEPENDENCY_INTERNAL);
                               1964                 :                :             }
                               1965                 :                :         }
                               1966                 :                :     }
                               1967                 :                : 
                               1968                 :                :     /*
                               1969                 :                :      * If we're swapping two toast tables by content, do the same for their
                               1970                 :                :      * valid index. The swap can actually be safely done only if the relations
                               1971                 :                :      * have indexes.
                               1972                 :                :      */
                               1973         [ +  + ]:           1807 :     if (swap_toast_by_content &&
 4826 fujii@postgresql.org     1974         [ +  + ]:            486 :         relform1->relkind == RELKIND_TOASTVALUE &&
                               1975         [ +  - ]:            162 :         relform2->relkind == RELKIND_TOASTVALUE)
                               1976                 :                :     {
                               1977                 :                :         Oid         toastIndex1,
                               1978                 :                :                     toastIndex2;
                               1979                 :                : 
                               1980                 :                :         /* Get valid index for each relation */
                               1981                 :            162 :         toastIndex1 = toast_get_valid_index(r1,
                               1982                 :                :                                             AccessExclusiveLock);
                               1983                 :            162 :         toastIndex2 = toast_get_valid_index(r2,
                               1984                 :                :                                             AccessExclusiveLock);
                               1985                 :                : 
                               1986                 :            162 :         swap_relation_files(toastIndex1,
                               1987                 :                :                             toastIndex2,
                               1988                 :                :                             target_is_pg_class,
                               1989                 :                :                             swap_toast_by_content,
                               1990                 :                :                             is_internal,
                               1991                 :                :                             InvalidTransactionId,
                               1992                 :                :                             InvalidMultiXactId,
                               1993                 :                :                             mapped_tables);
                               1994                 :                :     }
                               1995                 :                : 
                               1996                 :                :     /* Clean up. */
 8806 tgl@sss.pgh.pa.us        1997                 :           1807 :     heap_freetuple(reltup1);
                               1998                 :           1807 :     heap_freetuple(reltup2);
                               1999                 :                : 
 2799 andres@anarazel.de       2000                 :           1807 :     table_close(relRelation, RowExclusiveLock);
 8807 bruce@momjian.us         2001                 :           1807 : }
                               2002                 :                : 
                               2003                 :                : /*
                               2004                 :                :  * Remove the transient table that was built by make_new_heap, and finish
                               2005                 :                :  * cleaning up (including rebuilding all indexes on the old heap).
                               2006                 :                :  */
                               2007                 :                : void
 6069 tgl@sss.pgh.pa.us        2008                 :           1473 : finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap,
                               2009                 :                :                  bool is_system_catalog,
                               2010                 :                :                  bool swap_toast_by_content,
                               2011                 :                :                  bool check_constraints,
                               2012                 :                :                  bool is_internal,
                               2013                 :                :                  bool reindex,
                               2014                 :                :                  TransactionId frozenXid,
                               2015                 :                :                  MultiXactId cutoffMulti,
                               2016                 :                :                  char newrelpersistence)
                               2017                 :                : {
                               2018                 :                :     ObjectAddress object;
                               2019                 :                :     Oid         mapped_tables[4];
                               2020                 :                :     int         i;
                               2021                 :                : 
                               2022                 :                :     /* Report that we are now swapping relation files */
  194 alvherre@kurilemu.de     2023                 :           1473 :     pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                               2024                 :                :                                  PROGRESS_REPACK_PHASE_SWAP_REL_FILES);
                               2025                 :                : 
                               2026                 :                :     /* Zero out possible results from swapped_relation_files */
 6069 tgl@sss.pgh.pa.us        2027                 :           1473 :     memset(mapped_tables, 0, sizeof(mapped_tables));
                               2028                 :                : 
                               2029                 :                :     /*
                               2030                 :                :      * Swap the contents of the heap relations (including any toast tables).
                               2031                 :                :      * Also set old heap's relfrozenxid to frozenXid.
                               2032                 :                :      */
                               2033                 :           1473 :     swap_relation_files(OIDOldHeap, OIDNewHeap,
                               2034                 :                :                         (OIDOldHeap == RelationRelationId),
                               2035                 :                :                         swap_toast_by_content, is_internal,
                               2036                 :                :                         frozenXid, cutoffMulti, mapped_tables);
                               2037                 :                : 
                               2038                 :                :     /*
                               2039                 :                :      * If it's a system catalog, queue a sinval message to flush all catcaches
                               2040                 :                :      * on the catalog when we reach CommandCounterIncrement.
                               2041                 :                :      */
                               2042         [ +  + ]:           1473 :     if (is_system_catalog)
                               2043                 :            116 :         CacheInvalidateCatalog(OIDOldHeap);
                               2044                 :                : 
  167 alvherre@kurilemu.de     2045         [ +  + ]:           1473 :     if (reindex)
                               2046                 :                :     {
                               2047                 :                :         int         reindex_flags;
                               2048                 :           1464 :         ReindexParams reindex_params = {0};
                               2049                 :                : 
                               2050                 :                :         /*
                               2051                 :                :          * Rebuild each index on the relation (but not the toast table, which
                               2052                 :                :          * is all-new at this point).  It is important to do this before the
                               2053                 :                :          * DROP step because if we are processing a system catalog that will
                               2054                 :                :          * be used during DROP, we want to have its indexes available.  There
                               2055                 :                :          * is no advantage to the other order anyway because this is all
                               2056                 :                :          * transactional, so no chance to reclaim disk space before commit. We
                               2057                 :                :          * do not need a final CommandCounterIncrement() because
                               2058                 :                :          * reindex_relation does it.
                               2059                 :                :          *
                               2060                 :                :          * Note: because index_build is called via reindex_relation, it will
                               2061                 :                :          * never set indcheckxmin true for the indexes.  This is OK even
                               2062                 :                :          * though in some sense we are building new indexes rather than
                               2063                 :                :          * rebuilding existing ones, because the new heap won't contain any
                               2064                 :                :          * HOT chains at all, let alone broken ones, so it can't be necessary
                               2065                 :                :          * to set indcheckxmin.
                               2066                 :                :          */
                               2067                 :           1464 :         reindex_flags = REINDEX_REL_SUPPRESS_INDEX_USE;
                               2068         [ +  + ]:           1464 :         if (check_constraints)
                               2069                 :           1035 :             reindex_flags |= REINDEX_REL_CHECK_CONSTRAINTS;
                               2070                 :                : 
                               2071                 :                :         /*
                               2072                 :                :          * Ensure that the indexes have the same persistence as the parent
                               2073                 :                :          * relation.
                               2074                 :                :          */
                               2075         [ +  + ]:           1464 :         if (newrelpersistence == RELPERSISTENCE_UNLOGGED)
                               2076                 :             25 :             reindex_flags |= REINDEX_REL_FORCE_INDEXES_UNLOGGED;
                               2077         [ +  + ]:           1439 :         else if (newrelpersistence == RELPERSISTENCE_PERMANENT)
                               2078                 :           1386 :             reindex_flags |= REINDEX_REL_FORCE_INDEXES_PERMANENT;
                               2079                 :                : 
                               2080                 :                :         /* Report that we are now reindexing relations */
                               2081                 :           1464 :         pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                               2082                 :                :                                      PROGRESS_REPACK_PHASE_REBUILD_INDEX);
                               2083                 :                : 
                               2084                 :           1464 :         reindex_relation(NULL, OIDOldHeap, reindex_flags, &reindex_params);
                               2085                 :                :     }
                               2086                 :                : 
                               2087                 :                :     /* Report that we are now doing clean up */
  194                          2088                 :           1461 :     pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                               2089                 :                :                                  PROGRESS_REPACK_PHASE_FINAL_CLEANUP);
                               2090                 :                : 
                               2091                 :                :     /*
                               2092                 :                :      * If the relation being rebuilt is pg_class, swap_relation_files()
                               2093                 :                :      * couldn't update pg_class's own pg_class entry (check comments in
                               2094                 :                :      * swap_relation_files()), thus relfrozenxid was not updated. That's
                               2095                 :                :      * annoying because a potential reason for doing a VACUUM FULL is a
                               2096                 :                :      * imminent or actual anti-wraparound shutdown.  So, now that we can
                               2097                 :                :      * access the new relation using its indices, update relfrozenxid.
                               2098                 :                :      * pg_class doesn't have a toast relation, so we don't need to update the
                               2099                 :                :      * corresponding toast relation. Not that there's little point moving all
                               2100                 :                :      * relfrozenxid updates here since swap_relation_files() needs to write to
                               2101                 :                :      * pg_class for non-mapped relations anyway.
                               2102                 :                :      */
 4583 rhaas@postgresql.org     2103         [ +  + ]:           1461 :     if (OIDOldHeap == RelationRelationId)
                               2104                 :                :     {
                               2105                 :                :         Relation    relRelation;
                               2106                 :                :         HeapTuple   reltup;
                               2107                 :                :         Form_pg_class relform;
                               2108                 :                : 
 2799 andres@anarazel.de       2109                 :             23 :         relRelation = table_open(RelationRelationId, RowExclusiveLock);
                               2110                 :                : 
 4583 rhaas@postgresql.org     2111                 :             23 :         reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(OIDOldHeap));
                               2112         [ -  + ]:             23 :         if (!HeapTupleIsValid(reltup))
 4583 rhaas@postgresql.org     2113         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for relation %u", OIDOldHeap);
 4583 rhaas@postgresql.org     2114                 :CBC          23 :         relform = (Form_pg_class) GETSTRUCT(reltup);
                               2115                 :                : 
                               2116                 :             23 :         relform->relfrozenxid = frozenXid;
                               2117                 :             23 :         relform->relminmxid = cutoffMulti;
                               2118                 :                : 
 3519 alvherre@alvh.no-ip.     2119                 :             23 :         CatalogTupleUpdate(relRelation, &reltup->t_self, reltup);
                               2120                 :                : 
 2799 andres@anarazel.de       2121                 :             23 :         table_close(relRelation, RowExclusiveLock);
                               2122                 :                :     }
                               2123                 :                : 
                               2124                 :                :     /* Destroy new heap with old filenumber */
 6072 tgl@sss.pgh.pa.us        2125                 :           1461 :     object.classId = RelationRelationId;
                               2126                 :           1461 :     object.objectId = OIDNewHeap;
                               2127                 :           1461 :     object.objectSubId = 0;
                               2128                 :                : 
  167 alvherre@kurilemu.de     2129         [ +  + ]:           1461 :     if (!reindex)
                               2130                 :                :     {
                               2131                 :                :         /*
                               2132                 :                :          * Make sure the changes in pg_class are visible. This is especially
                               2133                 :                :          * important if !swap_toast_by_content, so that the correct TOAST
                               2134                 :                :          * relation is dropped. (reindex_relation() above did not help in this
                               2135                 :                :          * case))
                               2136                 :                :          */
                               2137                 :              9 :         CommandCounterIncrement();
                               2138                 :                :     }
                               2139                 :                : 
                               2140                 :                :     /*
                               2141                 :                :      * The new relation is local to our transaction and we know nothing
                               2142                 :                :      * depends on it, so DROP_RESTRICT should be OK.
                               2143                 :                :      */
 5351 rhaas@postgresql.org     2144                 :           1461 :     performDeletion(&object, DROP_RESTRICT, PERFORM_DELETION_INTERNAL);
                               2145                 :                : 
                               2146                 :                :     /* performDeletion does CommandCounterIncrement at end */
                               2147                 :                : 
                               2148                 :                :     /*
                               2149                 :                :      * Now we must remove any relation mapping entries that we set up for the
                               2150                 :                :      * transient table, as well as its toast table and toast index if any. If
                               2151                 :                :      * we fail to do this before commit, the relmapper will complain about new
                               2152                 :                :      * permanent map entries being added post-bootstrap.
                               2153                 :                :      */
 6069 tgl@sss.pgh.pa.us        2154         [ +  + ]:           1550 :     for (i = 0; OidIsValid(mapped_tables[i]); i++)
                               2155                 :             89 :         RelationMapRemoveMapping(mapped_tables[i]);
                               2156                 :                : 
                               2157                 :                :     /*
                               2158                 :                :      * At this point, everything is kosher except that, if we did toast swap
                               2159                 :                :      * by links, the toast table's name corresponds to the transient table.
                               2160                 :                :      * The name is irrelevant to the backend because it's referenced by OID,
                               2161                 :                :      * but users looking at the catalogs could be confused.  Rename it to
                               2162                 :                :      * prevent this problem.
                               2163                 :                :      *
                               2164                 :                :      * Note no lock required on the relation, because we already hold an
                               2165                 :                :      * exclusive lock on it.
                               2166                 :                :      */
 6072                          2167         [ +  + ]:           1461 :     if (!swap_toast_by_content)
                               2168                 :                :     {
                               2169                 :                :         Relation    newrel;
                               2170                 :                : 
 2799 andres@anarazel.de       2171                 :           1299 :         newrel = table_open(OIDOldHeap, NoLock);
 6072 tgl@sss.pgh.pa.us        2172         [ +  + ]:           1299 :         if (OidIsValid(newrel->rd_rel->reltoastrelid))
                               2173                 :                :         {
                               2174                 :                :             Oid         toastidx;
                               2175                 :                :             char        NewToastName[NAMEDATALEN];
                               2176                 :                : 
                               2177                 :                :             /* Get the associated valid index to be renamed */
 4826 fujii@postgresql.org     2178                 :            383 :             toastidx = toast_get_valid_index(newrel->rd_rel->reltoastrelid,
                               2179                 :                :                                              AccessExclusiveLock);
                               2180                 :                : 
                               2181                 :                :             /* rename the toast table ... */
 6072 tgl@sss.pgh.pa.us        2182                 :            383 :             snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u",
                               2183                 :                :                      OIDOldHeap);
                               2184                 :            383 :             RenameRelationInternal(newrel->rd_rel->reltoastrelid,
                               2185                 :                :                                    NewToastName, true, false);
                               2186                 :                : 
                               2187                 :                :             /* ... and its valid index too. */
                               2188                 :            383 :             snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u_index",
                               2189                 :                :                      OIDOldHeap);
                               2190                 :                : 
                               2191                 :            383 :             RenameRelationInternal(toastidx,
                               2192                 :                :                                    NewToastName, true, true);
                               2193                 :                : 
                               2194                 :                :             /*
                               2195                 :                :              * Reset the relrewrite for the toast. The command-counter
                               2196                 :                :              * increment is required here as we are about to update the tuple
                               2197                 :                :              * that is updated as part of RenameRelationInternal.
                               2198                 :                :              */
 1852 akapila@postgresql.o     2199                 :            383 :             CommandCounterIncrement();
                               2200                 :            383 :             ResetRelRewrite(newrel->rd_rel->reltoastrelid);
                               2201                 :                :         }
 6072 tgl@sss.pgh.pa.us        2202                 :           1299 :         relation_close(newrel, NoLock);
                               2203                 :                :     }
                               2204                 :                : 
                               2205                 :                :     /* if it's not a catalog table, clear any missing attribute settings */
 3098 andrew@dunslane.net      2206         [ +  + ]:           1461 :     if (!is_system_catalog)
                               2207                 :                :     {
                               2208                 :                :         Relation    newrel;
                               2209                 :                : 
 2799 andres@anarazel.de       2210                 :           1345 :         newrel = table_open(OIDOldHeap, NoLock);
 3098 andrew@dunslane.net      2211                 :           1345 :         RelationClearMissing(newrel);
                               2212                 :           1345 :         relation_close(newrel, NoLock);
                               2213                 :                :     }
 6072 tgl@sss.pgh.pa.us        2214                 :           1461 : }
                               2215                 :                : 
                               2216                 :                : /*
                               2217                 :                :  * Determine which relations to process, when REPACK/CLUSTER is called
                               2218                 :                :  * without specifying a table name.  The exact process depends on whether
                               2219                 :                :  * USING INDEX was given or not, and in any case we only return tables and
                               2220                 :                :  * materialized views that the current user has privileges to repack/cluster.
                               2221                 :                :  *
                               2222                 :                :  * If USING INDEX was given, we scan pg_index to find those that have
                               2223                 :                :  * indisclustered set; if it was not given, scan pg_class and return all
                               2224                 :                :  * tables.
                               2225                 :                :  *
                               2226                 :                :  * Return it as a list of RelToCluster in the given memory context.
                               2227                 :                :  */
                               2228                 :                : static List *
  194 alvherre@kurilemu.de     2229                 :             18 : get_tables_to_repack(RepackCommand cmd, bool usingindex, MemoryContext permcxt)
                               2230                 :                : {
                               2231                 :                :     Relation    catalog;
                               2232                 :                :     TableScanDesc scan;
                               2233                 :                :     HeapTuple   tuple;
 1632 alvherre@alvh.no-ip.     2234                 :             18 :     List       *rtcs = NIL;
                               2235                 :                : 
  194 alvherre@kurilemu.de     2236         [ +  + ]:             18 :     if (usingindex)
                               2237                 :                :     {
                               2238                 :                :         ScanKeyData entry;
                               2239                 :                : 
                               2240                 :                :         /*
                               2241                 :                :          * For USING INDEX, scan pg_index to find those with indisclustered.
                               2242                 :                :          *
                               2243                 :                :          * Note we don't obtain lock of any kind on the index, which means the
                               2244                 :                :          * index or its owning table could be gone or change at any point.  We
                               2245                 :                :          * have to be extra careful when examining catalog state for them.
                               2246                 :                :          */
                               2247                 :             14 :         catalog = table_open(IndexRelationId, AccessShareLock);
                               2248                 :             14 :         ScanKeyInit(&entry,
                               2249                 :                :                     Anum_pg_index_indisclustered,
                               2250                 :                :                     BTEqualStrategyNumber, F_BOOLEQ,
                               2251                 :                :                     BoolGetDatum(true));
                               2252                 :             14 :         scan = table_beginscan_catalog(catalog, 1, &entry);
                               2253         [ +  + ]:             26 :         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
                               2254                 :                :         {
                               2255                 :                :             RelToCluster *rtc;
                               2256                 :                :             Form_pg_index index;
                               2257                 :                :             HeapTuple   classtup;
                               2258                 :                :             Oid         relnamespace;
                               2259                 :                :             char        relpersistence;
                               2260                 :                :             MemoryContext oldcxt;
                               2261                 :                : 
                               2262                 :             12 :             index = (Form_pg_index) GETSTRUCT(tuple);
                               2263                 :                : 
  138                          2264                 :             12 :             classtup = SearchSysCache1(RELOID, ObjectIdGetDatum(index->indrelid));
                               2265         [ -  + ]:             12 :             if (!HeapTupleIsValid(classtup))
  194 alvherre@kurilemu.de     2266                 :UBC           0 :                 continue;
   72 alvherre@kurilemu.de     2267                 :CBC          12 :             relnamespace = ((Form_pg_class) GETSTRUCT(classtup))->relnamespace;
                               2268                 :             12 :             relpersistence = ((Form_pg_class) GETSTRUCT(classtup))->relpersistence;
                               2269                 :             12 :             ReleaseSysCache(classtup);
                               2270                 :                : 
                               2271                 :                :             /* Skip temp relations belonging to other sessions */
                               2272         [ -  + ]:             12 :             if (relpersistence == RELPERSISTENCE_TEMP &&
   72 alvherre@kurilemu.de     2273         [ #  # ]:UBC           0 :                 !isTempOrTempToastNamespace(relnamespace))
  138                          2274                 :              0 :                 continue;
                               2275                 :                : 
                               2276                 :                :             /* noisily skip rels which the user can't process */
  194 alvherre@kurilemu.de     2277         [ +  + ]:CBC          12 :             if (!repack_is_permitted_for_relation(cmd, index->indrelid,
                               2278                 :                :                                                   GetUserId(), false))
                               2279                 :              8 :                 continue;
                               2280                 :                : 
                               2281                 :                :             /* Use a permanent memory context for the result list */
                               2282                 :              4 :             oldcxt = MemoryContextSwitchTo(permcxt);
                               2283                 :              4 :             rtc = palloc_object(RelToCluster);
                               2284                 :              4 :             rtc->tableOid = index->indrelid;
                               2285                 :              4 :             rtc->indexOid = index->indexrelid;
                               2286                 :              4 :             rtcs = lappend(rtcs, rtc);
                               2287                 :              4 :             MemoryContextSwitchTo(oldcxt);
                               2288                 :                :         }
                               2289                 :                :     }
                               2290                 :                :     else
                               2291                 :                :     {
                               2292                 :              4 :         catalog = table_open(RelationRelationId, AccessShareLock);
                               2293                 :              4 :         scan = table_beginscan_catalog(catalog, 0, NULL);
                               2294                 :                : 
                               2295         [ +  + ]:           8692 :         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
                               2296                 :                :         {
                               2297                 :                :             RelToCluster *rtc;
                               2298                 :                :             Form_pg_class class;
                               2299                 :                :             MemoryContext oldcxt;
                               2300                 :                : 
                               2301                 :           8688 :             class = (Form_pg_class) GETSTRUCT(tuple);
                               2302                 :                : 
                               2303                 :                :             /* Can only process plain tables and matviews */
                               2304         [ +  + ]:           8688 :             if (class->relkind != RELKIND_RELATION &&
                               2305         [ +  + ]:           5772 :                 class->relkind != RELKIND_MATVIEW)
                               2306                 :           5740 :                 continue;
                               2307                 :                : 
                               2308                 :                :             /* Skip temp relations belonging to other sessions */
  138                          2309         [ +  + ]:           2948 :             if (class->relpersistence == RELPERSISTENCE_TEMP &&
                               2310         [ -  + ]:             16 :                 !isTempOrTempToastNamespace(class->relnamespace))
  138 alvherre@kurilemu.de     2311                 :UBC           0 :                 continue;
                               2312                 :                : 
                               2313                 :                :             /* noisily skip rels which the user can't process */
  194 alvherre@kurilemu.de     2314         [ +  + ]:CBC        2948 :             if (!repack_is_permitted_for_relation(cmd, class->oid,
                               2315                 :                :                                                   GetUserId(), false))
                               2316                 :           2940 :                 continue;
                               2317                 :                : 
                               2318                 :                :             /* Use a permanent memory context for the result list */
                               2319                 :              8 :             oldcxt = MemoryContextSwitchTo(permcxt);
                               2320                 :              8 :             rtc = palloc_object(RelToCluster);
                               2321                 :              8 :             rtc->tableOid = class->oid;
                               2322                 :              8 :             rtc->indexOid = InvalidOid;
                               2323                 :              8 :             rtcs = lappend(rtcs, rtc);
                               2324                 :              8 :             MemoryContextSwitchTo(oldcxt);
                               2325                 :                :         }
                               2326                 :                :     }
                               2327                 :                : 
                               2328                 :             18 :     table_endscan(scan);
   72                          2329                 :             18 :     table_close(catalog, AccessShareLock);
                               2330                 :                : 
 1632 alvherre@alvh.no-ip.     2331                 :             18 :     return rtcs;
                               2332                 :                : }
                               2333                 :                : 
                               2334                 :                : /*
                               2335                 :                :  * Determine relations to process, when REPACK/CLUSTER is called with a
                               2336                 :                :  * partitioning table; that is, a list of its leaf partitions.  That table has
                               2337                 :                :  * already been opened by caller and is passed as 'rel'.  It is closed and
                               2338                 :                :  * unlocked here before return, so caller should clobber its pointer to avoid
                               2339                 :                :  * confusion.
                               2340                 :                :  *
                               2341                 :                :  * Return it as a list of RelToCluster.
                               2342                 :                :  *
                               2343                 :                :  * XXX we don't support CONCURRENTLY for partitioned tables yet.
                               2344                 :                :  */
                               2345                 :                : static List *
   62 alvherre@kurilemu.de     2346                 :             32 : get_tables_to_repack_partitioned(RepackStmt *stmt, Relation rel,
                               2347                 :                :                                  MemoryContext permcxt)
                               2348                 :                : {
                               2349                 :                :     Oid         relid;
                               2350                 :                :     bool        rel_is_index;
                               2351                 :                :     List       *inhoids;
 1632 alvherre@alvh.no-ip.     2352                 :             32 :     List       *rtcs = NIL;
                               2353                 :                : 
   62 alvherre@kurilemu.de     2354         [ -  + ]:             32 :     Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
                               2355         [ -  + ]:             32 :     Assert(CheckRelationLockedByMe(rel, AccessExclusiveLock, false));
                               2356                 :                : 
                               2357                 :                :     /*
                               2358                 :                :      * We find the list of tables by looking for inheritors.  If USING INDEX
                               2359                 :                :      * was given, look for inheritors of that index, whose name we resolve
                               2360                 :                :      * now.
                               2361                 :                :      *
                               2362                 :                :      * Otherwise we look for inheritors of the table itself.
                               2363                 :                :      */
                               2364         [ +  + ]:             32 :     if (stmt->usingindex)
                               2365                 :                :     {
                               2366                 :                :         /*
                               2367                 :                :          * If no index name was specified when repacking a partitioned table,
                               2368                 :                :          * punt for now.  Maybe we can improve this later.
                               2369                 :                :          */
                               2370         [ +  + ]:             28 :         if (!stmt->indexname)
                               2371                 :                :         {
                               2372         [ +  + ]:              8 :             if (stmt->command == REPACK_COMMAND_CLUSTER)
                               2373         [ +  - ]:              4 :                 ereport(ERROR,
                               2374                 :                :                         errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2375                 :                :                         errmsg("there is no previously clustered index for table \"%s\"",
                               2376                 :                :                                RelationGetRelationName(rel)));
                               2377                 :                :             else
                               2378         [ +  - ]:              4 :                 ereport(ERROR,
                               2379                 :                :                         errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2380                 :                :                 /*- translator: first %s is name of a SQL command, eg. REPACK */
                               2381                 :                :                         errmsg("cannot execute %s on partitioned table \"%s\" USING INDEX with no index name",
                               2382                 :                :                                RepackCommandAsString(stmt->command),
                               2383                 :                :                                RelationGetRelationName(rel)));
                               2384                 :                :         }
                               2385                 :                : 
                               2386                 :             20 :         relid = determine_clustered_index(rel, stmt->usingindex,
                               2387                 :             20 :                                           stmt->indexname);
                               2388         [ -  + ]:             20 :         if (!OidIsValid(relid))
   62 alvherre@kurilemu.de     2389         [ #  # ]:UBC           0 :             elog(ERROR, "unable to determine index to cluster on");
   62 alvherre@kurilemu.de     2390                 :CBC          20 :         check_index_is_clusterable(rel, relid, AccessExclusiveLock);
                               2391                 :                : 
                               2392                 :             16 :         rel_is_index = true;
                               2393                 :                :     }
                               2394                 :                :     else
                               2395                 :                :     {
                               2396                 :              4 :         relid = RelationGetRelid(rel);
                               2397                 :              4 :         rel_is_index = false;
                               2398                 :                :     }
                               2399                 :                : 
                               2400                 :                :     /*
                               2401                 :                :      * Do not lock the children until they're processed.  Note that we do hold
                               2402                 :                :      * a lock on the parent partitioned table.
                               2403                 :                :      */
  194                          2404                 :             20 :     inhoids = find_all_inheritors(relid, NoLock, NULL);
                               2405   [ +  -  +  +  :            148 :     foreach_oid(child_oid, inhoids)
                                              +  + ]
                               2406                 :                :     {
                               2407                 :                :         Oid         table_oid,
                               2408                 :                :                     index_oid;
                               2409                 :                :         RelToCluster *rtc;
                               2410                 :                :         MemoryContext oldcxt;
                               2411                 :                : 
                               2412         [ +  + ]:            108 :         if (rel_is_index)
                               2413                 :                :         {
                               2414                 :                :             /* consider only leaf indexes */
                               2415         [ +  + ]:             80 :             if (get_rel_relkind(child_oid) != RELKIND_INDEX)
                               2416                 :             40 :                 continue;
                               2417                 :                : 
                               2418                 :                :             /*
                               2419                 :                :              * Although we do have a lock on some ancestor partitioned index,
                               2420                 :                :              * we may not have one on the immediate parent, so this lookup may
                               2421                 :                :              * still return invalid.
                               2422                 :                :              */
   62                          2423                 :             40 :             table_oid = IndexGetRelation(child_oid, true);
                               2424         [ -  + ]:             40 :             if (!OidIsValid(table_oid))
   62 alvherre@kurilemu.de     2425                 :UBC           0 :                 continue;
  194 alvherre@kurilemu.de     2426                 :CBC          40 :             index_oid = child_oid;
                               2427                 :                :         }
                               2428                 :                :         else
                               2429                 :                :         {
                               2430                 :                :             /* consider only leaf relations */
                               2431         [ +  + ]:             28 :             if (get_rel_relkind(child_oid) != RELKIND_RELATION)
                               2432                 :             16 :                 continue;
                               2433                 :                : 
                               2434                 :             12 :             table_oid = child_oid;
                               2435                 :             12 :             index_oid = InvalidOid;
                               2436                 :                :         }
                               2437                 :                : 
                               2438                 :                :         /*
                               2439                 :                :          * It's possible that the user does not have privileges to CLUSTER the
                               2440                 :                :          * leaf partition despite having them on the partitioned table.  Skip
                               2441                 :                :          * if so.
                               2442                 :                :          */
   62                          2443         [ +  + ]:             52 :         if (!repack_is_permitted_for_relation(stmt->command, table_oid,
                               2444                 :                :                                               GetUserId(), false))
 1186 nathan@postgresql.or     2445                 :             12 :             continue;
                               2446                 :                : 
                               2447                 :                :         /* Use a permanent memory context for the result list */
  194 alvherre@kurilemu.de     2448                 :             40 :         oldcxt = MemoryContextSwitchTo(permcxt);
  284 michael@paquier.xyz      2449                 :             40 :         rtc = palloc_object(RelToCluster);
  194 alvherre@kurilemu.de     2450                 :             40 :         rtc->tableOid = table_oid;
                               2451                 :             40 :         rtc->indexOid = index_oid;
 1632 alvherre@alvh.no-ip.     2452                 :             40 :         rtcs = lappend(rtcs, rtc);
  194 alvherre@kurilemu.de     2453                 :             40 :         MemoryContextSwitchTo(oldcxt);
                               2454                 :                :     }
                               2455                 :                : 
                               2456                 :                :     /* close parent relation, releasing lock on it */
   62                          2457                 :             20 :     table_close(rel, AccessExclusiveLock);
                               2458                 :                : 
 1632 alvherre@alvh.no-ip.     2459                 :             20 :     return rtcs;
                               2460                 :                : }
                               2461                 :                : 
                               2462                 :                : 
                               2463                 :                : /*
                               2464                 :                :  * Return whether userid has privileges to execute REPACK/CLUSTER on relid.
                               2465                 :                :  *
                               2466                 :                :  * The relation may already be locked by caller, in which case it cannot
                               2467                 :                :  * possibly go missing; otherwise it may have been removed recently.  If
                               2468                 :                :  * it's been removed, silently return false.  If the relation exists but
                               2469                 :                :  * the user doesn't have the required privs, emit a WARNING and return false.
                               2470                 :                :  *
                               2471                 :                :  * Otherwise the relation exists and user has required perms, so return true.
                               2472                 :                :  */
                               2473                 :                : static bool
   32 alvherre@kurilemu.de     2474                 :           3064 : repack_is_permitted_for_relation(RepackCommand cmd, Oid relid, Oid userid,
                               2475                 :                :                                  bool already_locked)
                               2476                 :                : {
   72                          2477                 :           3064 :     bool        is_missing = false;
                               2478                 :                :     AclResult   result;
                               2479                 :                :     char       *relname;
                               2480                 :                : 
  194                          2481   [ +  +  -  + ]:           3064 :     Assert(cmd == REPACK_COMMAND_CLUSTER || cmd == REPACK_COMMAND_REPACK);
   32                          2482   [ +  +  -  + ]:           3064 :     Assert(!already_locked ||
                               2483                 :                :            CheckRelationOidLockedByMe(relid, AccessShareLock, true));
                               2484                 :                : 
   72                          2485                 :           3064 :     result = pg_class_aclcheck_ext(relid, userid, ACL_MAINTAIN, &is_missing);
                               2486                 :                : 
                               2487                 :                :     /*
                               2488                 :                :      * If the relation was concurrently dropped, nothing to do.  This is only
                               2489                 :                :      * reachable when the caller doesn't already have a lock on the relation.
                               2490                 :                :      */
                               2491         [ -  + ]:           3064 :     if (is_missing)
                               2492                 :                :     {
   32 alvherre@kurilemu.de     2493         [ #  # ]:UBC           0 :         Assert(!already_locked);
   72                          2494                 :              0 :         return false;
                               2495                 :                :     }
                               2496                 :                : 
   72 alvherre@kurilemu.de     2497         [ +  + ]:CBC        3064 :     if (result == ACLCHECK_OK)
  921 nathan@postgresql.or     2498                 :            104 :         return true;
                               2499                 :                : 
                               2500                 :                :     /*
                               2501                 :                :      * The relation can also be dropped after we tested its ACL and before we
                               2502                 :                :      * read its relname, so be careful here.
                               2503                 :                :      */
   72 alvherre@kurilemu.de     2504                 :           2960 :     relname = get_rel_name(relid);
                               2505         [ +  - ]:           2960 :     if (relname != NULL)
                               2506                 :                :     {
                               2507         [ +  - ]:           2960 :         ereport(WARNING,
                               2508                 :                :                 errmsg("permission denied to execute %s on \"%s\", skipping it",
                               2509                 :                :                        RepackCommandAsString(cmd), relname));
                               2510                 :           2960 :         pfree(relname);
                               2511                 :                :     }
                               2512                 :                : 
  921 nathan@postgresql.or     2513                 :           2960 :     return false;
                               2514                 :                : }
                               2515                 :                : 
                               2516                 :                : 
                               2517                 :                : /*
                               2518                 :                :  * Given a RepackStmt with an indicated relation name, resolve the relation
                               2519                 :                :  * name, obtain lock on it, then determine what to do based on the relation
                               2520                 :                :  * type: if it's table and not partitioned, repack it as indicated (using an
                               2521                 :                :  * existing clustered index, or following the given one), and return NULL.
                               2522                 :                :  *
                               2523                 :                :  * On the other hand, if the table is partitioned, do nothing further and
                               2524                 :                :  * instead return the opened and locked relcache entry, so that caller can
                               2525                 :                :  * process the partitions using the multiple-table handling code.  In this
                               2526                 :                :  * case, if an index name is given, it's up to the caller to resolve it.
                               2527                 :                :  */
                               2528                 :                : static Relation
  167 alvherre@kurilemu.de     2529                 :            239 : process_single_relation(RepackStmt *stmt, LOCKMODE lockmode, bool isTopLevel,
                               2530                 :                :                         ClusterParams *params)
                               2531                 :                : {
                               2532                 :                :     Relation    rel;
                               2533                 :                :     Oid         tableOid;
                               2534                 :                : 
  194                          2535         [ -  + ]:            239 :     Assert(stmt->relation != NULL);
                               2536   [ +  +  -  + ]:            239 :     Assert(stmt->command == REPACK_COMMAND_CLUSTER ||
                               2537                 :                :            stmt->command == REPACK_COMMAND_REPACK);
                               2538                 :                : 
                               2539                 :                :     /*
                               2540                 :                :      * Make sure ANALYZE is specified if a column list is present.
                               2541                 :                :      */
                               2542   [ +  +  +  + ]:            239 :     if ((params->options & CLUOPT_ANALYZE) == 0 && stmt->relation->va_cols != NIL)
                               2543         [ +  - ]:              4 :         ereport(ERROR,
                               2544                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               2545                 :                :                 errmsg("ANALYZE option must be specified when a column list is provided"));
                               2546                 :                : 
                               2547                 :                :     /* Find, lock, and check permissions on the table. */
                               2548                 :            235 :     tableOid = RangeVarGetRelidExtended(stmt->relation->relation,
                               2549                 :                :                                         lockmode,
                               2550                 :                :                                         0,
                               2551                 :                :                                         RangeVarCallbackMaintainsTable,
                               2552                 :                :                                         NULL);
                               2553                 :            227 :     rel = table_open(tableOid, NoLock);
                               2554                 :                : 
                               2555                 :                :     /*
                               2556                 :                :      * Reject clustering a remote temp table ... their local buffer manager is
                               2557                 :                :      * not going to cope.
                               2558                 :                :      */
                               2559   [ +  +  +  + ]:            227 :     if (RELATION_IS_OTHER_TEMP(rel))
                               2560         [ +  - ]:              1 :         ereport(ERROR,
                               2561                 :                :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               2562                 :                :         /*- translator: first %s is name of a SQL command, eg. REPACK */
                               2563                 :                :                 errmsg("cannot execute %s on temporary tables of other sessions",
                               2564                 :                :                        RepackCommandAsString(stmt->command)));
                               2565                 :                : 
                               2566                 :                :     /*
                               2567                 :                :      * For partitioned tables, let caller handle this.  Otherwise, process it
                               2568                 :                :      * here and we're done.
                               2569                 :                :      */
                               2570         [ +  + ]:            226 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
                               2571                 :             33 :         return rel;
                               2572                 :                :     else
                               2573                 :                :     {
  167                          2574                 :            193 :         Oid         indexOid = InvalidOid;
                               2575                 :                : 
  194                          2576                 :            193 :         indexOid = determine_clustered_index(rel, stmt->usingindex,
                               2577                 :            193 :                                              stmt->indexname);
                               2578         [ +  + ]:            185 :         if (OidIsValid(indexOid))
  167                          2579                 :            139 :             check_index_is_clusterable(rel, indexOid, lockmode);
                               2580                 :                : 
                               2581                 :            173 :         cluster_rel(stmt->command, rel, indexOid, params, isTopLevel);
                               2582                 :                : 
                               2583                 :                :         /*
                               2584                 :                :          * Do an analyze, if requested.  We close the transaction and start a
                               2585                 :                :          * new one, so that we don't hold the stronger lock for longer than
                               2586                 :                :          * needed.
                               2587                 :                :          */
  194                          2588         [ +  + ]:            157 :         if (params->options & CLUOPT_ANALYZE)
                               2589                 :                :         {
                               2590                 :              8 :             VacuumParams vac_params = {0};
                               2591                 :                : 
                               2592                 :              8 :             PopActiveSnapshot();
                               2593                 :              8 :             CommitTransactionCommand();
                               2594                 :                : 
                               2595                 :              8 :             StartTransactionCommand();
                               2596                 :              8 :             PushActiveSnapshot(GetTransactionSnapshot());
                               2597                 :                : 
                               2598                 :              8 :             vac_params.options |= VACOPT_ANALYZE;
                               2599         [ -  + ]:              8 :             if (params->options & CLUOPT_VERBOSE)
  194 alvherre@kurilemu.de     2600                 :UBC           0 :                 vac_params.options |= VACOPT_VERBOSE;
  173 nathan@postgresql.or     2601                 :CBC           8 :             analyze_rel(tableOid, NULL, &vac_params,
  194 alvherre@kurilemu.de     2602                 :              8 :                         stmt->relation->va_cols, true, NULL);
                               2603                 :              8 :             PopActiveSnapshot();
                               2604                 :              8 :             CommandCounterIncrement();
                               2605                 :                :         }
                               2606                 :                : 
                               2607                 :            157 :         return NULL;
                               2608                 :                :     }
                               2609                 :                : }
                               2610                 :                : 
                               2611                 :                : /*
                               2612                 :                :  * Given a relation and the usingindex/indexname options in a
                               2613                 :                :  * REPACK USING INDEX or CLUSTER command, return the OID of the
                               2614                 :                :  * index to use for clustering the table.
                               2615                 :                :  *
                               2616                 :                :  * Caller must hold lock on the relation so that the set of indexes
                               2617                 :                :  * doesn't change, and must call check_index_is_clusterable.
                               2618                 :                :  */
                               2619                 :                : static Oid
                               2620                 :            213 : determine_clustered_index(Relation rel, bool usingindex, const char *indexname)
                               2621                 :                : {
                               2622                 :                :     Oid         indexOid;
                               2623                 :                : 
                               2624   [ +  +  +  + ]:            213 :     if (indexname == NULL && usingindex)
                               2625                 :                :     {
                               2626                 :                :         /*
                               2627                 :                :          * If USING INDEX with no name is given, find a clustered index, or
                               2628                 :                :          * error out if none.
                               2629                 :                :          */
                               2630                 :             20 :         indexOid = InvalidOid;
                               2631   [ +  -  +  +  :             44 :         foreach_oid(idxoid, RelationGetIndexList(rel))
                                              +  + ]
                               2632                 :                :         {
                               2633         [ +  + ]:             20 :             if (get_index_isclustered(idxoid))
                               2634                 :                :             {
                               2635                 :             16 :                 indexOid = idxoid;
                               2636                 :             16 :                 break;
                               2637                 :                :             }
                               2638                 :                :         }
                               2639                 :                : 
                               2640         [ +  + ]:             20 :         if (!OidIsValid(indexOid))
                               2641         [ +  - ]:              4 :             ereport(ERROR,
                               2642                 :                :                     errcode(ERRCODE_UNDEFINED_OBJECT),
                               2643                 :                :                     errmsg("there is no previously clustered index for table \"%s\"",
                               2644                 :                :                            RelationGetRelationName(rel)));
                               2645                 :                :     }
                               2646         [ +  + ]:            193 :     else if (indexname != NULL)
                               2647                 :                :     {
                               2648                 :                :         /* An index was specified; obtain its OID. */
                               2649                 :            147 :         indexOid = get_relname_relid(indexname, rel->rd_rel->relnamespace);
                               2650         [ +  + ]:            147 :         if (!OidIsValid(indexOid))
                               2651         [ +  - ]:              4 :             ereport(ERROR,
                               2652                 :                :                     errcode(ERRCODE_UNDEFINED_OBJECT),
                               2653                 :                :                     errmsg("index \"%s\" for table \"%s\" does not exist",
                               2654                 :                :                            indexname, RelationGetRelationName(rel)));
                               2655                 :                :     }
                               2656                 :                :     else
                               2657                 :             46 :         indexOid = InvalidOid;
                               2658                 :                : 
                               2659                 :            205 :     return indexOid;
                               2660                 :                : }
                               2661                 :                : 
                               2662                 :                : static const char *
                               2663                 :           3467 : RepackCommandAsString(RepackCommand cmd)
                               2664                 :                : {
                               2665   [ +  +  +  - ]:           3467 :     switch (cmd)
                               2666                 :                :     {
                               2667                 :           3043 :         case REPACK_COMMAND_REPACK:
                               2668                 :           3043 :             return "REPACK";
                               2669                 :            237 :         case REPACK_COMMAND_VACUUMFULL:
                               2670                 :            237 :             return "VACUUM";
                               2671                 :            187 :         case REPACK_COMMAND_CLUSTER:
                               2672                 :            187 :             return "CLUSTER";
                               2673                 :                :     }
  194 alvherre@kurilemu.de     2674                 :UBC           0 :     return "???";             /* keep compiler quiet */
                               2675                 :                : }
                               2676                 :                : 
                               2677                 :                : /*
                               2678                 :                :  * Apply all the changes stored in 'file'.
                               2679                 :                :  */
                               2680                 :                : static void
  167 alvherre@kurilemu.de     2681                 :CBC          18 : apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt)
                               2682                 :                : {
                               2683                 :             18 :     ConcurrentChangeKind kind = '\0';
                               2684                 :             18 :     Relation    rel = chgcxt->cc_rel;
                               2685                 :                :     TupleTableSlot *spilled_tuple;
                               2686                 :                :     TupleTableSlot *old_update_tuple;
                               2687                 :                :     TupleTableSlot *ondisk_tuple;
                               2688                 :             18 :     bool        have_old_tuple = false;
                               2689                 :                :     MemoryContext oldcxt;
                               2690                 :                : 
                               2691                 :             18 :     spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel),
                               2692                 :                :                                              &TTSOpsVirtual);
                               2693                 :             18 :     ondisk_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel),
                               2694                 :                :                                             table_slot_callbacks(rel));
                               2695                 :             18 :     old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel),
                               2696                 :                :                                                 &TTSOpsVirtual);
                               2697                 :                : 
                               2698         [ +  + ]:             18 :     oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(chgcxt->cc_estate));
                               2699                 :                : 
                               2700                 :                :     while (true)
                               2701                 :             42 :     {
                               2702                 :                :         size_t      nread;
                               2703                 :             60 :         ConcurrentChangeKind prevkind = kind;
                               2704                 :                : 
                               2705         [ -  + ]:             60 :         CHECK_FOR_INTERRUPTS();
                               2706                 :                : 
                               2707                 :             60 :         nread = BufFileReadMaybeEOF(file, &kind, 1, true);
                               2708         [ +  + ]:             60 :         if (nread == 0)         /* done with the file? */
                               2709                 :             18 :             break;
                               2710                 :                : 
                               2711                 :                :         /*
                               2712                 :                :          * If this is the old tuple for an update, read it into the tuple slot
                               2713                 :                :          * and go to the next one.  The update itself will be executed on the
                               2714                 :                :          * next iteration, when we receive the NEW tuple.
                               2715                 :                :          */
                               2716         [ +  + ]:             42 :         if (kind == CHANGE_UPDATE_OLD)
                               2717                 :                :         {
                               2718                 :              8 :             restore_tuple(file, rel, old_update_tuple);
                               2719                 :              8 :             have_old_tuple = true;
                               2720                 :              8 :             continue;
                               2721                 :                :         }
                               2722                 :                : 
                               2723                 :                :         /*
                               2724                 :                :          * Just before an UPDATE or DELETE, we must update the command
                               2725                 :                :          * counter, because the change could refer to a tuple that we have
                               2726                 :                :          * just inserted; and before an INSERT, we have to do this also if the
                               2727                 :                :          * previous command was either update or delete.
                               2728                 :                :          *
                               2729                 :                :          * With this approach we don't spend so many CCIs for long strings of
                               2730                 :                :          * only INSERTs, which can't affect one another.
                               2731                 :                :          */
                               2732   [ +  +  +  + ]:             34 :         if (kind == CHANGE_UPDATE_NEW || kind == CHANGE_DELETE ||
                               2733   [ +  -  +  +  :              7 :             (kind == CHANGE_INSERT && (prevkind == CHANGE_UPDATE_NEW ||
                                              +  + ]
                               2734                 :                :                                        prevkind == CHANGE_DELETE)))
                               2735                 :                :         {
                               2736                 :             31 :             CommandCounterIncrement();
                               2737                 :             31 :             UpdateActiveSnapshotCommandId();
                               2738                 :                :         }
                               2739                 :                : 
                               2740                 :                :         /*
                               2741                 :                :          * Now restore the tuple into the slot and execute the change.
                               2742                 :                :          */
                               2743                 :             34 :         restore_tuple(file, rel, spilled_tuple);
                               2744                 :                : 
                               2745         [ +  + ]:             34 :         if (kind == CHANGE_INSERT)
                               2746                 :                :         {
                               2747                 :              7 :             apply_concurrent_insert(rel, spilled_tuple, chgcxt);
                               2748                 :                :         }
                               2749         [ +  + ]:             27 :         else if (kind == CHANGE_DELETE)
                               2750                 :                :         {
                               2751                 :                :             bool        found;
                               2752                 :                : 
                               2753                 :                :             /* Find the tuple to be deleted */
                               2754                 :              3 :             found = find_target_tuple(rel, chgcxt, spilled_tuple, ondisk_tuple);
                               2755         [ -  + ]:              3 :             if (!found)
  115 alvherre@kurilemu.de     2756         [ #  # ]:UBC           0 :                 elog(ERROR, "could not find target tuple");
  167 alvherre@kurilemu.de     2757                 :CBC           3 :             apply_concurrent_delete(rel, ondisk_tuple);
                               2758                 :                :         }
                               2759         [ +  - ]:             24 :         else if (kind == CHANGE_UPDATE_NEW)
                               2760                 :                :         {
                               2761                 :                :             TupleTableSlot *key;
                               2762                 :                :             bool        found;
                               2763                 :                : 
                               2764         [ +  + ]:             24 :             if (have_old_tuple)
                               2765                 :              8 :                 key = old_update_tuple;
                               2766                 :                :             else
                               2767                 :             16 :                 key = spilled_tuple;
                               2768                 :                : 
                               2769                 :                :             /* Find the tuple to be updated or deleted. */
                               2770                 :             24 :             found = find_target_tuple(rel, chgcxt, key, ondisk_tuple);
                               2771         [ -  + ]:             24 :             if (!found)
  115 alvherre@kurilemu.de     2772         [ #  # ]:UBC           0 :                 elog(ERROR, "could not find target tuple");
                               2773                 :                : 
                               2774                 :                :             /*
                               2775                 :                :              * If 'tup' contains TOAST pointers, they point to the old
                               2776                 :                :              * relation's toast. Copy the corresponding TOAST pointers for the
                               2777                 :                :              * new relation from the existing tuple. (The fact that we
                               2778                 :                :              * received a TOAST pointer here implies that the attribute hasn't
                               2779                 :                :              * changed.)
                               2780                 :                :              */
  167 alvherre@kurilemu.de     2781                 :CBC          24 :             adjust_toast_pointers(rel, spilled_tuple, ondisk_tuple);
                               2782                 :                : 
                               2783                 :             24 :             apply_concurrent_update(rel, spilled_tuple, ondisk_tuple, chgcxt);
                               2784                 :                : 
                               2785                 :             24 :             ExecClearTuple(old_update_tuple);
                               2786                 :             24 :             have_old_tuple = false;
                               2787                 :                :         }
                               2788                 :                :         else
  167 alvherre@kurilemu.de     2789         [ #  # ]:UBC           0 :             elog(ERROR, "unrecognized kind of change: %d", kind);
                               2790                 :                : 
  167 alvherre@kurilemu.de     2791         [ +  - ]:CBC          34 :         ResetPerTupleExprContext(chgcxt->cc_estate);
                               2792                 :                :     }
                               2793                 :                : 
                               2794                 :                :     /* Cleanup. */
                               2795                 :             18 :     ExecDropSingleTupleTableSlot(spilled_tuple);
                               2796                 :             18 :     ExecDropSingleTupleTableSlot(ondisk_tuple);
                               2797                 :             18 :     ExecDropSingleTupleTableSlot(old_update_tuple);
                               2798                 :                : 
                               2799                 :             18 :     MemoryContextSwitchTo(oldcxt);
                               2800                 :             18 : }
                               2801                 :                : 
                               2802                 :                : /*
                               2803                 :                :  * Apply an insert from the spill of concurrent changes to the new copy of the
                               2804                 :                :  * table.
                               2805                 :                :  */
                               2806                 :                : static void
                               2807                 :              7 : apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
                               2808                 :                :                         ChangeContext *chgcxt)
                               2809                 :                : {
                               2810                 :                :     /* Put the tuple in the table, but make sure it won't be decoded */
                               2811                 :              7 :     table_tuple_insert(rel, slot, GetCurrentCommandId(true),
                               2812                 :                :                        TABLE_INSERT_NO_LOGICAL, NULL);
                               2813                 :                : 
                               2814                 :                :     /* Update indexes with this new tuple. */
                               2815                 :              7 :     ExecInsertIndexTuples(chgcxt->cc_rri,
                               2816                 :                :                           chgcxt->cc_estate,
                               2817                 :                :                           0,
                               2818                 :                :                           slot,
                               2819                 :                :                           NIL, NULL);
                               2820                 :              7 :     pgstat_progress_incr_param(PROGRESS_REPACK_HEAP_TUPLES_INSERTED, 1);
                               2821                 :              7 : }
                               2822                 :                : 
                               2823                 :                : /*
                               2824                 :                :  * Apply an update from the spill of concurrent changes to the new copy of the
                               2825                 :                :  * table.
                               2826                 :                :  */
                               2827                 :                : static void
                               2828                 :             24 : apply_concurrent_update(Relation rel, TupleTableSlot *spilled_tuple,
                               2829                 :                :                         TupleTableSlot *ondisk_tuple,
                               2830                 :                :                         ChangeContext *chgcxt)
                               2831                 :                : {
                               2832                 :                :     LockTupleMode lockmode;
                               2833                 :                :     TM_FailureData tmfd;
                               2834                 :                :     TU_UpdateIndexes update_indexes;
                               2835                 :                :     TM_Result   res;
                               2836                 :                : 
                               2837                 :                :     /*
                               2838                 :                :      * Carry out the update, skipping logical decoding for it.
                               2839                 :                :      */
                               2840                 :             24 :     res = table_tuple_update(rel, &(ondisk_tuple->tts_tid), spilled_tuple,
                               2841                 :                :                              GetCurrentCommandId(true),
                               2842                 :                :                              TABLE_UPDATE_NO_LOGICAL,
                               2843                 :                :                              InvalidSnapshot,
                               2844                 :                :                              InvalidSnapshot,
                               2845                 :                :                              false,
                               2846                 :                :                              &tmfd, &lockmode, &update_indexes);
                               2847         [ -  + ]:             24 :     if (res != TM_Ok)
  167 alvherre@kurilemu.de     2848         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2849                 :                :                 errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                               2850                 :                :                 errmsg("could not apply concurrent %s on relation \"%s\"",
                               2851                 :                :                        "UPDATE", RelationGetRelationName(rel)));
                               2852                 :                : 
  167 alvherre@kurilemu.de     2853         [ +  + ]:CBC          24 :     if (update_indexes != TU_None)
                               2854                 :                :     {
                               2855                 :              8 :         uint32      flags = EIIT_IS_UPDATE;
                               2856                 :                : 
                               2857         [ -  + ]:              8 :         if (update_indexes == TU_Summarizing)
  167 alvherre@kurilemu.de     2858                 :UBC           0 :             flags |= EIIT_ONLY_SUMMARIZING;
  167 alvherre@kurilemu.de     2859                 :CBC           8 :         ExecInsertIndexTuples(chgcxt->cc_rri,
                               2860                 :                :                               chgcxt->cc_estate,
                               2861                 :                :                               flags,
                               2862                 :                :                               spilled_tuple,
                               2863                 :                :                               NIL, NULL);
                               2864                 :                :     }
                               2865                 :                : 
                               2866                 :             24 :     pgstat_progress_incr_param(PROGRESS_REPACK_HEAP_TUPLES_UPDATED, 1);
                               2867                 :             24 : }
                               2868                 :                : 
                               2869                 :                : static void
                               2870                 :              3 : apply_concurrent_delete(Relation rel, TupleTableSlot *slot)
                               2871                 :                : {
                               2872                 :                :     TM_Result   res;
                               2873                 :                :     TM_FailureData tmfd;
                               2874                 :                : 
                               2875                 :                :     /*
                               2876                 :                :      * Delete tuple from the new heap, skipping logical decoding for it.
                               2877                 :                :      */
                               2878                 :              3 :     res = table_tuple_delete(rel, &(slot->tts_tid),
                               2879                 :                :                              GetCurrentCommandId(true),
                               2880                 :                :                              TABLE_DELETE_NO_LOGICAL,
                               2881                 :                :                              InvalidSnapshot, InvalidSnapshot,
                               2882                 :                :                              false,
                               2883                 :                :                              &tmfd);
                               2884                 :                : 
                               2885         [ -  + ]:              3 :     if (res != TM_Ok)
  167 alvherre@kurilemu.de     2886         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2887                 :                :                 errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                               2888                 :                :                 errmsg("could not apply concurrent %s on relation \"%s\"",
                               2889                 :                :                        "DELETE", RelationGetRelationName(rel)));
                               2890                 :                : 
  167 alvherre@kurilemu.de     2891                 :CBC           3 :     pgstat_progress_incr_param(PROGRESS_REPACK_HEAP_TUPLES_DELETED, 1);
                               2892                 :              3 : }
                               2893                 :                : 
                               2894                 :                : /*
                               2895                 :                :  * Read tuple from file and put it in the input slot.  All memory is allocated
                               2896                 :                :  * in the current memory context; caller is responsible for freeing it as
                               2897                 :                :  * appropriate.
                               2898                 :                :  *
                               2899                 :                :  * External attributes are stored in separate memory chunks, in order to avoid
                               2900                 :                :  * exceeding MaxAllocSize - that could happen if the individual attributes are
                               2901                 :                :  * smaller than MaxAllocSize but the whole tuple is bigger.
                               2902                 :                :  */
                               2903                 :                : static void
                               2904                 :             42 : restore_tuple(BufFile *file, Relation relation, TupleTableSlot *slot)
                               2905                 :                : {
                               2906                 :                :     uint32      t_len;
                               2907                 :                :     HeapTuple   tup;
                               2908                 :                :     int         natt_ext;
                               2909                 :                : 
                               2910                 :                :     /* Read the tuple. */
                               2911                 :             42 :     BufFileReadExact(file, &t_len, sizeof(t_len));
                               2912                 :             42 :     tup = (HeapTuple) palloc(HEAPTUPLESIZE + t_len);
                               2913                 :             42 :     tup->t_data = (HeapTupleHeader) ((char *) tup + HEAPTUPLESIZE);
                               2914                 :             42 :     BufFileReadExact(file, tup->t_data, t_len);
                               2915                 :             42 :     tup->t_len = t_len;
                               2916                 :             42 :     ItemPointerSetInvalid(&tup->t_self);
                               2917                 :             42 :     tup->t_tableOid = RelationGetRelid(relation);
                               2918                 :                : 
                               2919                 :                :     /*
                               2920                 :                :      * Put the tuple we read in a slot. This deforms it, so that we can hack
                               2921                 :                :      * the external attributes in place.
                               2922                 :                :      */
                               2923                 :             42 :     ExecForceStoreHeapTuple(tup, slot, false);
                               2924                 :                : 
                               2925                 :                :     /*
                               2926                 :                :      * Next, read any attributes we stored separately into the tts_values
                               2927                 :                :      * array elements expecting them, if any.  This matches
                               2928                 :                :      * repack_store_change.
                               2929                 :                :      */
                               2930                 :             42 :     BufFileReadExact(file, &natt_ext, sizeof(natt_ext));
                               2931         [ +  + ]:             42 :     if (natt_ext > 0)
                               2932                 :                :     {
                               2933                 :             12 :         TupleDesc   desc = slot->tts_tupleDescriptor;
                               2934                 :                : 
                               2935         [ +  + ]:             69 :         for (int i = 0; i < desc->natts; i++)
                               2936                 :                :         {
                               2937                 :             57 :             CompactAttribute *attr = TupleDescCompactAttr(desc, i);
                               2938                 :                :             varlena    *varlen;
                               2939                 :                :             uint64      chunk_header;
                               2940                 :                :             void       *value;
                               2941                 :                :             Size        varlensz;
                               2942                 :                : 
                               2943   [ +  +  +  + ]:             57 :             if (attr->attisdropped || attr->attlen != -1)
                               2944                 :             41 :                 continue;
                               2945         [ -  + ]:             23 :             if (slot_attisnull(slot, i + 1))
  167 alvherre@kurilemu.de     2946                 :UBC           0 :                 continue;
  167 alvherre@kurilemu.de     2947                 :CBC          23 :             varlen = (varlena *) DatumGetPointer(slot->tts_values[i]);
                               2948         [ +  + ]:             23 :             if (!VARATT_IS_EXTERNAL_INDIRECT(varlen))
                               2949                 :              7 :                 continue;
                               2950                 :             16 :             slot_getsomeattrs(slot, i + 1);
                               2951                 :                : 
                               2952                 :             16 :             BufFileReadExact(file, &chunk_header, VARHDRSZ);
                               2953                 :             16 :             varlensz = VARSIZE_ANY(&chunk_header);
                               2954                 :                : 
                               2955                 :             16 :             value = palloc(varlensz);
  145                          2956                 :             16 :             memcpy(value, &chunk_header, VARHDRSZ);
  167                          2957                 :             16 :             BufFileReadExact(file, (char *) value + VARHDRSZ, varlensz - VARHDRSZ);
                               2958                 :                : 
                               2959                 :             16 :             slot->tts_values[i] = PointerGetDatum(value);
                               2960                 :             16 :             natt_ext--;
                               2961         [ -  + ]:             16 :             if (natt_ext < 0)
   96 alvherre@kurilemu.de     2962         [ #  # ]:UBC           0 :                 elog(ERROR, "insufficient number of attributes stored separately");
                               2963                 :                :         }
                               2964                 :                : 
   96 alvherre@kurilemu.de     2965         [ -  + ]:CBC          12 :         if (natt_ext != 0)
   96 alvherre@kurilemu.de     2966         [ #  # ]:UBC           0 :             elog(ERROR,
                               2967                 :                :                  "unexpected number of attributes stored separately (%d remaining)",
                               2968                 :                :                  natt_ext);
                               2969                 :                :     }
  167 alvherre@kurilemu.de     2970                 :CBC          42 : }
                               2971                 :                : 
                               2972                 :                : /*
                               2973                 :                :  * Adjust 'dest' replacing any EXTERNAL_ONDISK toast pointers with the
                               2974                 :                :  * corresponding ones from 'src'.
                               2975                 :                :  */
                               2976                 :                : static void
                               2977                 :             24 : adjust_toast_pointers(Relation relation, TupleTableSlot *dest, TupleTableSlot *src)
                               2978                 :                : {
                               2979                 :             24 :     TupleDesc   desc = dest->tts_tupleDescriptor;
                               2980                 :                : 
                               2981         [ +  + ]:            118 :     for (int i = 0; i < desc->natts; i++)
                               2982                 :                :     {
                               2983                 :             94 :         CompactAttribute *attr = TupleDescCompactAttr(desc, i);
                               2984                 :                :         varlena    *varlena_dst;
                               2985                 :                : 
                               2986         [ +  + ]:             94 :         if (attr->attisdropped)
                               2987                 :             24 :             continue;
                               2988         [ +  + ]:             70 :         if (attr->attlen != -1)
                               2989                 :             38 :             continue;
                               2990         [ -  + ]:             32 :         if (slot_attisnull(dest, i + 1))
  167 alvherre@kurilemu.de     2991                 :UBC           0 :             continue;
                               2992                 :                : 
  167 alvherre@kurilemu.de     2993                 :CBC          32 :         slot_getsomeattrs(dest, i + 1);
                               2994                 :                : 
                               2995                 :             32 :         varlena_dst = (varlena *) DatumGetPointer(dest->tts_values[i]);
                               2996         [ +  + ]:             32 :         if (!VARATT_IS_EXTERNAL_ONDISK(varlena_dst))
                               2997                 :             30 :             continue;
                               2998                 :              2 :         slot_getsomeattrs(src, i + 1);
                               2999                 :                : 
                               3000                 :              2 :         dest->tts_values[i] = src->tts_values[i];
                               3001                 :                :     }
                               3002                 :             24 : }
                               3003                 :                : 
                               3004                 :                : /*
                               3005                 :                :  * Find the tuple to be updated or deleted by the given data change, whose
                               3006                 :                :  * tuple has already been loaded into locator.
                               3007                 :                :  *
                               3008                 :                :  * If the tuple is found, put it in retrieved and return true.  If the tuple is
                               3009                 :                :  * not found, return false.
                               3010                 :                :  */
                               3011                 :                : static bool
                               3012                 :             27 : find_target_tuple(Relation rel, ChangeContext *chgcxt, TupleTableSlot *locator,
                               3013                 :                :                   TupleTableSlot *retrieved)
                               3014                 :                : {
                               3015                 :             27 :     Form_pg_index idx = chgcxt->cc_ident_index->rd_index;
                               3016                 :                :     IndexScanDesc scan;
  132                          3017                 :             27 :     bool        retval = false;
                               3018                 :                : 
                               3019                 :                :     /*
                               3020                 :                :      * Scan key is passed by caller, so it does not have to be constructed
                               3021                 :                :      * multiple times. Key entries have all fields initialized, except for
                               3022                 :                :      * sk_argument.
                               3023                 :                :      *
                               3024                 :                :      * Use the incoming tuple to finalize the scan key.
                               3025                 :                :      */
  167                          3026         [ +  + ]:             56 :     for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
                               3027                 :                :     {
                               3028                 :             29 :         ScanKey     entry = &chgcxt->cc_ident_key[i];
                               3029                 :             29 :         AttrNumber  attno = idx->indkey.values[i];
                               3030                 :                : 
                               3031                 :             29 :         entry->sk_argument = locator->tts_values[attno - 1];
                               3032         [ -  + ]:             29 :         Assert(!locator->tts_isnull[attno - 1]);
                               3033                 :                :     }
                               3034                 :                : 
                               3035                 :                :     /* XXX no instrumentation for now */
    5 pg@bowt.ie               3036                 :GNC          27 :     scan = index_beginscan(rel, chgcxt->cc_ident_index, false, GetActiveSnapshot(),
                               3037                 :                :                            NULL, chgcxt->cc_ident_key_nentries, 0, 0);
  167 alvherre@kurilemu.de     3038                 :CBC          27 :     index_rescan(scan, chgcxt->cc_ident_key, chgcxt->cc_ident_key_nentries, NULL, 0);
    5 pg@bowt.ie               3039         [ +  - ]:GNC          28 :     while (table_index_getnext_slot(scan, ForwardScanDirection, retrieved))
                               3040                 :                :     {
                               3041                 :                :         /* Be wary of temporal constraints */
  132 alvherre@kurilemu.de     3042   [ +  +  +  + ]:CBC          28 :         if (scan->xs_recheck && !identity_key_equal(chgcxt, locator, retrieved))
                               3043                 :                :         {
                               3044         [ -  + ]:              1 :             CHECK_FOR_INTERRUPTS();
                               3045                 :              1 :             continue;
                               3046                 :                :         }
                               3047                 :                : 
                               3048                 :             27 :         retval = true;
                               3049                 :             27 :         break;
                               3050                 :                :     }
  167                          3051                 :             27 :     index_endscan(scan);
                               3052                 :                : 
                               3053                 :             27 :     return retval;
                               3054                 :                : }
                               3055                 :                : 
                               3056                 :                : /*
                               3057                 :                :  * Check whether the candidate tuple matches the locator tuple on all replica
                               3058                 :                :  * identity key columns, using the same equality operators as the identity
                               3059                 :                :  * index scan.  The locator tuple has already been loaded into cc_ident_key.
                               3060                 :                :  *
                               3061                 :                :  * This is needed to filter lossy index matches, such as GiST multirange scans
                               3062                 :                :  * used for temporal constraints.
                               3063                 :                :  */
                               3064                 :                : static bool
  132                          3065                 :              2 : identity_key_equal(ChangeContext *chgcxt, TupleTableSlot *locator,
                               3066                 :                :                    TupleTableSlot *candidate)
                               3067                 :                : {
                               3068                 :              2 :     slot_getsomeattrs(locator, chgcxt->cc_last_key_attno);
                               3069                 :              2 :     slot_getsomeattrs(candidate, chgcxt->cc_last_key_attno);
                               3070                 :                : 
                               3071         [ +  + ]:              4 :     for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
                               3072                 :                :     {
                               3073                 :              3 :         ScanKey     entry = &chgcxt->cc_ident_key[i];
                               3074                 :              3 :         AttrNumber  attno = chgcxt->cc_ident_index->rd_index->indkey.values[i];
                               3075                 :                : 
                               3076         [ -  + ]:              3 :         Assert(attno > 0);
                               3077                 :                : 
                               3078         [ -  + ]:              3 :         if (locator->tts_isnull[attno - 1] != candidate->tts_isnull[attno - 1])
  132 alvherre@kurilemu.de     3079                 :UBC           0 :             return false;
                               3080                 :                : 
  132 alvherre@kurilemu.de     3081         [ -  + ]:CBC           3 :         if (locator->tts_isnull[attno - 1])
  132 alvherre@kurilemu.de     3082                 :UBC           0 :             continue;
                               3083                 :                : 
  132 alvherre@kurilemu.de     3084         [ +  + ]:CBC           3 :         if (!DatumGetBool(FunctionCall2Coll(&entry->sk_func,
                               3085                 :                :                                             entry->sk_collation,
                               3086                 :              3 :                                             candidate->tts_values[attno - 1],
                               3087                 :                :                                             entry->sk_argument)))
                               3088                 :              1 :             return false;
                               3089                 :                :     }
                               3090                 :                : 
                               3091                 :              1 :     return true;
                               3092                 :                : }
                               3093                 :                : 
                               3094                 :                : /*
                               3095                 :                :  * Decode and apply concurrent changes, up to (and including) the record whose
                               3096                 :                :  * LSN is 'end_of_wal'.
                               3097                 :                :  *
                               3098                 :                :  * XXX the names "process_concurrent_changes" and "apply_concurrent_changes"
                               3099                 :                :  * are far too similar to each other.
                               3100                 :                :  */
                               3101                 :                : static void
  167                          3102                 :             18 : process_concurrent_changes(XLogRecPtr end_of_wal, ChangeContext *chgcxt, bool done)
                               3103                 :                : {
                               3104                 :                :     DecodingWorkerShared *shared;
                               3105                 :                :     char        fname[MAXPGPATH];
                               3106                 :                :     BufFile    *file;
                               3107                 :                : 
                               3108                 :             18 :     pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                               3109                 :                :                                  PROGRESS_REPACK_PHASE_CATCH_UP);
                               3110                 :                : 
                               3111                 :                :     /* Ask the worker for the file. */
                               3112                 :             18 :     shared = (DecodingWorkerShared *) dsm_segment_address(decoding_worker->seg);
                               3113                 :             18 :     SpinLockAcquire(&shared->mutex);
                               3114                 :             18 :     shared->lsn_upto = end_of_wal;
                               3115                 :             18 :     shared->done = done;
                               3116                 :             18 :     SpinLockRelease(&shared->mutex);
                               3117                 :                : 
                               3118                 :                :     /*
                               3119                 :                :      * The worker needs to finish processing of the current WAL record. Even
                               3120                 :                :      * if it's idle, it'll need to close the output file. Thus we're likely to
                               3121                 :                :      * wait, so prepare for sleep.
                               3122                 :                :      */
                               3123                 :             18 :     ConditionVariablePrepareToSleep(&shared->cv);
                               3124                 :                :     for (;;)
                               3125                 :             18 :     {
                               3126                 :                :         int         last_exported;
                               3127                 :                : 
                               3128                 :             36 :         SpinLockAcquire(&shared->mutex);
                               3129                 :             36 :         last_exported = shared->last_exported;
                               3130                 :             36 :         SpinLockRelease(&shared->mutex);
                               3131                 :                : 
                               3132                 :                :         /*
                               3133                 :                :          * Has the worker exported the file we are waiting for?
                               3134                 :                :          */
                               3135         [ +  + ]:             36 :         if (last_exported == chgcxt->cc_file_seq)
                               3136                 :             18 :             break;
                               3137                 :                : 
                               3138                 :             18 :         ConditionVariableSleep(&shared->cv, WAIT_EVENT_REPACK_WORKER_EXPORT);
                               3139                 :                :     }
                               3140                 :             18 :     ConditionVariableCancelSleep();
                               3141                 :                : 
                               3142                 :                :     /* Open the file. */
                               3143                 :             18 :     DecodingWorkerFileName(fname, shared->relid, chgcxt->cc_file_seq);
                               3144                 :             18 :     file = BufFileOpenFileSet(&shared->sfs.fs, fname, O_RDONLY, false);
                               3145                 :             18 :     apply_concurrent_changes(file, chgcxt);
                               3146                 :                : 
                               3147                 :             18 :     BufFileClose(file);
                               3148                 :                : 
                               3149                 :                :     /* Get ready for the next file. */
                               3150                 :             18 :     chgcxt->cc_file_seq++;
                               3151                 :             18 : }
                               3152                 :                : 
                               3153                 :                : /*
                               3154                 :                :  * Initialize the ChangeContext struct for the given relation, with
                               3155                 :                :  * the given index as identity index.
                               3156                 :                :  */
                               3157                 :                : static void
                               3158                 :              9 : initialize_change_context(ChangeContext *chgcxt,
                               3159                 :                :                           Relation relation, Oid ident_index_id)
                               3160                 :                : {
                               3161                 :              9 :     chgcxt->cc_rel = relation;
                               3162                 :                : 
                               3163                 :                :     /* Only initialize fields needed by ExecInsertIndexTuples(). */
                               3164                 :              9 :     chgcxt->cc_estate = CreateExecutorState();
                               3165                 :                : 
                               3166                 :                :     /*
                               3167                 :                :      * Set up a range table for the executor, containing our repacked table as
                               3168                 :                :      * its only member.
                               3169                 :                :      */
                               3170                 :                :     {
                               3171                 :                :         RangeTblEntry *rte;
   79                          3172                 :              9 :         TupleDesc   desc = RelationGetDescr(relation);
                               3173                 :              9 :         List       *perminfos = NIL;
                               3174                 :              9 :         Bitmapset  *updatedCols = NULL;
                               3175                 :                :         RTEPermissionInfo *perminfo;
                               3176                 :                : 
                               3177                 :                :         /*
                               3178                 :                :          * For our use, the RTE only needs to have perminfoindex initialized,
                               3179                 :                :          * but there's no reason to not set the fields whose values we have at
                               3180                 :                :          * hand.
                               3181                 :                :          */
                               3182                 :              9 :         rte = makeNode(RangeTblEntry);
                               3183                 :              9 :         rte->rtekind = RTE_RELATION;
                               3184                 :              9 :         rte->relid = RelationGetRelid(relation);
                               3185                 :              9 :         rte->relkind = RelationGetForm(relation)->relkind;
                               3186                 :                :         /* Create the RTEPermissionInfo instance (and set ->perminfoindex). */
                               3187                 :              9 :         addRTEPermissionInfo(&perminfos, rte);
                               3188                 :                : 
                               3189                 :                :         /*
                               3190                 :                :          * Initialize updatedCols to show that all columns are updated.  This
                               3191                 :                :          * is of course not necessarily true, and we cannot know this early;
                               3192                 :                :          * but this is only used by ExecInsertIndexTuples to flag index
                               3193                 :                :          * updates with no logical value changes, so if it's wrong, nothing
                               3194                 :                :          * terribly bad happens. We may want to improve this someday though.
                               3195                 :                :          *
                               3196                 :                :          * Don't claim that dropped columns are changed though.
                               3197                 :                :          */
                               3198         [ +  + ]:             31 :         for (int i = 0; i < desc->natts; i++)
                               3199                 :                :         {
                               3200                 :             22 :             CompactAttribute *attr = TupleDescCompactAttr(desc, i);
                               3201                 :                : 
                               3202         [ +  + ]:             22 :             if (attr->attisdropped)
                               3203                 :              2 :                 continue;
                               3204                 :             20 :             updatedCols = bms_add_member(updatedCols,
                               3205                 :                :                                          i + 1 - FirstLowInvalidHeapAttributeNumber);
                               3206                 :                :         }
                               3207                 :                : 
                               3208                 :                :         /* install updatedCols in the right place */
                               3209                 :              9 :         perminfo = getRTEPermissionInfo(perminfos, rte);
                               3210                 :              9 :         perminfo->updatedCols = updatedCols;
                               3211                 :                : 
                               3212                 :                :         /* finally we can initialize the range table proper */
                               3213                 :              9 :         ExecInitRangeTable(chgcxt->cc_estate, list_make1(rte), perminfos,
                               3214                 :                :                            bms_make_singleton(1));
                               3215                 :                :     }
                               3216                 :                : 
                               3217                 :                :     /* Set up our ResultRelInfo to use for index updates */
                               3218                 :              9 :     chgcxt->cc_rri = makeNode(ResultRelInfo);
                               3219                 :              9 :     InitResultRelInfo(chgcxt->cc_rri, relation, 1, NULL, 0);
  167                          3220                 :              9 :     ExecOpenIndices(chgcxt->cc_rri, false);
                               3221                 :                : 
                               3222                 :                :     /*
                               3223                 :                :      * The table's relcache entry already has the relcache entry for the
                               3224                 :                :      * identity index; find that.
                               3225                 :                :      */
                               3226                 :              9 :     chgcxt->cc_ident_index = NULL;
                               3227         [ +  - ]:              9 :     for (int i = 0; i < chgcxt->cc_rri->ri_NumIndices; i++)
                               3228                 :                :     {
                               3229                 :                :         Relation    ind_rel;
                               3230                 :                : 
                               3231                 :              9 :         ind_rel = chgcxt->cc_rri->ri_IndexRelationDescs[i];
                               3232         [ +  - ]:              9 :         if (ind_rel->rd_id == ident_index_id)
                               3233                 :                :         {
                               3234                 :              9 :             chgcxt->cc_ident_index = ind_rel;
                               3235                 :              9 :             break;
                               3236                 :                :         }
                               3237                 :                :     }
                               3238         [ -  + ]:              9 :     if (chgcxt->cc_ident_index == NULL)
  115 alvherre@kurilemu.de     3239         [ #  # ]:UBC           0 :         elog(ERROR, "could not find identity index");
                               3240                 :                : 
                               3241                 :                :     /* Set up for scanning said identity index */
                               3242                 :                :     {
                               3243                 :                :         Form_pg_index indexForm;
                               3244                 :                : 
  167 alvherre@kurilemu.de     3245                 :CBC           9 :         indexForm = chgcxt->cc_ident_index->rd_index;
                               3246                 :              9 :         chgcxt->cc_ident_key_nentries = indexForm->indnkeyatts;
                               3247                 :              9 :         chgcxt->cc_ident_key = (ScanKey) palloc_array(ScanKeyData, indexForm->indnkeyatts);
                               3248         [ +  + ]:             20 :         for (int i = 0; i < indexForm->indnkeyatts; i++)
                               3249                 :                :         {
                               3250                 :                :             ScanKey     entry;
                               3251                 :                :             Oid         opfamily,
                               3252                 :                :                         opcintype,
                               3253                 :                :                         opno,
                               3254                 :                :                         opcode;
                               3255                 :                :             StrategyNumber eq_strategy;
                               3256                 :                : 
                               3257                 :             11 :             entry = &chgcxt->cc_ident_key[i];
                               3258                 :                : 
                               3259                 :             11 :             opfamily = chgcxt->cc_ident_index->rd_opfamily[i];
                               3260                 :             11 :             opcintype = chgcxt->cc_ident_index->rd_opcintype[i];
  132                          3261                 :             11 :             eq_strategy = IndexAmTranslateCompareType(COMPARE_EQ,
                               3262                 :             11 :                                                       chgcxt->cc_ident_index->rd_rel->relam,
                               3263                 :                :                                                       opfamily, false);
                               3264         [ -  + ]:             11 :             if (eq_strategy == InvalidStrategy)
  132 alvherre@kurilemu.de     3265         [ #  # ]:UBC           0 :                 elog(ERROR, "could not find equality strategy for index operator family %u for type %u",
                               3266                 :                :                      opfamily, opcintype);
  167 alvherre@kurilemu.de     3267                 :CBC          11 :             opno = get_opfamily_member(opfamily, opcintype, opcintype,
                               3268                 :                :                                        eq_strategy);
                               3269         [ -  + ]:             11 :             if (!OidIsValid(opno))
  132 alvherre@kurilemu.de     3270         [ #  # ]:UBC           0 :                 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
                               3271                 :                :                      eq_strategy, opcintype, opcintype, opfamily);
  167 alvherre@kurilemu.de     3272                 :CBC          11 :             opcode = get_opcode(opno);
                               3273         [ -  + ]:             11 :             if (!OidIsValid(opcode))
  132 alvherre@kurilemu.de     3274         [ #  # ]:UBC           0 :                 elog(ERROR, "missing oprcode for operator %u", opno);
                               3275                 :                : 
                               3276                 :                :             /* Initialize everything but argument. */
  167 alvherre@kurilemu.de     3277                 :CBC          11 :             ScanKeyInit(entry,
                               3278                 :             11 :                         i + 1,
                               3279                 :                :                         eq_strategy, opcode,
                               3280                 :                :                         (Datum) 0);
                               3281                 :             11 :             entry->sk_collation = chgcxt->cc_ident_index->rd_indcollation[i];
                               3282                 :                :         }
                               3283                 :                :     }
                               3284                 :                : 
                               3285                 :                :     /* Determine the last column we must deform to read the identity */
  132                          3286                 :              9 :     chgcxt->cc_last_key_attno = InvalidAttrNumber;
                               3287         [ +  + ]:             20 :     for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
                               3288                 :                :     {
                               3289                 :             11 :         AttrNumber  attno = chgcxt->cc_ident_index->rd_index->indkey.values[i];
                               3290                 :                : 
                               3291         [ -  + ]:             11 :         Assert(attno > 0);
                               3292                 :             11 :         chgcxt->cc_last_key_attno = Max(chgcxt->cc_last_key_attno, attno);
                               3293                 :                :     }
                               3294                 :                : 
  167                          3295                 :              9 :     chgcxt->cc_file_seq = WORKER_FILE_SNAPSHOT + 1;
                               3296                 :              9 : }
                               3297                 :                : 
                               3298                 :                : /*
                               3299                 :                :  * Free up resources taken by a ChangeContext.
                               3300                 :                :  */
                               3301                 :                : static void
                               3302                 :              9 : release_change_context(ChangeContext *chgcxt)
                               3303                 :                : {
                               3304                 :              9 :     ExecCloseIndices(chgcxt->cc_rri);
                               3305                 :              9 :     FreeExecutorState(chgcxt->cc_estate);
                               3306                 :                :     /* XXX are these pfrees necessary? */
                               3307                 :              9 :     pfree(chgcxt->cc_rri);
                               3308                 :              9 :     pfree(chgcxt->cc_ident_key);
                               3309                 :              9 : }
                               3310                 :                : 
                               3311                 :                : /*
                               3312                 :                :  * The final steps of rebuild_relation() for concurrent processing.
                               3313                 :                :  *
                               3314                 :                :  * On entry, NewHeap is locked in AccessExclusiveLock mode. OldHeap and its
                               3315                 :                :  * clustering index (if one is passed) are still locked in a mode that allows
                               3316                 :                :  * concurrent data changes. On exit, both tables and their indexes are closed,
                               3317                 :                :  * but locked in AccessExclusiveLock mode.
                               3318                 :                :  */
                               3319                 :                : static void
                               3320                 :              9 : rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
                               3321                 :                :                                    Oid identIdx, TransactionId frozenXid,
                               3322                 :                :                                    MultiXactId cutoffMulti)
                               3323                 :                : {
                               3324                 :                :     List       *ind_oids_new;
                               3325                 :              9 :     Oid         old_table_oid = RelationGetRelid(OldHeap);
                               3326                 :              9 :     Oid         new_table_oid = RelationGetRelid(NewHeap);
                               3327                 :              9 :     List       *ind_oids_old = RelationGetIndexList(OldHeap);
                               3328                 :                :     ListCell   *lc,
                               3329                 :                :                *lc2;
                               3330                 :                :     char        relpersistence;
                               3331                 :                :     bool        is_system_catalog;
                               3332                 :                :     Oid         ident_idx_new;
                               3333                 :                :     XLogRecPtr  end_of_wal;
                               3334                 :                :     List       *indexrels;
                               3335                 :                :     ChangeContext chgcxt;
                               3336                 :                : 
                               3337         [ -  + ]:              9 :     Assert(CheckRelationLockedByMe(OldHeap, ShareUpdateExclusiveLock, false));
                               3338         [ -  + ]:              9 :     Assert(CheckRelationLockedByMe(NewHeap, AccessExclusiveLock, false));
                               3339                 :                : 
                               3340                 :                :     /*
                               3341                 :                :      * Unlike the exclusive case, we build new indexes for the new relation
                               3342                 :                :      * rather than swapping the storage and reindexing the old relation. The
                               3343                 :                :      * point is that the index build can take some time, so we do it before we
                               3344                 :                :      * get AccessExclusiveLock on the old heap and therefore we cannot swap
                               3345                 :                :      * the heap storage yet.
                               3346                 :                :      *
                               3347                 :                :      * index_create() will lock the new indexes using AccessExclusiveLock - no
                               3348                 :                :      * need to change that. At the same time, we use ShareUpdateExclusiveLock
                               3349                 :                :      * to lock the existing indexes - that should be enough to prevent others
                               3350                 :                :      * from changing them while we're repacking the relation. The lock on
                               3351                 :                :      * table should prevent others from changing the index column list, but
                               3352                 :                :      * might not be enough for commands like ALTER INDEX ... SET ... (Those
                               3353                 :                :      * are not necessarily dangerous, but can make user confused if the
                               3354                 :                :      * changes they do get lost due to REPACK.)
                               3355                 :                :      */
                               3356                 :              9 :     ind_oids_new = build_new_indexes(NewHeap, OldHeap, ind_oids_old);
                               3357                 :                : 
                               3358                 :                :     /*
                               3359                 :                :      * The identity index in the new relation appears in the same relative
                               3360                 :                :      * position as the corresponding index in the old relation.  Find it.
                               3361                 :                :      */
                               3362                 :              9 :     ident_idx_new = InvalidOid;
                               3363   [ +  -  +  -  :             18 :     foreach_oid(ind_old, ind_oids_old)
                                              +  + ]
                               3364                 :                :     {
                               3365         [ +  - ]:              9 :         if (identIdx == ind_old)
                               3366                 :                :         {
                               3367                 :              9 :             int         pos = foreach_current_index(ind_old);
                               3368                 :                : 
  139                          3369         [ -  + ]:              9 :             if (list_length(ind_oids_new) <= pos)
  167 alvherre@kurilemu.de     3370         [ #  # ]:UBC           0 :                 elog(ERROR, "list of new indexes too short");
  167 alvherre@kurilemu.de     3371                 :CBC           9 :             ident_idx_new = list_nth_oid(ind_oids_new, pos);
                               3372                 :              9 :             break;
                               3373                 :                :         }
                               3374                 :                :     }
                               3375         [ -  + ]:              9 :     if (!OidIsValid(ident_idx_new))
  167 alvherre@kurilemu.de     3376         [ #  # ]:UBC           0 :         elog(ERROR, "could not find index matching \"%s\" at the new relation",
                               3377                 :                :              get_rel_name(identIdx));
                               3378                 :                : 
                               3379                 :                :     /* Gather information to apply concurrent changes. */
  167 alvherre@kurilemu.de     3380                 :CBC           9 :     initialize_change_context(&chgcxt, NewHeap, ident_idx_new);
                               3381                 :                : 
                               3382                 :                :     /*
                               3383                 :                :      * During testing, wait for another backend to perform concurrent data
                               3384                 :                :      * changes which we will process below.
                               3385                 :                :      */
                               3386                 :              9 :     INJECTION_POINT("repack-concurrently-before-lock", NULL);
                               3387                 :                : 
                               3388                 :                :     /*
                               3389                 :                :      * Flush all WAL records inserted so far (possibly except for the last
                               3390                 :                :      * incomplete page; see GetInsertRecPtr), to minimize the amount of data
                               3391                 :                :      * we need to flush while holding exclusive lock on the source table.
                               3392                 :                :      */
                               3393                 :              9 :     XLogFlush(GetXLogInsertEndRecPtr());
                               3394                 :              9 :     end_of_wal = GetFlushRecPtr(NULL);
                               3395                 :                : 
                               3396                 :                :     /*
                               3397                 :                :      * Apply concurrent changes first time, to minimize the time we need to
                               3398                 :                :      * hold AccessExclusiveLock. (Quite some amount of WAL could have been
                               3399                 :                :      * written during the data copying and index creation.)
                               3400                 :                :      */
                               3401                 :              9 :     process_concurrent_changes(end_of_wal, &chgcxt, false);
                               3402                 :                : 
                               3403                 :                :     /*
                               3404                 :                :      * Acquire AccessExclusiveLock on the table, its TOAST relation (if there
                               3405                 :                :      * is one), all its indexes, so that we can swap the files.
                               3406                 :                :      */
                               3407                 :              9 :     LockRelationOid(old_table_oid, AccessExclusiveLock);
                               3408                 :                : 
                               3409                 :                :     /*
                               3410                 :                :      * Lock all indexes now, not only the clustering one: all indexes need to
                               3411                 :                :      * have their files swapped. While doing that, store their relation
                               3412                 :                :      * references in a zero-terminated array, to handle predicate locks below.
                               3413                 :                :      */
                               3414                 :              9 :     indexrels = NIL;
                               3415   [ +  -  +  +  :             28 :     foreach_oid(ind_oid, ind_oids_old)
                                              +  + ]
                               3416                 :                :     {
                               3417                 :                :         Relation    index;
                               3418                 :                : 
                               3419                 :             10 :         index = index_open(ind_oid, AccessExclusiveLock);
                               3420                 :                : 
                               3421                 :                :         /*
                               3422                 :                :          * Some things about the index may have changed before we locked the
                               3423                 :                :          * index, such as ALTER INDEX RENAME.  We don't need to do anything
                               3424                 :                :          * here to absorb those changes in the new index.
                               3425                 :                :          */
                               3426                 :             10 :         indexrels = lappend(indexrels, index);
                               3427                 :                :     }
                               3428                 :                : 
                               3429                 :                :     /*
                               3430                 :                :      * Lock the OldHeap's TOAST relation exclusively - again, the lock is
                               3431                 :                :      * needed to swap the files.
                               3432                 :                :      */
                               3433         [ +  + ]:              9 :     if (OidIsValid(OldHeap->rd_rel->reltoastrelid))
                               3434                 :              5 :         LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
                               3435                 :                : 
                               3436                 :                :     /*
                               3437                 :                :      * Tuples and pages of the old heap will be gone, but the heap will stay.
                               3438                 :                :      */
                               3439                 :              9 :     TransferPredicateLocksToHeapRelation(OldHeap);
                               3440   [ +  -  +  +  :             28 :     foreach_ptr(RelationData, index, indexrels)
                                              +  + ]
                               3441                 :                :     {
                               3442                 :             10 :         TransferPredicateLocksToHeapRelation(index);
                               3443                 :             10 :         index_close(index, NoLock);
                               3444                 :                :     }
                               3445                 :              9 :     list_free(indexrels);
                               3446                 :                : 
                               3447                 :                :     /*
                               3448                 :                :      * Flush WAL again, to make sure that all changes committed while we were
                               3449                 :                :      * waiting for the exclusive lock are available for decoding.
                               3450                 :                :      */
                               3451                 :              9 :     XLogFlush(GetXLogInsertEndRecPtr());
                               3452                 :              9 :     end_of_wal = GetFlushRecPtr(NULL);
                               3453                 :                : 
                               3454                 :                :     /*
                               3455                 :                :      * Apply the concurrent changes again. Indicate that the decoding worker
                               3456                 :                :      * won't be needed anymore.
                               3457                 :                :      */
                               3458                 :              9 :     process_concurrent_changes(end_of_wal, &chgcxt, true);
                               3459                 :                : 
                               3460                 :                :     /* Remember info about rel before closing OldHeap */
                               3461                 :              9 :     relpersistence = OldHeap->rd_rel->relpersistence;
                               3462                 :              9 :     is_system_catalog = IsSystemRelation(OldHeap);
                               3463                 :                : 
                               3464                 :              9 :     pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                               3465                 :                :                                  PROGRESS_REPACK_PHASE_SWAP_REL_FILES);
                               3466                 :                : 
                               3467                 :                :     /*
                               3468                 :                :      * Even ShareUpdateExclusiveLock should have prevented others from
                               3469                 :                :      * creating / dropping indexes (even using the CONCURRENTLY option), so we
                               3470                 :                :      * do not need to check whether the lists match.
                               3471                 :                :      */
                               3472   [ +  -  +  +  :             19 :     forboth(lc, ind_oids_old, lc2, ind_oids_new)
                                     +  -  +  +  +  
                                        +  +  -  +  
                                                 + ]
                               3473                 :                :     {
                               3474                 :             10 :         Oid         ind_old = lfirst_oid(lc);
                               3475                 :             10 :         Oid         ind_new = lfirst_oid(lc2);
                               3476                 :             10 :         Oid         mapped_tables[4] = {0};
                               3477                 :                : 
                               3478                 :             10 :         swap_relation_files(ind_old, ind_new,
                               3479                 :                :                             (old_table_oid == RelationRelationId),
                               3480                 :                :                             false,  /* swap_toast_by_content */
                               3481                 :                :                             true,
                               3482                 :                :                             InvalidTransactionId,
                               3483                 :                :                             InvalidMultiXactId,
                               3484                 :                :                             mapped_tables);
                               3485                 :                : 
                               3486                 :                : #ifdef USE_ASSERT_CHECKING
                               3487                 :                : 
                               3488                 :                :         /*
                               3489                 :                :          * Concurrent processing is not supported for system relations, so
                               3490                 :                :          * there should be no mapped tables.
                               3491                 :                :          */
                               3492         [ +  + ]:             50 :         for (int i = 0; i < 4; i++)
                               3493         [ -  + ]:             40 :             Assert(!OidIsValid(mapped_tables[i]));
                               3494                 :                : #endif
                               3495                 :                :     }
                               3496                 :                : 
                               3497                 :                :     /* The new indexes must be visible for deletion. */
                               3498                 :              9 :     CommandCounterIncrement();
                               3499                 :                : 
                               3500                 :                :     /* Close the old heap but keep lock until transaction commit. */
                               3501                 :              9 :     table_close(OldHeap, NoLock);
                               3502                 :                :     /* Close the new heap. (We didn't have to open its indexes). */
                               3503                 :              9 :     table_close(NewHeap, NoLock);
                               3504                 :                : 
                               3505                 :                :     /* Cleanup what we don't need anymore. (And close the identity index.) */
                               3506                 :              9 :     release_change_context(&chgcxt);
                               3507                 :                : 
                               3508                 :                :     /*
                               3509                 :                :      * Swap the relations and their TOAST relations and TOAST indexes. This
                               3510                 :                :      * also drops the new relation and its indexes.
                               3511                 :                :      *
                               3512                 :                :      * (System catalogs are currently not supported.)
                               3513                 :                :      */
                               3514         [ -  + ]:              9 :     Assert(!is_system_catalog);
                               3515                 :              9 :     finish_heap_swap(old_table_oid, new_table_oid,
                               3516                 :                :                      is_system_catalog,
                               3517                 :                :                      false,     /* swap_toast_by_content */
                               3518                 :                :                      false,
                               3519                 :                :                      true,
                               3520                 :                :                      false,     /* reindex */
                               3521                 :                :                      frozenXid, cutoffMulti,
                               3522                 :                :                      relpersistence);
                               3523                 :              9 : }
                               3524                 :                : 
                               3525                 :                : /*
                               3526                 :                :  * Build indexes on NewHeap according to those on OldHeap.
                               3527                 :                :  *
                               3528                 :                :  * OldIndexes is the list of index OIDs on OldHeap. The contained indexes end
                               3529                 :                :  * up locked using ShareUpdateExclusiveLock.
                               3530                 :                :  *
                               3531                 :                :  * A list of OIDs of the corresponding indexes created on NewHeap is
                               3532                 :                :  * returned. The order of items does match, so we can use these arrays to swap
                               3533                 :                :  * index storage.
                               3534                 :                :  */
                               3535                 :                : static List *
                               3536                 :              9 : build_new_indexes(Relation NewHeap, Relation OldHeap, List *OldIndexes)
                               3537                 :                : {
                               3538                 :              9 :     List       *result = NIL;
                               3539                 :                : 
                               3540                 :              9 :     pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
                               3541                 :                :                                  PROGRESS_REPACK_PHASE_REBUILD_INDEX);
                               3542                 :                : 
                               3543   [ +  -  +  +  :             28 :     foreach_oid(oldindex, OldIndexes)
                                              +  + ]
                               3544                 :                :     {
                               3545                 :                :         Oid         newindex;
                               3546                 :                :         char       *newName;
                               3547                 :                :         Relation    ind;
                               3548                 :                : 
                               3549                 :             10 :         ind = index_open(oldindex, ShareUpdateExclusiveLock);
                               3550                 :                : 
                               3551                 :             10 :         newName = ChooseRelationName(get_rel_name(oldindex),
                               3552                 :                :                                      NULL,
                               3553                 :                :                                      "repacknew",
                               3554                 :             10 :                                      get_rel_namespace(ind->rd_index->indrelid),
                               3555                 :                :                                      false);
                               3556                 :             10 :         newindex = index_create_copy(NewHeap, INDEX_CREATE_SUPPRESS_PROGRESS,
                               3557                 :             10 :                                      oldindex, ind->rd_rel->reltablespace,
                               3558                 :                :                                      newName);
                               3559                 :             10 :         copy_index_constraints(ind, newindex, RelationGetRelid(NewHeap));
                               3560                 :             10 :         result = lappend_oid(result, newindex);
                               3561                 :                : 
                               3562                 :             10 :         index_close(ind, NoLock);
                               3563                 :                : 
    4 fujii@postgresql.org     3564                 :             10 :         pgstat_progress_incr_param(PROGRESS_REPACK_INDEX_REBUILD_COUNT, 1);
                               3565                 :                :     }
                               3566                 :                : 
  167 alvherre@kurilemu.de     3567                 :              9 :     return result;
                               3568                 :                : }
                               3569                 :                : 
                               3570                 :                : /*
                               3571                 :                :  * Create a transient copy of a constraint -- supported by a transient
                               3572                 :                :  * copy of the index that supports the original constraint.
                               3573                 :                :  *
                               3574                 :                :  * When repacking a table that contains exclusion constraints, the executor
                               3575                 :                :  * relies on these constraints being properly catalogued.  These copies are
                               3576                 :                :  * to support that.
                               3577                 :                :  *
                               3578                 :                :  * We don't need the constraints for anything else (the original constraints
                               3579                 :                :  * will be there once repack completes), so we add pg_depend entries so that
                               3580                 :                :  * they are dropped when the transient table is dropped.
                               3581                 :                :  */
                               3582                 :                : static void
                               3583                 :             10 : copy_index_constraints(Relation old_index, Oid new_index_id, Oid new_heap_id)
                               3584                 :                : {
                               3585                 :                :     ScanKeyData skey;
                               3586                 :                :     Relation    rel;
                               3587                 :                :     TupleDesc   desc;
                               3588                 :                :     SysScanDesc scan;
                               3589                 :                :     HeapTuple   tup;
                               3590                 :                :     ObjectAddress objrel;
                               3591                 :                : 
                               3592                 :             10 :     rel = table_open(ConstraintRelationId, RowExclusiveLock);
                               3593                 :             10 :     ObjectAddressSet(objrel, RelationRelationId, new_heap_id);
                               3594                 :                : 
                               3595                 :                :     /*
                               3596                 :                :      * Retrieve the constraints supported by the old index and create an
                               3597                 :                :      * identical one that points to the new index.
                               3598                 :                :      */
                               3599                 :             10 :     ScanKeyInit(&skey,
                               3600                 :                :                 Anum_pg_constraint_conrelid,
                               3601                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               3602                 :             10 :                 ObjectIdGetDatum(old_index->rd_index->indrelid));
                               3603                 :             10 :     scan = systable_beginscan(rel, ConstraintRelidTypidNameIndexId, true,
                               3604                 :                :                               NULL, 1, &skey);
                               3605                 :             10 :     desc = RelationGetDescr(rel);
                               3606         [ +  + ]:             32 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
                               3607                 :                :     {
                               3608                 :             22 :         Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(tup);
                               3609                 :                :         Oid         oid;
                               3610                 :             22 :         Datum       values[Natts_pg_constraint] = {0};
                               3611                 :             22 :         bool        nulls[Natts_pg_constraint] = {0};
                               3612                 :             22 :         bool        replaces[Natts_pg_constraint] = {0};
                               3613                 :                :         HeapTuple   new_tup;
                               3614                 :                :         ObjectAddress objcon;
                               3615                 :                : 
                               3616         [ +  + ]:             22 :         if (conform->conindid != RelationGetRelid(old_index))
                               3617                 :             13 :             continue;
                               3618                 :                : 
                               3619                 :              9 :         oid = GetNewOidWithIndex(rel, ConstraintOidIndexId,
                               3620                 :                :                                  Anum_pg_constraint_oid);
                               3621                 :              9 :         values[Anum_pg_constraint_oid - 1] = ObjectIdGetDatum(oid);
                               3622                 :              9 :         replaces[Anum_pg_constraint_oid - 1] = true;
                               3623                 :              9 :         values[Anum_pg_constraint_conrelid - 1] = ObjectIdGetDatum(new_heap_id);
                               3624                 :              9 :         replaces[Anum_pg_constraint_conrelid - 1] = true;
                               3625                 :              9 :         values[Anum_pg_constraint_conindid - 1] = ObjectIdGetDatum(new_index_id);
                               3626                 :              9 :         replaces[Anum_pg_constraint_conindid - 1] = true;
                               3627                 :                : 
                               3628                 :              9 :         new_tup = heap_modify_tuple(tup, desc, values, nulls, replaces);
                               3629                 :                : 
                               3630                 :                :         /* Insert it into the catalog. */
                               3631                 :              9 :         CatalogTupleInsert(rel, new_tup);
                               3632                 :                : 
                               3633                 :                :         /* Create a dependency so it's removed when we drop the new heap. */
                               3634                 :              9 :         ObjectAddressSet(objcon, ConstraintRelationId, oid);
                               3635                 :              9 :         recordDependencyOn(&objcon, &objrel, DEPENDENCY_AUTO);
                               3636                 :                :     }
                               3637                 :             10 :     systable_endscan(scan);
                               3638                 :                : 
                               3639                 :             10 :     table_close(rel, RowExclusiveLock);
                               3640                 :                : 
                               3641                 :             10 :     CommandCounterIncrement();
                               3642                 :             10 : }
                               3643                 :                : 
                               3644                 :                : /*
                               3645                 :                :  * Create a transient copy of attribute defaults.
                               3646                 :                :  *
                               3647                 :                :  * When repacking a table that has stored generated columns, the executor
                               3648                 :                :  * relies on these entries to generate the values for them during apply of
                               3649                 :                :  * concurrent operations.  These copies are there to support that.
                               3650                 :                :  *
                               3651                 :                :  * We don't need the defaults for anything else, so we add pg_depend entries
                               3652                 :                :  * so that they are dropped when the transient table is dropped.
                               3653                 :                :  */
                               3654                 :                : static void
   79                          3655                 :              9 : copy_attribute_defaults(Oid old_heap_oid, Oid new_heap_oid)
                               3656                 :                : {
                               3657                 :                :     ScanKeyData skey;
                               3658                 :                :     Relation    rel;
                               3659                 :                :     Relation    att_rel;
                               3660                 :                :     SysScanDesc scan;
                               3661                 :                :     HeapTuple   def_tup;
                               3662                 :                :     ObjectAddress objrel;
                               3663                 :                : 
                               3664                 :              9 :     rel = table_open(AttrDefaultRelationId, RowExclusiveLock);
                               3665                 :              9 :     att_rel = table_open(AttributeRelationId, RowExclusiveLock);
                               3666                 :                : 
                               3667                 :              9 :     ObjectAddressSet(objrel, RelationRelationId, new_heap_oid);
                               3668                 :                : 
                               3669                 :              9 :     ScanKeyInit(&skey,
                               3670                 :                :                 Anum_pg_attrdef_adrelid,
                               3671                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               3672                 :                :                 ObjectIdGetDatum(old_heap_oid));
                               3673                 :              9 :     scan = systable_beginscan(rel, AttrDefaultIndexId, true,
                               3674                 :                :                               NULL, 1, &skey);
                               3675         [ +  + ]:             11 :     while (HeapTupleIsValid(def_tup = systable_getnext(scan)))
                               3676                 :                :     {
                               3677                 :                :         Form_pg_attrdef adform;
                               3678                 :                :         Oid         oid;
                               3679                 :                :         Datum       def_values[Natts_pg_attrdef];
                               3680                 :                :         bool        def_nulls[Natts_pg_attrdef];
                               3681                 :              2 :         bool        def_replaces[Natts_pg_attrdef] = {0};
                               3682                 :                :         Datum       att_values[Natts_pg_attribute];
                               3683                 :                :         bool        att_nulls[Natts_pg_attribute];
                               3684                 :              2 :         bool        att_replaces[Natts_pg_attribute] = {0};
                               3685                 :                :         HeapTuple   new_def_tup,
                               3686                 :                :                     att_tup,
                               3687                 :                :                     new_att_tup;
                               3688                 :                :         ObjectAddress objad;
                               3689                 :                : 
                               3690                 :              2 :         adform = (Form_pg_attrdef) GETSTRUCT(def_tup);
                               3691         [ -  + ]:              2 :         Assert(adform->adrelid == old_heap_oid);
                               3692                 :                : 
                               3693                 :                :         /*
                               3694                 :                :          * Insert a new tuple that's identical to the existing one, other than
                               3695                 :                :          * its OID and the relation it refers to.
                               3696                 :                :          */
                               3697                 :              2 :         oid = GetNewOidWithIndex(rel, AttrDefaultOidIndexId,
                               3698                 :                :                                  Anum_pg_attrdef_oid);
                               3699                 :              2 :         def_values[Anum_pg_attrdef_oid - 1] = ObjectIdGetDatum(oid);
                               3700                 :              2 :         def_nulls[Anum_pg_attrdef_oid - 1] = false;
                               3701                 :              2 :         def_replaces[Anum_pg_attrdef_oid - 1] = true;
                               3702                 :              2 :         def_values[Anum_pg_attrdef_adrelid - 1] = ObjectIdGetDatum(new_heap_oid);
                               3703                 :              2 :         def_nulls[Anum_pg_attrdef_adrelid - 1] = false;
                               3704                 :              2 :         def_replaces[Anum_pg_attrdef_adrelid - 1] = true;
                               3705                 :              2 :         new_def_tup = heap_modify_tuple(def_tup, RelationGetDescr(rel),
                               3706                 :                :                                         def_values, def_nulls, def_replaces);
                               3707                 :              2 :         CatalogTupleInsert(rel, new_def_tup);
                               3708                 :                : 
                               3709                 :                :         /* Set atthasdef for this attribute in the transient table */
                               3710                 :              2 :         att_tup = SearchSysCache2(ATTNUM,
                               3711                 :                :                                   ObjectIdGetDatum(new_heap_oid),
                               3712                 :              2 :                                   ObjectIdGetDatum(adform->adnum));
                               3713         [ -  + ]:              2 :         if (!HeapTupleIsValid(att_tup))
   79 alvherre@kurilemu.de     3714         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for attribute %d of relation %u",
                               3715                 :                :                  adform->adnum, new_heap_oid);
   79 alvherre@kurilemu.de     3716                 :CBC           2 :         att_values[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(true);
                               3717                 :              2 :         att_nulls[Anum_pg_attribute_atthasdef - 1] = false;
                               3718                 :              2 :         att_replaces[Anum_pg_attribute_atthasdef - 1] = true;
                               3719                 :              2 :         new_att_tup = heap_modify_tuple(att_tup, RelationGetDescr(att_rel),
                               3720                 :                :                                         att_values, att_nulls, att_replaces);
                               3721                 :              2 :         CatalogTupleUpdate(att_rel, &new_att_tup->t_self, new_att_tup);
                               3722                 :              2 :         ReleaseSysCache(att_tup);
                               3723                 :                : 
                               3724                 :                :         /* Add a pg_depend record so it's removed with the transient table */
                               3725                 :              2 :         ObjectAddressSet(objad, AttrDefaultRelationId, oid);
                               3726                 :              2 :         recordDependencyOn(&objad, &objrel, DEPENDENCY_AUTO);
                               3727                 :                :     }
                               3728                 :              9 :     systable_endscan(scan);
                               3729                 :                : 
                               3730                 :              9 :     table_close(rel, RowExclusiveLock);
                               3731                 :              9 :     table_close(att_rel, RowExclusiveLock);
                               3732                 :                : 
                               3733                 :              9 :     CommandCounterIncrement();
                               3734                 :              9 : }
                               3735                 :                : 
                               3736                 :                : /*
                               3737                 :                :  * Try to start a background worker to perform logical decoding of data
                               3738                 :                :  * changes applied to relation while REPACK CONCURRENTLY is copying its
                               3739                 :                :  * contents to a new table.
                               3740                 :                :  */
                               3741                 :                : static void
  167                          3742                 :              9 : start_repack_decoding_worker(Oid relid)
                               3743                 :                : {
                               3744                 :                :     Size        size;
                               3745                 :                :     DecodingWorkerShared *shared;
                               3746                 :                :     shm_mq     *mq;
                               3747                 :                :     BackgroundWorker bgw;
                               3748                 :                : 
  117                          3749                 :              9 :     decoding_worker = palloc0_object(DecodingWorker);
                               3750                 :                : 
                               3751                 :                :     /* Setup shared memory. */
  167                          3752                 :              9 :     size = BUFFERALIGN(offsetof(DecodingWorkerShared, error_queue)) +
                               3753                 :                :         BUFFERALIGN(REPACK_ERROR_QUEUE_SIZE);
  117                          3754                 :              9 :     decoding_worker->seg = dsm_create(size, 0);
                               3755                 :                : 
                               3756                 :              9 :     shared = (DecodingWorkerShared *) dsm_segment_address(decoding_worker->seg);
  157                          3757                 :              9 :     shared->initialized = false;
  167                          3758                 :              9 :     shared->lsn_upto = InvalidXLogRecPtr;
                               3759                 :              9 :     shared->done = false;
  117                          3760                 :              9 :     SharedFileSetInit(&shared->sfs, decoding_worker->seg);
  167                          3761                 :              9 :     shared->last_exported = -1;
                               3762                 :              9 :     SpinLockInit(&shared->mutex);
                               3763                 :              9 :     shared->dbid = MyDatabaseId;
                               3764                 :                : 
                               3765                 :                :     /*
                               3766                 :                :      * This is the UserId set in cluster_rel(). Security context shouldn't be
                               3767                 :                :      * needed for decoding worker.
                               3768                 :                :      */
                               3769                 :              9 :     shared->roleid = GetUserId();
                               3770                 :              9 :     shared->relid = relid;
                               3771                 :              9 :     ConditionVariableInit(&shared->cv);
                               3772                 :              9 :     shared->backend_pid = MyProcPid;
                               3773                 :              9 :     shared->backend_proc_number = MyProcNumber;
                               3774                 :                : 
                               3775                 :                :     /* Transmit our timeouts to the worker too */
    3                          3776                 :              9 :     shared->lock_timeout = LockTimeout;
                               3777                 :              9 :     shared->transaction_timeout = TransactionTimeout;
                               3778                 :                : 
  167                          3779                 :              9 :     mq = shm_mq_create((char *) BUFFERALIGN(shared->error_queue),
                               3780                 :                :                        REPACK_ERROR_QUEUE_SIZE);
                               3781                 :              9 :     shm_mq_set_receiver(mq, MyProc);
                               3782                 :                : 
  117                          3783                 :              9 :     decoding_worker->error_mqh = shm_mq_attach(mq, decoding_worker->seg, NULL);
                               3784                 :                : 
  167                          3785                 :              9 :     memset(&bgw, 0, sizeof(bgw));
                               3786                 :              9 :     snprintf(bgw.bgw_name, BGW_MAXLEN,
                               3787                 :                :              "REPACK decoding worker for relation \"%s\"",
                               3788                 :                :              get_rel_name(relid));
                               3789                 :              9 :     snprintf(bgw.bgw_type, BGW_MAXLEN, "REPACK decoding worker");
                               3790                 :              9 :     bgw.bgw_flags = BGWORKER_SHMEM_ACCESS |
                               3791                 :                :         BGWORKER_BACKEND_DATABASE_CONNECTION;
                               3792                 :              9 :     bgw.bgw_start_time = BgWorkerStart_RecoveryFinished;
                               3793                 :              9 :     bgw.bgw_restart_time = BGW_NEVER_RESTART;
                               3794                 :              9 :     snprintf(bgw.bgw_library_name, MAXPGPATH, "postgres");
                               3795                 :              9 :     snprintf(bgw.bgw_function_name, BGW_MAXLEN, "RepackWorkerMain");
  117                          3796                 :              9 :     bgw.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(decoding_worker->seg));
  167                          3797                 :              9 :     bgw.bgw_notify_pid = MyProcPid;
                               3798                 :                : 
                               3799         [ -  + ]:              9 :     if (!RegisterDynamicBackgroundWorker(&bgw, &decoding_worker->handle))
  167 alvherre@kurilemu.de     3800         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3801                 :                :                 errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
                               3802                 :                :                 errmsg("out of background worker slots"),
                               3803                 :                :                 errhint("You might need to increase \"%s\".", "max_worker_processes"));
                               3804                 :                : 
                               3805                 :                :     /*
                               3806                 :                :      * Now that the worker is registered, connect the error message queue to
                               3807                 :                :      * it.
                               3808                 :                :      */
    3 alvherre@kurilemu.de     3809                 :CBC           9 :     shm_mq_set_handle(decoding_worker->error_mqh, decoding_worker->handle);
                               3810                 :                : 
                               3811                 :                :     /*
                               3812                 :                :      * Make sure the worker has started before we wait for it to initialize
                               3813                 :                :      * decoding below, so that the failure-to-start case does not hang
                               3814                 :                :      * forever.
                               3815                 :                :      */
                               3816                 :              9 :     wait_for_repack_decoding_worker();
                               3817                 :                : 
                               3818                 :                :     /*
                               3819                 :                :      * The decoding setup must be done before the caller can have XID assigned
                               3820                 :                :      * for any reason, otherwise the worker might end up in a deadlock,
                               3821                 :                :      * waiting for the caller's transaction to end. Therefore wait here until
                               3822                 :                :      * the worker indicates that it has the logical decoding initialized.
                               3823                 :                :      */
  167                          3824                 :              9 :     ConditionVariablePrepareToSleep(&shared->cv);
                               3825                 :                :     for (;;)
                               3826                 :             19 :     {
                               3827                 :                :         bool        initialized;
                               3828                 :                : 
                               3829                 :             28 :         SpinLockAcquire(&shared->mutex);
                               3830                 :             28 :         initialized = shared->initialized;
                               3831                 :             28 :         SpinLockRelease(&shared->mutex);
                               3832                 :                : 
                               3833         [ +  + ]:             28 :         if (initialized)
                               3834                 :              9 :             break;
                               3835                 :                : 
                               3836                 :             19 :         ConditionVariableSleep(&shared->cv, WAIT_EVENT_REPACK_WORKER_EXPORT);
                               3837                 :                :     }
                               3838                 :              9 :     ConditionVariableCancelSleep();
                               3839                 :              9 : }
                               3840                 :                : 
                               3841                 :                : /*
                               3842                 :                :  * Wait for the decoding worker to start up, and throw an error if it fails
                               3843                 :                :  * to do so.
                               3844                 :                :  *
                               3845                 :                :  * This is similar to WaitForParallelWorkersToAttach(). The only reliable way
                               3846                 :                :  * to tell a worker that failed to start (fork failure, or an exit before it
                               3847                 :                :  * attached) from one that is merely slow is to check whether it became the
                               3848                 :                :  * sender on the error message queue. If it stopped without attaching, nothing
                               3849                 :                :  * was queued and we report the generic failure ourselves. If it attached, any
                               3850                 :                :  * error it reported is in the queue and is thrown when we process pending
                               3851                 :                :  * messages, either here or later while we wait for it to initialize decoding.
                               3852                 :                :  */
                               3853                 :                : static void
    3                          3854                 :              9 : wait_for_repack_decoding_worker(void)
                               3855                 :                : {
                               3856                 :                :     for (;;)
                               3857                 :             18 :     {
                               3858                 :                :         BgwHandleStatus status;
                               3859                 :                :         shm_mq     *mq;
                               3860                 :                :         int         rc;
                               3861                 :                :         pid_t       pid;
                               3862                 :                : 
                               3863                 :                :         /*
                               3864                 :                :          * This will process any repack messages that are pending and it may
                               3865                 :                :          * also throw an error propagated from a worker.
                               3866                 :                :          */
                               3867         [ -  + ]:             27 :         CHECK_FOR_INTERRUPTS();
                               3868                 :                : 
                               3869                 :                :         /* If error_mqh is NULL, the worker has exited cleanly */
                               3870         [ -  + ]:             27 :         if (decoding_worker->error_mqh == NULL)
    3 alvherre@kurilemu.de     3871                 :UBC           0 :             break;
                               3872                 :                : 
    3 alvherre@kurilemu.de     3873                 :CBC          27 :         status = GetBackgroundWorkerPid(decoding_worker->handle, &pid);
                               3874         [ +  + ]:             27 :         if (status == BGWH_STARTED)
                               3875                 :                :         {
                               3876                 :                :             /* Has the worker attached to the error message queue? */
                               3877                 :             20 :             mq = shm_mq_get_queue(decoding_worker->error_mqh);
                               3878         [ +  + ]:             20 :             if (shm_mq_get_sender(mq) != NULL)
                               3879                 :              9 :                 break;
                               3880                 :                :         }
                               3881         [ -  + ]:              7 :         else if (status == BGWH_STOPPED)
                               3882                 :                :         {
                               3883                 :                :             /*
                               3884                 :                :              * If the worker stopped without attaching to the error message
                               3885                 :                :              * queue, throw an error. Otherwise, assume it attached and
                               3886                 :                :              * reported an error before exiting, so mark it attached and let
                               3887                 :                :              * the next attempt to process pending messages, here or later
                               3888                 :                :              * while the initial snapshot is set up, throw that error.
                               3889                 :                :              */
    3 alvherre@kurilemu.de     3890                 :UBC           0 :             mq = shm_mq_get_queue(decoding_worker->error_mqh);
                               3891         [ #  # ]:              0 :             if (shm_mq_get_sender(mq) == NULL)
                               3892         [ #  # ]:              0 :                 ereport(ERROR,
                               3893                 :                :                         errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               3894                 :                :                         errmsg("REPACK decoding worker failed to start"),
                               3895                 :                :                         errhint("More details may be available in the server log."));
                               3896                 :              0 :             break;
                               3897                 :                :         }
                               3898                 :                : 
                               3899                 :                :         /* Worker neither started or stopped yet, so wait. */
    3 alvherre@kurilemu.de     3900                 :CBC          18 :         rc = WaitLatch(MyLatch,
                               3901                 :                :                        WL_LATCH_SET | WL_EXIT_ON_PM_DEATH,
                               3902                 :                :                        -1, WAIT_EVENT_BGWORKER_STARTUP);
                               3903                 :                : 
                               3904         [ +  - ]:             18 :         if (rc & WL_LATCH_SET)
                               3905                 :             18 :             ResetLatch(MyLatch);
                               3906                 :                :     }
                               3907                 :              9 : }
                               3908                 :                : 
                               3909                 :                : /*
                               3910                 :                :  * Stop the decoding worker and cleanup the related resources.
                               3911                 :                :  *
                               3912                 :                :  * The worker stops on its own when it knows there is no more work to do, but
                               3913                 :                :  * we need to stop it explicitly at least on ERROR in the launching backend.
                               3914                 :                :  */
                               3915                 :                : static void
  167                          3916                 :              9 : stop_repack_decoding_worker(void)
                               3917                 :                : {
                               3918                 :                :     /* Nothing to do if no worker was set up. */
                               3919         [ -  + ]:              9 :     if (decoding_worker == NULL)
  167 alvherre@kurilemu.de     3920                 :UBC           0 :         return;
                               3921                 :                : 
                               3922                 :                :     /* Terminate the decoding worker, if one is running */
    3 alvherre@kurilemu.de     3923         [ +  - ]:CBC           9 :     if (decoding_worker->handle != NULL)
                               3924                 :              9 :         TerminateBackgroundWorker(decoding_worker->handle);
                               3925                 :                : 
                               3926                 :                :     /*
                               3927                 :                :      * The error queue should have already been nulled out during worker
                               3928                 :                :      * shutdown, but if that didn't happen, do it now.
                               3929                 :                :      */
                               3930         [ -  + ]:              9 :     if (decoding_worker->error_mqh != NULL)
                               3931                 :                :     {
    3 alvherre@kurilemu.de     3932                 :UBC           0 :         shm_mq_detach(decoding_worker->error_mqh);
                               3933                 :              0 :         decoding_worker->error_mqh = NULL;
                               3934                 :                :     }
                               3935                 :                : 
                               3936                 :                :     /*
                               3937                 :                :      * Cancel any sleep on the condition variable before detaching the shared
                               3938                 :                :      * memory segment, because the CV lives in that segment.  Otherwise later
                               3939                 :                :      * cleanup would touch freed memory.
                               3940                 :                :      */
    3 alvherre@kurilemu.de     3941                 :CBC           9 :     ConditionVariableCancelSleep();
                               3942                 :                : 
                               3943                 :                :     /*
                               3944                 :                :      * We can't finish the REPACK command until the worker has exited.  This
                               3945                 :                :      * means, in particular, that we can't respond to interrupts at this
                               3946                 :                :      * stage.
                               3947                 :                :      */
  117                          3948         [ +  - ]:              9 :     if (decoding_worker->handle != NULL)
                               3949                 :                :     {
                               3950                 :                :         BgwHandleStatus status;
                               3951                 :                : 
                               3952                 :              9 :         HOLD_INTERRUPTS();
                               3953                 :              9 :         status = WaitForBackgroundWorkerShutdown(decoding_worker->handle);
                               3954         [ -  + ]:              9 :         RESUME_INTERRUPTS();
                               3955                 :                : 
                               3956         [ -  + ]:              9 :         if (status == BGWH_POSTMASTER_DIED)
  117 alvherre@kurilemu.de     3957         [ #  # ]:UBC           0 :             ereport(FATAL,
                               3958                 :                :                     errcode(ERRCODE_ADMIN_SHUTDOWN),
                               3959                 :                :                     errmsg("postmaster exited during REPACK command"));
                               3960                 :                :     }
                               3961                 :                : 
                               3962                 :                :     /*
                               3963                 :                :      * Detach from the shared memory segment only now that the worker is gone.
                               3964                 :                :      * The worker attaches to the shared file set after it maps the segment,
                               3965                 :                :      * so detaching any earlier can destroy the file set under a worker that
                               3966                 :                :      * is still starting up.
                               3967                 :                :      */
  117 alvherre@kurilemu.de     3968         [ +  - ]:CBC           9 :     if (decoding_worker->seg != NULL)
                               3969                 :                :     {
                               3970                 :              9 :         dsm_detach(decoding_worker->seg);
    3                          3971                 :              9 :         decoding_worker->seg = NULL;
                               3972                 :                :     }
                               3973                 :                : 
  167                          3974                 :              9 :     pfree(decoding_worker);
                               3975                 :              9 :     decoding_worker = NULL;
                               3976                 :                : }
                               3977                 :                : 
                               3978                 :                : /* stop_repack_decoding_worker, wrapped as a before_shmem_exit callback */
                               3979                 :                : static void
  124 alvherre@kurilemu.de     3980                 :UBC           0 : stop_repack_decoding_worker_cb(int code, Datum arg)
                               3981                 :                : {
                               3982                 :              0 :     stop_repack_decoding_worker();
                               3983                 :              0 : }
                               3984                 :                : 
                               3985                 :                : /*
                               3986                 :                :  * Get the initial snapshot from the decoding worker.
                               3987                 :                :  */
                               3988                 :                : static Snapshot
  167 alvherre@kurilemu.de     3989                 :CBC           9 : get_initial_snapshot(DecodingWorker *worker)
                               3990                 :                : {
                               3991                 :                :     DecodingWorkerShared *shared;
                               3992                 :                :     char        fname[MAXPGPATH];
                               3993                 :                :     BufFile    *file;
                               3994                 :                :     Size        snap_size;
                               3995                 :                :     char       *snap_space;
                               3996                 :                :     Snapshot    snapshot;
                               3997                 :                : 
                               3998                 :              9 :     shared = (DecodingWorkerShared *) dsm_segment_address(worker->seg);
                               3999                 :                : 
                               4000                 :                :     /*
                               4001                 :                :      * The worker needs to initialize the logical decoding, which usually
                               4002                 :                :      * takes some time. Therefore it makes sense to prepare for the sleep
                               4003                 :                :      * first.
                               4004                 :                :      */
                               4005                 :              9 :     ConditionVariablePrepareToSleep(&shared->cv);
                               4006                 :                :     for (;;)
                               4007                 :              8 :     {
                               4008                 :                :         int         last_exported;
                               4009                 :                : 
                               4010                 :             17 :         SpinLockAcquire(&shared->mutex);
                               4011                 :             17 :         last_exported = shared->last_exported;
                               4012                 :             17 :         SpinLockRelease(&shared->mutex);
                               4013                 :                : 
                               4014                 :                :         /*
                               4015                 :                :          * Has the worker exported the file we are waiting for?
                               4016                 :                :          */
                               4017         [ +  + ]:             17 :         if (last_exported == WORKER_FILE_SNAPSHOT)
                               4018                 :              9 :             break;
                               4019                 :                : 
                               4020                 :              8 :         ConditionVariableSleep(&shared->cv, WAIT_EVENT_REPACK_WORKER_EXPORT);
                               4021                 :                :     }
                               4022                 :              9 :     ConditionVariableCancelSleep();
                               4023                 :                : 
                               4024                 :                :     /* Read the snapshot from a file. */
                               4025                 :              9 :     DecodingWorkerFileName(fname, shared->relid, WORKER_FILE_SNAPSHOT);
                               4026                 :              9 :     file = BufFileOpenFileSet(&shared->sfs.fs, fname, O_RDONLY, false);
                               4027                 :              9 :     BufFileReadExact(file, &snap_size, sizeof(snap_size));
                               4028                 :              9 :     snap_space = (char *) palloc(snap_size);
                               4029                 :              9 :     BufFileReadExact(file, snap_space, snap_size);
                               4030                 :              9 :     BufFileClose(file);
                               4031                 :                : 
                               4032                 :                :     /* Restore it. */
                               4033                 :              9 :     snapshot = RestoreSnapshot(snap_space);
                               4034                 :              9 :     pfree(snap_space);
                               4035                 :                : 
                               4036                 :              9 :     return snapshot;
                               4037                 :                : }
                               4038                 :                : 
                               4039                 :                : /*
                               4040                 :                :  * Generate worker's file name into 'fname', which must be of size MAXPGPATH.
                               4041                 :                :  * If relations of the same 'relid' happen to be processed at the same time,
                               4042                 :                :  * they must be from different databases and therefore different backends must
                               4043                 :                :  * be involved.
                               4044                 :                :  */
                               4045                 :                : void
                               4046                 :             54 : DecodingWorkerFileName(char *fname, Oid relid, uint32 seq)
                               4047                 :                : {
                               4048                 :                :     /* The PID is already present in the fileset name, so we needn't add it */
                               4049                 :             54 :     snprintf(fname, MAXPGPATH, "%u-%u", relid, seq);
                               4050                 :             54 : }
                               4051                 :                : 
                               4052                 :                : /*
                               4053                 :                :  * Handle receipt of an interrupt indicating a repack worker message.
                               4054                 :                :  *
                               4055                 :                :  * Note: this is called within a signal handler!  All we can do is set
                               4056                 :                :  * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
                               4057                 :                :  * ProcessRepackMessages().
                               4058                 :                :  */
                               4059                 :                : void
                               4060                 :             10 : HandleRepackMessageInterrupt(void)
                               4061                 :                : {
                               4062                 :             10 :     InterruptPending = true;
                               4063                 :             10 :     RepackMessagePending = true;
                               4064                 :             10 :     SetLatch(MyLatch);
                               4065                 :             10 : }
                               4066                 :                : 
                               4067                 :                : /*
                               4068                 :                :  * Process any queued protocol messages received from the repack worker.
                               4069                 :                :  */
                               4070                 :                : void
                               4071                 :              9 : ProcessRepackMessages(void)
                               4072                 :                : {
                               4073                 :                :     MemoryContext oldcontext;
                               4074                 :                :     static MemoryContext hpm_context = NULL;
                               4075                 :                : 
                               4076                 :                :     /*
                               4077                 :                :      * Nothing to do if we haven't launched the worker yet or have already
                               4078                 :                :      * terminated it. Stopping the worker detaches the error message queue
                               4079                 :                :      * before clearing decoding_worker, so also bail out once error_mqh is
                               4080                 :                :      * gone.
                               4081                 :                :      */
    3                          4082   [ +  -  -  + ]:              9 :     if (decoding_worker == NULL || decoding_worker->error_mqh == NULL)
  167 alvherre@kurilemu.de     4083                 :UBC           0 :         return;
                               4084                 :                : 
                               4085                 :                :     /*
                               4086                 :                :      * This is invoked from ProcessInterrupts(), and since some of the
                               4087                 :                :      * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
                               4088                 :                :      * for recursive calls if more signals are received while this runs.  It's
                               4089                 :                :      * unclear that recursive entry would be safe, and it doesn't seem useful
                               4090                 :                :      * even if it is safe, so let's block interrupts until done.
                               4091                 :                :      */
  167 alvherre@kurilemu.de     4092                 :CBC           9 :     HOLD_INTERRUPTS();
                               4093                 :                : 
                               4094                 :                :     /*
                               4095                 :                :      * Moreover, CurrentMemoryContext might be pointing almost anywhere.  We
                               4096                 :                :      * don't want to risk leaking data into long-lived contexts, so let's do
                               4097                 :                :      * our work here in a private context that we can reset on each use.
                               4098                 :                :      */
                               4099         [ +  + ]:              9 :     if (hpm_context == NULL)    /* first time through? */
                               4100                 :              7 :         hpm_context = AllocSetContextCreate(TopMemoryContext,
                               4101                 :                :                                             "ProcessRepackMessages",
                               4102                 :                :                                             ALLOCSET_DEFAULT_SIZES);
                               4103                 :                :     else
                               4104                 :              2 :         MemoryContextReset(hpm_context);
                               4105                 :                : 
                               4106                 :              9 :     oldcontext = MemoryContextSwitchTo(hpm_context);
                               4107                 :                : 
                               4108                 :                :     /* OK to process messages.  Reset the flag saying there are more to do. */
                               4109                 :              9 :     RepackMessagePending = false;
                               4110                 :                : 
                               4111                 :                :     /*
                               4112                 :                :      * Read messages from the worker, but stop if the error queue disappears,
                               4113                 :                :      * which happens when a PqRepackMsg_Terminate is received; or as soon as
                               4114                 :                :      * no more messages can be read without blocking.  Messages are
                               4115                 :                :      * infrequent, so no point optimizing stringinfo allocation.
                               4116                 :                :      */
    3                          4117         [ +  + ]:             18 :     while (decoding_worker->error_mqh != NULL)
                               4118                 :                :     {
                               4119                 :                :         shm_mq_result res;
                               4120                 :                :         Size        nbytes;
                               4121                 :                :         void       *data;
                               4122                 :                :         StringInfoData msg;
                               4123                 :                : 
  167                          4124                 :              9 :         res = shm_mq_receive(decoding_worker->error_mqh, &nbytes,
                               4125                 :                :                              &data, true);
    3                          4126   [ +  -  -  - ]:              9 :         switch (res)
                               4127                 :                :         {
                               4128                 :              9 :             case SHM_MQ_SUCCESS:
                               4129                 :              9 :                 initStringInfo(&msg);
                               4130                 :              9 :                 appendBinaryStringInfo(&msg, data, nbytes);
                               4131                 :              9 :                 ProcessRepackMessage(&msg);
                               4132                 :              9 :                 pfree(msg.data);
                               4133                 :              9 :                 break;
                               4134                 :                : 
    3 alvherre@kurilemu.de     4135                 :UBC           0 :             case SHM_MQ_WOULD_BLOCK:
                               4136                 :                :                 /* no more messages to process for now */
                               4137                 :              0 :                 goto out;
                               4138                 :                : 
                               4139                 :              0 :             case SHM_MQ_DETACHED:
                               4140                 :                : 
                               4141                 :                :                 /*
                               4142                 :                :                  * Normal worker stop sends a Terminate message, causing
                               4143                 :                :                  * ProcessRepackMessage to set error_mqh to NULL, thus exiting
                               4144                 :                :                  * this loop; so this case should never happen.  If it does,
                               4145                 :                :                  * the worker terminated abnormally, so report that.
                               4146                 :                :                  */
                               4147         [ #  # ]:              0 :                 ereport(ERROR,
                               4148                 :                :                         errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               4149                 :                :                         errmsg("lost connection to REPACK decoding worker"),
                               4150                 :                :                         errhint("More details may be available in the server log."));
                               4151                 :                :         }
                               4152                 :                :     }
                               4153                 :                : 
    3 alvherre@kurilemu.de     4154                 :CBC           9 : out:
  167                          4155                 :              9 :     MemoryContextSwitchTo(oldcontext);
                               4156                 :                : 
                               4157                 :                :     /* Might as well clear the context on our way out */
                               4158                 :              9 :     MemoryContextReset(hpm_context);
                               4159                 :                : 
                               4160         [ -  + ]:              9 :     RESUME_INTERRUPTS();
                               4161                 :                : }
                               4162                 :                : 
                               4163                 :                : /*
                               4164                 :                :  * Process a single protocol message received from a repack worker.
                               4165                 :                :  */
                               4166                 :                : static void
                               4167                 :              9 : ProcessRepackMessage(StringInfo msg)
                               4168                 :                : {
                               4169                 :                :     char        msgtype;
                               4170                 :                : 
                               4171                 :              9 :     msgtype = pq_getmsgbyte(msg);
                               4172                 :                : 
                               4173      [ -  +  - ]:              9 :     switch (msgtype)
                               4174                 :                :     {
  167 alvherre@kurilemu.de     4175                 :UBC           0 :         case PqMsg_ErrorResponse:
                               4176                 :                :         case PqMsg_NoticeResponse:
                               4177                 :                :             {
                               4178                 :                :                 ErrorData   edata;
                               4179                 :                : 
                               4180                 :                :                 /* Parse ErrorResponse or NoticeResponse. */
                               4181                 :              0 :                 pq_parse_errornotice(msg, &edata);
                               4182                 :                : 
                               4183                 :                :                 /* Death of a worker isn't enough justification for suicide. */
                               4184                 :              0 :                 edata.elevel = Min(edata.elevel, ERROR);
                               4185                 :                : 
                               4186                 :                :                 /*
                               4187                 :                :                  * Add a context line to show that this is a message
                               4188                 :                :                  * propagated from the worker.  Otherwise, it can sometimes be
                               4189                 :                :                  * confusing to understand what actually happened.
                               4190                 :                :                  */
                               4191         [ #  # ]:              0 :                 if (edata.context)
                               4192                 :              0 :                     edata.context = psprintf("%s\n%s", edata.context,
                               4193                 :                :                                              _("REPACK decoding worker"));
                               4194                 :                :                 else
                               4195                 :              0 :                     edata.context = pstrdup(_("REPACK decoding worker"));
                               4196                 :                : 
                               4197                 :                :                 /* Rethrow error or print notice. */
                               4198                 :              0 :                 ThrowErrorData(&edata);
                               4199                 :                : 
                               4200                 :              0 :                 break;
                               4201                 :                :             }
                               4202                 :                : 
    3 alvherre@kurilemu.de     4203                 :CBC           9 :         case PqRepackMsg_Terminate:
                               4204                 :                : 
                               4205                 :                :             /*
                               4206                 :                :              * The worker has completed its work; stop watching its message
                               4207                 :                :              * queue now for orderly shutdown.
                               4208                 :                :              */
                               4209                 :              9 :             shm_mq_detach(decoding_worker->error_mqh);
                               4210                 :              9 :             decoding_worker->error_mqh = NULL;
                               4211                 :              9 :             break;
                               4212                 :                : 
  167 alvherre@kurilemu.de     4213                 :UBC           0 :         default:
    3                          4214         [ #  # ]:              0 :             elog(ERROR, "unrecognized message type received from decoding worker: %c (message length %d bytes)",
                               4215                 :                :                  msgtype, msg->len);
                               4216                 :                :     }
  167 alvherre@kurilemu.de     4217                 :CBC           9 : }
        

Generated by: LCOV version 2.0-1