PostgreSQL Source Code git master
Loading...
Searching...
No Matches
repack.c
Go to the documentation of this file.
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"
41#include "access/transam.h"
42#include "access/xact.h"
43#include "catalog/catalog.h"
44#include "catalog/dependency.h"
45#include "catalog/heap.h"
46#include "catalog/index.h"
47#include "catalog/namespace.h"
49#include "catalog/pg_am.h"
51#include "catalog/pg_inherits.h"
52#include "catalog/toasting.h"
53#include "commands/defrem.h"
54#include "commands/progress.h"
55#include "commands/repack.h"
57#include "commands/tablecmds.h"
58#include "commands/vacuum.h"
59#include "executor/executor.h"
60#include "libpq/pqformat.h"
61#include "libpq/pqmq.h"
62#include "miscadmin.h"
63#include "optimizer/optimizer.h"
64#include "pgstat.h"
66#include "storage/bufmgr.h"
67#include "storage/lmgr.h"
68#include "storage/predicate.h"
69#include "storage/proc.h"
70#include "utils/acl.h"
71#include "utils/fmgroids.h"
72#include "utils/guc.h"
74#include "utils/inval.h"
75#include "utils/lsyscache.h"
76#include "utils/memutils.h"
77#include "utils/pg_rusage.h"
78#include "utils/relmapper.h"
79#include "utils/snapmgr.h"
80#include "utils/syscache.h"
81#include "utils/wait_event_types.h"
82
83/*
84 * This struct is used to pass around the information on tables to be
85 * clustered. We need this so we can make a list of them when invoked without
86 * a specific table/index pair.
87 */
88typedef struct
89{
93
94/*
95 * The first file exported by the decoding worker must contain a snapshot, the
96 * following ones contain the data changes.
97 */
98#define WORKER_FILE_SNAPSHOT 0
99
100/*
101 * Information needed to apply concurrent data changes.
102 */
103typedef struct ChangeContext
104{
105 /* The relation the changes are applied to. */
107
108 /* Needed to update indexes of cc_rel. */
111
112 /*
113 * Existing tuples to UPDATE and DELETE are located via this index. We
114 * keep the scankey in partially initialized state to avoid repeated work.
115 * sk_argument is completed on the fly.
116 */
120
121 /* The latest column we need to deform to have the tuple identity */
123
124 /* Sequential number of the file containing the changes. */
127
128/*
129 * Backend-local information to control the decoding worker.
130 */
131typedef struct DecodingWorker
132{
133 /* The worker. */
135
136 /* DecodingWorkerShared is in this segment. */
138
139 /* Handle of the error queue. */
142
143/* Pointer to currently running decoding worker. */
145
146/*
147 * Is there a message sent by a repack worker that the backend needs to
148 * receive?
149 */
151
152static LOCKMODE RepackLockLevel(bool concurrent);
154 Oid indexOid, Oid userid, LOCKMODE lmode,
155 int options);
159 Oid ident_idx);
161 Snapshot snapshot,
162 bool verbose,
166static List *get_tables_to_repack(RepackCommand cmd, bool usingindex,
169 Oid relid, bool rel_is_index,
172 Oid relid, Oid userid);
173
175static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
180static void apply_concurrent_delete(Relation rel, TupleTableSlot *slot);
181static void restore_tuple(BufFile *file, Relation relation,
182 TupleTableSlot *slot);
183static void adjust_toast_pointers(Relation relation, TupleTableSlot *dest,
184 TupleTableSlot *src);
186 TupleTableSlot *locator,
189 TupleTableSlot *locator,
191static void process_concurrent_changes(XLogRecPtr end_of_wal,
193 bool done);
195 Relation relation,
206 LOCKMODE lockmode,
207 bool isTopLevel,
208 ClusterParams *params);
209static Oid determine_clustered_index(Relation rel, bool usingindex,
210 const char *indexname);
211
212static void start_repack_decoding_worker(Oid relid);
213static void stop_repack_decoding_worker(void);
215
216static void ProcessRepackMessage(StringInfo msg);
217static const char *RepackCommandAsString(RepackCommand cmd);
218
219
220/*
221 * The repack code allows for processing multiple tables at once. Because
222 * of this, we cannot just run everything on a single transaction, or we
223 * would be forced to acquire exclusive locks on all the tables being
224 * clustered, simultaneously --- very likely leading to deadlock.
225 *
226 * To solve this we follow a similar strategy to VACUUM code, processing each
227 * relation in a separate transaction. For this to work, we need to:
228 *
229 * - provide a separate memory context so that we can pass information in
230 * a way that survives across transactions
231 * - start a new transaction every time a new relation is clustered
232 * - check for validity of the information on to-be-clustered relations,
233 * as someone might have deleted a relation behind our back, or
234 * clustered one on a different index
235 * - end the transaction
236 *
237 * The single-relation case does not have any such overhead.
238 *
239 * We also allow a relation to be repacked following an index, but without
240 * naming a specific one. In that case, the indisclustered bit will be
241 * looked up, and an ERROR will be thrown if no so-marked index is found.
242 */
243void
245{
246 ClusterParams params = {0};
247 Relation rel = NULL;
249 LOCKMODE lockmode;
250 List *rtcs;
251
252 /* Parse option list */
253 foreach_node(DefElem, opt, stmt->params)
254 {
255 if (strcmp(opt->defname, "verbose") == 0)
256 params.options |= defGetBoolean(opt) ? CLUOPT_VERBOSE : 0;
257 else if (strcmp(opt->defname, "analyze") == 0 ||
258 strcmp(opt->defname, "analyse") == 0)
259 params.options |= defGetBoolean(opt) ? CLUOPT_ANALYZE : 0;
260 else if (strcmp(opt->defname, "concurrently") == 0 &&
261 defGetBoolean(opt))
262 {
263 if (stmt->command != REPACK_COMMAND_REPACK)
266 errmsg("CONCURRENTLY option not supported for %s",
267 RepackCommandAsString(stmt->command)));
268 params.options |= CLUOPT_CONCURRENT;
269 }
270 else
273 errmsg("unrecognized %s option \"%s\"",
274 RepackCommandAsString(stmt->command),
275 opt->defname),
276 parser_errposition(pstate, opt->location));
277 }
278
279 /* Determine the lock mode to use. */
280 lockmode = RepackLockLevel((params.options & CLUOPT_CONCURRENT) != 0);
281
282 if ((params.options & CLUOPT_CONCURRENT) != 0)
283 {
284 /*
285 * Make sure we're not in a transaction block.
286 *
287 * The reason is that repack_setup_logical_decoding() could wait
288 * indefinitely for our XID to complete. (The deadlock detector would
289 * not recognize it because we'd be waiting for ourselves, i.e. no
290 * real lock conflict.) It would be possible to run in a transaction
291 * block if we had no XID, but this restriction is simpler for users
292 * to understand and we don't lose any functionality.
293 */
294 PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
295 }
296
297 /*
298 * If a single relation is specified, process it and we're done ... unless
299 * the relation is a partitioned table, in which case we fall through.
300 */
301 if (stmt->relation != NULL)
302 {
303 rel = process_single_relation(stmt, lockmode, isTopLevel, &params);
304 if (rel == NULL)
305 return; /* all done */
306 }
307
308 /*
309 * Don't allow ANALYZE in the multiple-relation case for now. Maybe we
310 * can add support for this later.
311 */
312 if (params.options & CLUOPT_ANALYZE)
315 errmsg("cannot execute %s on multiple tables",
316 "REPACK (ANALYZE)"));
317
318 /*
319 * By here, we know we are in a multi-table situation.
320 *
321 * Concurrent processing is currently considered rather special (e.g. in
322 * terms of resources consumed) so it is not performed in bulk.
323 */
324 if (params.options & CLUOPT_CONCURRENT)
325 {
326 if (rel != NULL)
327 {
328 Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
331 errmsg("%s is not supported for partitioned tables",
332 "REPACK (CONCURRENTLY)"),
333 errhint("Consider running the command on individual partitions."));
334 }
335 else
338 errmsg("%s requires an explicit table name",
339 "REPACK (CONCURRENTLY)"));
340 }
341
342 /*
343 * In order to avoid holding locks for too long, we want to process each
344 * table in its own transaction. This forces us to disallow running
345 * inside a user transaction block.
346 */
348
349 /* Also, we need a memory context to hold our list of relations */
351 "Repack",
353
354 /*
355 * Since we open a new transaction for each relation, we have to check
356 * that the relation still is what we think it is.
357 *
358 * In single-transaction CLUSTER, we don't need the overhead.
359 */
360 params.options |= CLUOPT_RECHECK;
361
362 /*
363 * If we don't have a relation yet, determine a relation list. If we do,
364 * then it must be a partitioned table, and we want to process its
365 * partitions.
366 */
367 if (rel == NULL)
368 {
369 Assert(stmt->indexname == NULL);
370 rtcs = get_tables_to_repack(stmt->command, stmt->usingindex,
373 }
374 else
375 {
376 Oid relid;
377 bool rel_is_index;
378
379 Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
380
381 /*
382 * If USING INDEX was specified, resolve the index name now and pass
383 * it down.
384 */
385 if (stmt->usingindex)
386 {
387 /*
388 * If no index name was specified when repacking a partitioned
389 * table, punt for now. Maybe we can improve this later.
390 */
391 if (!stmt->indexname)
392 {
393 if (stmt->command == REPACK_COMMAND_CLUSTER)
396 errmsg("there is no previously clustered index for table \"%s\"",
398 else
401 /*- translator: first %s is name of a SQL command, eg. REPACK */
402 errmsg("cannot execute %s on partitioned table \"%s\" USING INDEX with no index name",
403 RepackCommandAsString(stmt->command),
405 }
406
407 relid = determine_clustered_index(rel, stmt->usingindex,
408 stmt->indexname);
409 if (!OidIsValid(relid))
410 elog(ERROR, "unable to determine index to cluster on");
412
413 rel_is_index = true;
414 }
415 else
416 {
417 relid = RelationGetRelid(rel);
418 rel_is_index = false;
419 }
420
422 relid, rel_is_index,
424
425 /* close parent relation, releasing lock on it */
427 rel = NULL;
428 }
429
430 /* Commit to get out of starting transaction */
433
434 /* Cluster the tables, each in a separate transaction */
435 Assert(rel == NULL);
437 {
438 /* Start a new transaction for each relation. */
440
441 /*
442 * Open the target table, coping with the case where it has been
443 * dropped.
444 */
445 rel = try_table_open(rtc->tableOid, lockmode);
446 if (rel == NULL)
447 {
449 continue;
450 }
451
452 /* functions in indexes may want a snapshot set */
454
455 /* Process this table */
456 cluster_rel(stmt->command, rel, rtc->indexOid, &params, isTopLevel);
457 /* cluster_rel closes the relation, but keeps lock */
458
461 }
462
463 /* Start a new transaction for the cleanup work. */
465
466 /* Clean up working storage */
468}
469
470/*
471 * In the non-concurrent case, we obtain AccessExclusiveLock throughout the
472 * operation to avoid any lock-upgrade hazards. In the concurrent case, we
473 * grab ShareUpdateExclusiveLock (just like VACUUM) for most of the
474 * processing and only acquire AccessExclusiveLock at the end, to swap the
475 * relation -- supposedly for a short time.
476 */
477static LOCKMODE
478RepackLockLevel(bool concurrent)
479{
480 if (concurrent)
482 else
483 return AccessExclusiveLock;
484}
485
486/*
487 * cluster_rel
488 *
489 * This clusters the table by creating a new, clustered table and
490 * swapping the relfilenumbers of the new table and the old table, so
491 * the OID of the original table is preserved. Thus we do not lose
492 * GRANT, inheritance nor references to this table.
493 *
494 * Indexes are rebuilt too, via REINDEX. Since we are effectively bulk-loading
495 * the new table, it's better to create the indexes afterwards than to fill
496 * them incrementally while we load the table.
497 *
498 * If indexOid is InvalidOid, the table will be rewritten in physical order
499 * instead of index order.
500 *
501 * Note that, in the concurrent case, the function releases the lock at some
502 * point, in order to get AccessExclusiveLock for the final steps (i.e. to
503 * swap the relation files). To make things simpler, the caller should expect
504 * OldHeap to be closed on return, regardless CLUOPT_CONCURRENT. (The
505 * AccessExclusiveLock is kept till the end of the transaction.)
506 *
507 * 'cmd' indicates which command is being executed, to be used for error
508 * messages.
509 */
510void
512 ClusterParams *params, bool isTopLevel)
513{
514 Oid tableOid = RelationGetRelid(OldHeap);
517 Oid save_userid;
518 int save_sec_context;
519 int save_nestlevel;
520 bool verbose = ((params->options & CLUOPT_VERBOSE) != 0);
521 bool recheck = ((params->options & CLUOPT_RECHECK) != 0);
522 bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0);
524
525 /* Determine the lock mode to use. */
526 lmode = RepackLockLevel(concurrent);
527
528 /*
529 * Check some preconditions in the concurrent case. This also obtains the
530 * replica index OID.
531 */
532 if (concurrent)
534
535 /* Check for user-requested abort. */
537
540
541 /*
542 * Switch to the table owner's userid, so that any index functions are run
543 * as that user. Also lock down security-restricted operations and
544 * arrange to make GUC variable changes local to this command.
545 */
546 GetUserIdAndSecContext(&save_userid, &save_sec_context);
547 SetUserIdAndSecContext(OldHeap->rd_rel->relowner,
548 save_sec_context | SECURITY_RESTRICTED_OPERATION);
549 save_nestlevel = NewGUCNestLevel();
551
552 /*
553 * Recheck that the relation is still what it was when we started.
554 *
555 * Note that it's critical to skip this in single-relation CLUSTER;
556 * otherwise, we would reject an attempt to cluster using a
557 * not-previously-clustered index.
558 */
559 if (recheck &&
560 !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid,
561 lmode, params->options))
562 goto out;
563
564 /*
565 * We allow repacking shared catalogs only when not using an index. It
566 * would work to use an index in most respects, but the index would only
567 * get marked as indisclustered in the current database, leading to
568 * unexpected behavior if CLUSTER were later invoked in another database.
569 */
570 if (OidIsValid(indexOid) && OldHeap->rd_rel->relisshared)
573 /*- translator: first %s is name of a SQL command, eg. REPACK */
574 errmsg("cannot execute %s on a shared catalog",
576
577 /*
578 * The CONCURRENTLY case should have been rejected earlier because it does
579 * not support system catalogs.
580 */
581 Assert(!(OldHeap->rd_rel->relisshared && concurrent));
582
583 /*
584 * Don't process temp tables of other backends ... their local buffer
585 * manager is not going to cope.
586 */
590 /*- translator: first %s is name of a SQL command, eg. REPACK */
591 errmsg("cannot execute %s on temporary tables of other sessions",
593
594 /*
595 * Also check for active uses of the relation in the current transaction,
596 * including open scans and pending AFTER trigger events.
597 */
599
600 /* Check heap and index are valid to cluster on */
601 if (OidIsValid(indexOid))
602 {
603 /* verify the index is good and lock it */
605 /* also open it */
606 index = index_open(indexOid, NoLock);
607 }
608 else
609 index = NULL;
610
611 /*
612 * When allow_system_table_mods is turned off, we disallow repacking a
613 * catalog on a particular index unless that's already the clustered index
614 * for that catalog.
615 *
616 * XXX We don't check for this in CLUSTER, because it's historically been
617 * allowed.
618 */
619 if (cmd != REPACK_COMMAND_CLUSTER &&
620 !allowSystemTableMods && OidIsValid(indexOid) &&
621 IsCatalogRelation(OldHeap) && !index->rd_index->indisclustered)
624 errmsg("permission denied: \"%s\" is a system catalog",
626 errdetail("System catalogs can only be clustered by the index they're already clustered on, if any, unless \"%s\" is enabled.",
627 "allow_system_table_mods"));
628
629 /*
630 * Quietly ignore the request if this is a materialized view which has not
631 * been populated from its query. No harm is done because there is no data
632 * to deal with, and we don't want to throw an error if this is part of a
633 * multi-relation request -- for example, CLUSTER was run on the entire
634 * database.
635 */
636 if (OldHeap->rd_rel->relkind == RELKIND_MATVIEW &&
638 {
639 if (index)
642 goto out;
643 }
644
645 Assert(OldHeap->rd_rel->relkind == RELKIND_RELATION ||
646 OldHeap->rd_rel->relkind == RELKIND_MATVIEW ||
647 OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE);
648
649 /*
650 * All predicate locks on the tuples or pages are about to be made
651 * invalid, because we move tuples around. Promote them to relation
652 * locks. Predicate locks on indexes will be promoted when they are
653 * reindexed.
654 *
655 * During concurrent processing, the heap as well as its indexes stay in
656 * operation, so we postpone this step until they are locked using
657 * AccessExclusiveLock near the end of the processing.
658 */
659 if (!concurrent)
661
662 /* rebuild_relation does all the dirty work */
663 PG_TRY();
664 {
666 }
667 PG_FINALLY();
668 {
669 if (concurrent)
670 {
671 /*
672 * Since during normal operation the worker was already asked to
673 * exit, stopping it explicitly is especially important on ERROR.
674 * However it still seems a good practice to make sure that the
675 * worker never survives the REPACK command.
676 */
678 }
679 }
680 PG_END_TRY();
681
682 /* rebuild_relation closes OldHeap, and index if valid */
683
684out:
685 /* Roll back any GUC changes executed by index functions */
686 AtEOXact_GUC(false, save_nestlevel);
687
688 /* Restore userid and security context */
689 SetUserIdAndSecContext(save_userid, save_sec_context);
690
692}
693
694/*
695 * Check if the table (and its index) still meets the requirements of
696 * cluster_rel().
697 */
698static bool
700 Oid userid, LOCKMODE lmode, int options)
701{
702 Oid tableOid = RelationGetRelid(OldHeap);
703
704 /* Check that the user still has privileges for the relation */
705 if (!repack_is_permitted_for_relation(cmd, tableOid, userid))
706 {
708 return false;
709 }
710
711 /*
712 * Silently skip a temp table for a remote session. Only doing this check
713 * in the "recheck" case is appropriate (which currently means somebody is
714 * executing a database-wide CLUSTER or on a partitioned table), because
715 * there is another check in cluster() which will stop any attempt to
716 * cluster remote temp tables by name. There is another check in
717 * cluster_rel which is redundant, but we leave it for extra safety.
718 */
720 {
722 return false;
723 }
724
725 if (OidIsValid(indexOid))
726 {
727 /*
728 * Check that the index still exists
729 */
731 {
733 return false;
734 }
735
736 /*
737 * Check that the index is still the one with indisclustered set, if
738 * needed.
739 */
740 if ((options & CLUOPT_RECHECK_ISCLUSTERED) != 0 &&
741 !get_index_isclustered(indexOid))
742 {
744 return false;
745 }
746 }
747
748 return true;
749}
750
751/*
752 * Verify that the specified heap and index are valid to cluster on
753 *
754 * Side effect: obtains lock on the index. The caller may
755 * in some cases already have a lock of the same strength on the table, but
756 * not in all cases so we can't rely on the table-level lock for
757 * protection here.
758 */
759void
761{
763
764 OldIndex = index_open(indexOid, lockmode);
765
766 /*
767 * Check that index is in fact an index on the given relation
768 */
769 if (OldIndex->rd_index == NULL ||
770 OldIndex->rd_index->indrelid != RelationGetRelid(OldHeap))
773 errmsg("\"%s\" is not an index for table \"%s\"",
776
777 /* Index AM must allow clustering */
778 if (!OldIndex->rd_indam->amclusterable)
781 errmsg("cannot cluster on index \"%s\" because access method does not support clustering",
783
784 /*
785 * Disallow clustering on incomplete indexes (those that might not index
786 * every row of the relation). We could relax this by making a separate
787 * seqscan pass over the table to copy the missing rows, but that seems
788 * expensive and tedious.
789 */
790 if (!heap_attisnull(OldIndex->rd_indextuple, Anum_pg_index_indpred, NULL))
793 errmsg("cannot cluster on partial index \"%s\"",
795
796 /*
797 * Disallow if index is left over from a failed CREATE INDEX CONCURRENTLY;
798 * it might well not contain entries for every heap row, or might not even
799 * be internally consistent. (But note that we don't check indcheckxmin;
800 * the worst consequence of following broken HOT chains would be that we
801 * might put recently-dead tuples out-of-order in the new table, and there
802 * is little harm in that.)
803 */
804 if (!OldIndex->rd_index->indisvalid)
807 errmsg("cannot cluster on invalid index \"%s\"",
809
810 /* Drop relcache refcnt on OldIndex, but keep lock */
812}
813
814/*
815 * mark_index_clustered: mark the specified index as the one clustered on
816 *
817 * With indexOid == InvalidOid, will mark all indexes of rel not-clustered.
818 */
819void
820mark_index_clustered(Relation rel, Oid indexOid, bool is_internal)
821{
826
827 Assert(rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
828
829 /*
830 * If the index is already marked clustered, no need to do anything.
831 */
832 if (OidIsValid(indexOid))
833 {
834 if (get_index_isclustered(indexOid))
835 return;
836 }
837
838 /*
839 * Check each index of the relation and set/clear the bit as needed.
840 */
842
843 foreach(index, RelationGetIndexList(rel))
844 {
846
850 elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
852
853 /*
854 * Unset the bit if set. We know it's wrong because we checked this
855 * earlier.
856 */
857 if (indexForm->indisclustered)
858 {
859 indexForm->indisclustered = false;
861 }
862 else if (thisIndexOid == indexOid)
863 {
864 /* this was checked earlier, but let's be real sure */
865 if (!indexForm->indisvalid)
866 elog(ERROR, "cannot cluster on invalid index %u", indexOid);
867 indexForm->indisclustered = true;
869 }
870
872 InvalidOid, is_internal);
873
875 }
876
878}
879
880/*
881 * Check if the CONCURRENTLY option is legal for the relation.
882 *
883 * *Ident_idx_p receives OID of the identity index.
884 */
885static void
887{
888 char relpersistence,
889 replident;
891
892 /* Data changes in system relations are not logically decoded. */
893 if (IsCatalogRelation(rel))
896 errmsg("cannot repack relation \"%s\"",
898 errhint("%s is not supported for catalog relations.",
899 "REPACK (CONCURRENTLY)"));
900
901 /*
902 * reorderbuffer.c does not seem to handle processing of TOAST relation
903 * alone.
904 */
905 if (IsToastRelation(rel))
908 errmsg("cannot repack relation \"%s\"",
910 errhint("%s is not supported for TOAST relations.",
911 "REPACK (CONCURRENTLY)"));
912
913 relpersistence = rel->rd_rel->relpersistence;
914 if (relpersistence != RELPERSISTENCE_PERMANENT)
917 errmsg("cannot repack relation \"%s\"",
919 errhint("%s is only allowed for permanent relations.",
920 "REPACK (CONCURRENTLY)"));
921
922 /* With NOTHING, WAL does not contain the old tuple. */
923 replident = rel->rd_rel->relreplident;
924 if (replident == REPLICA_IDENTITY_NOTHING)
927 errmsg("cannot repack relation \"%s\"",
929 errhint("Relation \"%s\" has insufficient replication identity.",
931
932 /*
933 * Obtain the replica identity index -- either one that has been set
934 * explicitly, or a non-deferrable primary key. If none of these cases
935 * apply, the table cannot be repacked concurrently. It might be possible
936 * to have repack work with a FULL replica identity; however that requires
937 * more work and is not implemented yet.
938 */
940 if (!OidIsValid(ident_idx))
943 errmsg("cannot process relation \"%s\"",
945 errhint("Relation \"%s\" has no identity index.",
947
949}
950
951
952/*
953 * rebuild_relation: rebuild an existing relation in index or physical order
954 *
955 * OldHeap: table to rebuild. See cluster_rel() for comments on the required
956 * lock strength.
957 *
958 * index: index to cluster by, or NULL to rewrite in physical order.
959 *
960 * ident_idx: identity index, to handle replaying of concurrent data changes
961 * to the new heap. InvalidOid if there's no CONCURRENTLY option.
962 *
963 * On entry, heap and index (if one is given) must be open, and the
964 * appropriate lock held on them -- AccessExclusiveLock for exclusive
965 * processing and ShareUpdateExclusiveLock for concurrent processing.
966 *
967 * On exit, they are closed, but still locked with AccessExclusiveLock.
968 * (The function handles the lock upgrade if 'concurrent' is true.)
969 */
970static void
973{
974 Oid tableOid = RelationGetRelid(OldHeap);
975 Oid accessMethod = OldHeap->rd_rel->relam;
976 Oid tableSpace = OldHeap->rd_rel->reltablespace;
979 char relpersistence;
983 bool concurrent = OidIsValid(ident_idx);
984 Snapshot snapshot = NULL;
985#if USE_ASSERT_CHECKING
987
988 lmode = RepackLockLevel(concurrent);
989
992#endif
993
994 if (concurrent)
995 {
996 /*
997 * The worker needs to be member of the locking group we're the leader
998 * of. We ought to become the leader before the worker starts. The
999 * worker will join the group as soon as it starts.
1000 *
1001 * This is to make sure that the deadlock described below is
1002 * detectable by deadlock.c: if the worker waits for a transaction to
1003 * complete and we are waiting for the worker output, then effectively
1004 * we (i.e. this backend) are waiting for that transaction.
1005 */
1007
1008 /*
1009 * Start the worker that decodes data changes applied while we're
1010 * copying the table contents.
1011 *
1012 * Note that the worker has to wait for all transactions with XID
1013 * already assigned to finish. If some of those transactions is
1014 * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
1015 * table (e.g. it runs CREATE INDEX), we can end up in a deadlock.
1016 * Not sure this risk is worth unlocking/locking the table (and its
1017 * clustering index) and checking again if it's still eligible for
1018 * REPACK CONCURRENTLY.
1019 */
1021
1022 /*
1023 * Wait until the worker has the initial snapshot and retrieve it.
1024 */
1026
1027 PushActiveSnapshot(snapshot);
1028 }
1029
1030 /* for CLUSTER or REPACK USING INDEX, mark the index as the one to use */
1031 if (index != NULL)
1033
1034 /* Remember info about rel before closing OldHeap */
1035 relpersistence = OldHeap->rd_rel->relpersistence;
1036
1037 /*
1038 * Create the transient table that will receive the re-ordered data.
1039 *
1040 * OldHeap is already locked, so no need to lock it again. make_new_heap
1041 * obtains AccessExclusiveLock on the new heap and its toast table.
1042 */
1043 OIDNewHeap = make_new_heap(tableOid, tableSpace,
1044 accessMethod,
1045 relpersistence,
1046 NoLock);
1049
1050 /* Copy the heap data into the new table in the desired order */
1053
1054 /* The historic snapshot won't be needed anymore. */
1055 if (snapshot)
1056 {
1059 }
1060
1061 if (concurrent)
1062 {
1064
1065 /*
1066 * Close the index, but keep the lock. Both heaps will be closed by
1067 * the following call.
1068 */
1069 if (index)
1071
1074
1077 }
1078 else
1079 {
1081
1082 /* Close relcache entries, but keep lock until transaction commit */
1084 if (index)
1086
1087 /*
1088 * Close the new relation so it can be dropped as soon as the storage
1089 * is swapped. The relation is not visible to others, so no need to
1090 * unlock it explicitly.
1091 */
1093
1094 /*
1095 * Swap the physical files of the target and transient tables, then
1096 * rebuild the target's indexes and throw away the transient table.
1097 */
1099 swap_toast_by_content, false, true,
1100 true, /* reindex */
1102 relpersistence);
1103 }
1104}
1105
1106
1107/*
1108 * Create the transient table that will be filled with new data during
1109 * CLUSTER, ALTER TABLE, and similar operations. The transient table
1110 * duplicates the logical structure of the OldHeap; but will have the
1111 * specified physical storage properties NewTableSpace, NewAccessMethod, and
1112 * relpersistence.
1113 *
1114 * After this, the caller should load the new heap with transferred/modified
1115 * data, then call finish_heap_swap to complete the operation.
1116 */
1117Oid
1119 char relpersistence, LOCKMODE lockmode)
1120{
1124 Oid toastid;
1126 HeapTuple tuple;
1127 Datum reloptions;
1128 bool isNull;
1130
1131 OldHeap = table_open(OIDOldHeap, lockmode);
1133
1134 /*
1135 * Note that the NewHeap will not receive any of the defaults or
1136 * constraints associated with the OldHeap; we don't need 'em, and there's
1137 * no reason to spend cycles inserting them into the catalogs only to
1138 * delete them.
1139 */
1140
1141 /*
1142 * But we do want to use reloptions of the old heap for new heap.
1143 */
1145 if (!HeapTupleIsValid(tuple))
1146 elog(ERROR, "cache lookup failed for relation %u", OIDOldHeap);
1147 reloptions = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
1148 &isNull);
1149 if (isNull)
1150 reloptions = (Datum) 0;
1151
1152 if (relpersistence == RELPERSISTENCE_TEMP)
1154 else
1156
1157 /*
1158 * Create the new heap, using a temporary name in the same namespace as
1159 * the existing table. NOTE: there is some risk of collision with user
1160 * relnames. Working around this seems more trouble than it's worth; in
1161 * particular, we can't create the new heap in a different namespace from
1162 * the old, or we will have problems with the TEMP status of temp tables.
1163 *
1164 * Note: the new heap is not a shared relation, even if we are rebuilding
1165 * a shared rel. However, we do make the new heap mapped if the source is
1166 * mapped. This simplifies swap_relation_files, and is absolutely
1167 * necessary for rebuilding pg_class, for reasons explained there.
1168 */
1169 snprintf(NewHeapName, sizeof(NewHeapName), "pg_temp_%u", OIDOldHeap);
1170
1174 InvalidOid,
1175 InvalidOid,
1176 InvalidOid,
1177 OldHeap->rd_rel->relowner,
1180 NIL,
1182 relpersistence,
1183 false,
1186 reloptions,
1187 false,
1188 true,
1189 true,
1190 OIDOldHeap,
1191 NULL);
1193
1194 ReleaseSysCache(tuple);
1195
1196 /*
1197 * Advance command counter so that the newly-created relation's catalog
1198 * tuples will be visible to table_open.
1199 */
1201
1202 /*
1203 * If necessary, create a TOAST table for the new relation.
1204 *
1205 * If the relation doesn't have a TOAST table already, we can't need one
1206 * for the new relation. The other way around is possible though: if some
1207 * wide columns have been dropped, NewHeapCreateToastTable can decide that
1208 * no TOAST table is needed for the new table.
1209 *
1210 * Note that NewHeapCreateToastTable ends with CommandCounterIncrement, so
1211 * that the TOAST table will be visible for insertion.
1212 */
1213 toastid = OldHeap->rd_rel->reltoastrelid;
1214 if (OidIsValid(toastid))
1215 {
1216 /* keep the existing toast table's reloptions, if any */
1218 if (!HeapTupleIsValid(tuple))
1219 elog(ERROR, "cache lookup failed for relation %u", toastid);
1220 reloptions = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
1221 &isNull);
1222 if (isNull)
1223 reloptions = (Datum) 0;
1224
1225 NewHeapCreateToastTable(OIDNewHeap, reloptions, lockmode, toastid);
1226
1227 ReleaseSysCache(tuple);
1228 }
1229
1231
1232 return OIDNewHeap;
1233}
1234
1235/*
1236 * Do the physical copying of table data.
1237 *
1238 * 'snapshot' and 'decoding_ctx': see table_relation_copy_for_cluster(). Pass
1239 * iff concurrent processing is required.
1240 *
1241 * There are three output parameters:
1242 * *pSwapToastByContent is set true if toast tables must be swapped by content.
1243 * *pFreezeXid receives the TransactionId used as freeze cutoff point.
1244 * *pCutoffMulti receives the MultiXactId used as a cutoff point.
1245 */
1246static void
1248 Snapshot snapshot, bool verbose, bool *pSwapToastByContent,
1250{
1256 VacuumParams params;
1257 struct VacuumCutoffs cutoffs;
1258 bool use_sort;
1259 double num_tuples = 0,
1260 tups_vacuumed = 0,
1262 BlockNumber num_pages;
1263 int elevel = verbose ? INFO : DEBUG2;
1264 PGRUsage ru0;
1265 char *nspname;
1266 bool concurrent = snapshot != NULL;
1268
1269 lmode = RepackLockLevel(concurrent);
1270
1272
1273 /* Store a copy of the namespace name for logging purposes */
1275
1276 /*
1277 * Their tuple descriptors should be exactly alike, but here we only need
1278 * assume that they have the same number of columns.
1279 */
1282 Assert(newTupDesc->natts == oldTupDesc->natts);
1283
1284 /*
1285 * If the OldHeap has a toast table, get lock on the toast table to keep
1286 * it from being vacuumed. This is needed because autovacuum processes
1287 * toast tables independently of their main tables, with no lock on the
1288 * latter. If an autovacuum were to start on the toast table after we
1289 * compute our OldestXmin below, it would use a later OldestXmin, and then
1290 * possibly remove as DEAD toast tuples belonging to main tuples we think
1291 * are only RECENTLY_DEAD. Then we'd fail while trying to copy those
1292 * tuples.
1293 *
1294 * We don't need to open the toast relation here, just lock it. The lock
1295 * will be held till end of transaction.
1296 */
1297 if (OldHeap->rd_rel->reltoastrelid)
1298 LockRelationOid(OldHeap->rd_rel->reltoastrelid, lmode);
1299
1300 /*
1301 * If both tables have TOAST tables, perform toast swap by content. It is
1302 * possible that the old table has a toast table but the new one doesn't,
1303 * if toastable columns have been dropped. In that case we have to do
1304 * swap by links. This is okay because swap by content is only essential
1305 * for system catalogs, and we don't support schema changes for them.
1306 */
1307 if (OldHeap->rd_rel->reltoastrelid && NewHeap->rd_rel->reltoastrelid &&
1308 !concurrent)
1309 {
1310 *pSwapToastByContent = true;
1311
1312 /*
1313 * When doing swap by content, any toast pointers written into NewHeap
1314 * must use the old toast table's OID, because that's where the toast
1315 * data will eventually be found. Set this up by setting rd_toastoid.
1316 * This also tells toast_save_datum() to preserve the toast value
1317 * OIDs, which we want so as not to invalidate toast pointers in
1318 * system catalog caches, and to avoid making multiple copies of a
1319 * single toast value.
1320 *
1321 * Note that we must hold NewHeap open until we are done writing data,
1322 * since the relcache will not guarantee to remember this setting once
1323 * the relation is closed. Also, this technique depends on the fact
1324 * that no one will try to read from the NewHeap until after we've
1325 * finished writing it and swapping the rels --- otherwise they could
1326 * follow the toast pointers to the wrong place. (It would actually
1327 * work for values copied over from the old toast table, but not for
1328 * any values that we toast which were previously not toasted.)
1329 *
1330 * This would not work with CONCURRENTLY because we may need to delete
1331 * TOASTed tuples from the new heap. With this hack, we'd delete them
1332 * from the old heap.
1333 */
1334 NewHeap->rd_toastoid = OldHeap->rd_rel->reltoastrelid;
1335 }
1336 else
1337 *pSwapToastByContent = false;
1338
1339 /*
1340 * Compute xids used to freeze and weed out dead tuples and multixacts.
1341 * Since we're going to rewrite the whole table anyway, there's no reason
1342 * not to be aggressive about this.
1343 */
1344 memset(&params, 0, sizeof(VacuumParams));
1345 vacuum_get_cutoffs(OldHeap, &params, &cutoffs);
1346
1347 /*
1348 * FreezeXid will become the table's new relfrozenxid, and that mustn't go
1349 * backwards, so take the max.
1350 */
1351 {
1352 TransactionId relfrozenxid = OldHeap->rd_rel->relfrozenxid;
1353
1356 cutoffs.FreezeLimit = relfrozenxid;
1357 }
1358
1359 /*
1360 * MultiXactCutoff, similarly, shouldn't go backwards either.
1361 */
1362 {
1363 MultiXactId relminmxid = OldHeap->rd_rel->relminmxid;
1364
1367 cutoffs.MultiXactCutoff = relminmxid;
1368 }
1369
1370 /*
1371 * Decide whether to use an indexscan or seqscan-and-optional-sort to scan
1372 * the OldHeap. We know how to use a sort to duplicate the ordering of a
1373 * btree index, and will use seqscan-and-sort for that case if the planner
1374 * tells us it's cheaper. Otherwise, always indexscan if an index is
1375 * provided, else plain seqscan.
1376 */
1377 if (OldIndex != NULL && OldIndex->rd_rel->relam == BTREE_AM_OID)
1380 else
1381 use_sort = false;
1382
1383 /* Log what we're doing */
1384 if (OldIndex != NULL && !use_sort)
1385 ereport(elevel,
1386 errmsg("repacking \"%s.%s\" using index scan on \"%s\"",
1387 nspname,
1390 else if (use_sort)
1391 ereport(elevel,
1392 errmsg("repacking \"%s.%s\" using sequential scan and sort",
1393 nspname,
1395 else
1396 ereport(elevel,
1397 errmsg("repacking \"%s.%s\" in physical order",
1398 nspname,
1400
1401 /*
1402 * Hand off the actual copying to AM specific function, the generic code
1403 * cannot know how to deal with visibility across AMs. Note that this
1404 * routine is allowed to set FreezeXid / MultiXactCutoff to different
1405 * values (e.g. because the AM doesn't use freezing).
1406 */
1408 cutoffs.OldestXmin, snapshot,
1409 &cutoffs.FreezeLimit,
1410 &cutoffs.MultiXactCutoff,
1411 &num_tuples, &tups_vacuumed,
1413
1414 /* return selected values to caller, get set as relfrozenxid/minmxid */
1415 *pFreezeXid = cutoffs.FreezeLimit;
1416 *pCutoffMulti = cutoffs.MultiXactCutoff;
1417
1418 /*
1419 * Reset rd_toastoid just to be tidy --- it shouldn't be looked at again.
1420 * In the CONCURRENTLY case, we need to set it again before applying the
1421 * concurrent changes.
1422 */
1423 NewHeap->rd_toastoid = InvalidOid;
1424
1426
1427 /* Log what we did */
1428 ereport(elevel,
1429 (errmsg("\"%s.%s\": found %.0f removable, %.0f nonremovable row versions in %u pages",
1430 nspname,
1432 tups_vacuumed, num_tuples,
1434 errdetail("%.0f dead row versions cannot be removed yet.\n"
1435 "%s.",
1437 pg_rusage_show(&ru0))));
1438
1439 /* Update pg_class to reflect the correct values of pages and tuples. */
1441
1445 elog(ERROR, "cache lookup failed for relation %u",
1448
1449 relform->relpages = num_pages;
1450 relform->reltuples = num_tuples;
1451
1452 /* Don't update the stats for pg_class. See swap_relation_files. */
1455 else
1457
1458 /* Clean up. */
1461
1462 /* Make the update visible */
1464}
1465
1466/*
1467 * Swap the physical files of two given relations.
1468 *
1469 * We swap the physical identity (reltablespace, relfilenumber) while keeping
1470 * the same logical identities of the two relations. relpersistence is also
1471 * swapped, which is critical since it determines where buffers live for each
1472 * relation.
1473 *
1474 * We can swap associated TOAST data in either of two ways: recursively swap
1475 * the physical content of the toast tables (and their indexes), or swap the
1476 * TOAST links in the given relations' pg_class entries. The former is needed
1477 * to manage rewrites of shared catalogs (where we cannot change the pg_class
1478 * links) while the latter is the only way to handle cases in which a toast
1479 * table is added or removed altogether.
1480 *
1481 * Additionally, the first relation is marked with relfrozenxid set to
1482 * frozenXid. It seems a bit ugly to have this here, but the caller would
1483 * have to do it anyway, so having it here saves a heap_update. Note: in
1484 * the swap-toast-links case, we assume we don't need to change the toast
1485 * table's relfrozenxid: the new version of the toast table should already
1486 * have relfrozenxid set to RecentXmin, which is good enough.
1487 *
1488 * Lastly, if r2 and its toast table and toast index (if any) are mapped,
1489 * their OIDs are emitted into mapped_tables[]. This is hacky but beats
1490 * having to look the information up again later in finish_heap_swap.
1491 */
1492static void
1495 bool is_internal,
1499{
1502 reltup2;
1504 relform2;
1508 char swptmpchr;
1509 Oid relam1,
1510 relam2;
1511
1512 /* We need writable copies of both pg_class tuples. */
1514
1517 elog(ERROR, "cache lookup failed for relation %u", r1);
1519
1522 elog(ERROR, "cache lookup failed for relation %u", r2);
1524
1525 relfilenumber1 = relform1->relfilenode;
1526 relfilenumber2 = relform2->relfilenode;
1527 relam1 = relform1->relam;
1528 relam2 = relform2->relam;
1529
1532 {
1533 /*
1534 * Normal non-mapped relations: swap relfilenumbers, reltablespaces,
1535 * relpersistence
1536 */
1538
1539 swaptemp = relform1->relfilenode;
1540 relform1->relfilenode = relform2->relfilenode;
1541 relform2->relfilenode = swaptemp;
1542
1543 swaptemp = relform1->reltablespace;
1544 relform1->reltablespace = relform2->reltablespace;
1545 relform2->reltablespace = swaptemp;
1546
1547 swaptemp = relform1->relam;
1548 relform1->relam = relform2->relam;
1549 relform2->relam = swaptemp;
1550
1551 swptmpchr = relform1->relpersistence;
1552 relform1->relpersistence = relform2->relpersistence;
1553 relform2->relpersistence = swptmpchr;
1554
1555 /* Also swap toast links, if we're swapping by links */
1557 {
1558 swaptemp = relform1->reltoastrelid;
1559 relform1->reltoastrelid = relform2->reltoastrelid;
1560 relform2->reltoastrelid = swaptemp;
1561 }
1562 }
1563 else
1564 {
1565 /*
1566 * Mapped-relation case. Here we have to swap the relation mappings
1567 * instead of modifying the pg_class columns. Both must be mapped.
1568 */
1571 elog(ERROR, "cannot swap mapped relation \"%s\" with non-mapped relation",
1572 NameStr(relform1->relname));
1573
1574 /*
1575 * We can't change the tablespace nor persistence of a mapped rel, and
1576 * we can't handle toast link swapping for one either, because we must
1577 * not apply any critical changes to its pg_class row. These cases
1578 * should be prevented by upstream permissions tests, so these checks
1579 * are non-user-facing emergency backstop.
1580 */
1581 if (relform1->reltablespace != relform2->reltablespace)
1582 elog(ERROR, "cannot change tablespace of mapped relation \"%s\"",
1583 NameStr(relform1->relname));
1584 if (relform1->relpersistence != relform2->relpersistence)
1585 elog(ERROR, "cannot change persistence of mapped relation \"%s\"",
1586 NameStr(relform1->relname));
1587 if (relform1->relam != relform2->relam)
1588 elog(ERROR, "cannot change access method of mapped relation \"%s\"",
1589 NameStr(relform1->relname));
1590 if (!swap_toast_by_content &&
1591 (relform1->reltoastrelid || relform2->reltoastrelid))
1592 elog(ERROR, "cannot swap toast by links for mapped relation \"%s\"",
1593 NameStr(relform1->relname));
1594
1595 /*
1596 * Fetch the mappings --- shouldn't fail, but be paranoid
1597 */
1600 elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
1601 NameStr(relform1->relname), r1);
1604 elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
1605 NameStr(relform2->relname), r2);
1606
1607 /*
1608 * Send replacement mappings to relmapper. Note these won't actually
1609 * take effect until CommandCounterIncrement.
1610 */
1611 RelationMapUpdateMap(r1, relfilenumber2, relform1->relisshared, false);
1612 RelationMapUpdateMap(r2, relfilenumber1, relform2->relisshared, false);
1613
1614 /* Pass OIDs of mapped r2 tables back to caller */
1615 *mapped_tables++ = r2;
1616 }
1617
1618 /*
1619 * Recognize that rel1's relfilenumber (swapped from rel2) is new in this
1620 * subtransaction. The rel2 storage (swapped from rel1) may or may not be
1621 * new.
1622 */
1623 {
1624 Relation rel1,
1625 rel2;
1626
1629 rel2->rd_createSubid = rel1->rd_createSubid;
1630 rel2->rd_newRelfilelocatorSubid = rel1->rd_newRelfilelocatorSubid;
1631 rel2->rd_firstRelfilelocatorSubid = rel1->rd_firstRelfilelocatorSubid;
1635 }
1636
1637 /*
1638 * In the case of a shared catalog, these next few steps will only affect
1639 * our own database's pg_class row; but that's okay, because they are all
1640 * noncritical updates. That's also an important fact for the case of a
1641 * mapped catalog, because it's possible that we'll commit the map change
1642 * and then fail to commit the pg_class update.
1643 */
1644
1645 /* set rel1's frozen Xid and minimum MultiXid */
1646 if (relform1->relkind != RELKIND_INDEX)
1647 {
1650 relform1->relfrozenxid = frozenXid;
1651 relform1->relminmxid = cutoffMulti;
1652 }
1653
1654 /* swap size statistics too, since new rel has freshly-updated stats */
1655 {
1660
1661 swap_pages = relform1->relpages;
1662 relform1->relpages = relform2->relpages;
1663 relform2->relpages = swap_pages;
1664
1665 swap_tuples = relform1->reltuples;
1666 relform1->reltuples = relform2->reltuples;
1667 relform2->reltuples = swap_tuples;
1668
1669 swap_allvisible = relform1->relallvisible;
1670 relform1->relallvisible = relform2->relallvisible;
1671 relform2->relallvisible = swap_allvisible;
1672
1673 swap_allfrozen = relform1->relallfrozen;
1674 relform1->relallfrozen = relform2->relallfrozen;
1675 relform2->relallfrozen = swap_allfrozen;
1676 }
1677
1678 /*
1679 * Update the tuples in pg_class --- unless the target relation of the
1680 * swap is pg_class itself. In that case, there is zero point in making
1681 * changes because we'd be updating the old data that we're about to throw
1682 * away. Because the real work being done here for a mapped relation is
1683 * just to change the relation map settings, it's all right to not update
1684 * the pg_class rows in this case. The most important changes will instead
1685 * performed later, in finish_heap_swap() itself.
1686 */
1687 if (!target_is_pg_class)
1688 {
1690
1693 indstate);
1695 indstate);
1697 }
1698 else
1699 {
1700 /* no update ... but we do still need relcache inval */
1703 }
1704
1705 /*
1706 * Now that pg_class has been updated with its relevant information for
1707 * the swap, update the dependency of the relations to point to their new
1708 * table AM, if it has changed.
1709 */
1710 if (relam1 != relam2)
1711 {
1713 r1,
1715 relam1,
1716 relam2) != 1)
1717 elog(ERROR, "could not change access method dependency for relation \"%s.%s\"",
1719 get_rel_name(r1));
1721 r2,
1723 relam2,
1724 relam1) != 1)
1725 elog(ERROR, "could not change access method dependency for relation \"%s.%s\"",
1727 get_rel_name(r2));
1728 }
1729
1730 /*
1731 * Post alter hook for modified relations. The change to r2 is always
1732 * internal, but r1 depends on the invocation context.
1733 */
1735 InvalidOid, is_internal);
1737 InvalidOid, true);
1738
1739 /*
1740 * If we have toast tables associated with the relations being swapped,
1741 * deal with them too.
1742 */
1743 if (relform1->reltoastrelid || relform2->reltoastrelid)
1744 {
1746 {
1747 if (relform1->reltoastrelid && relform2->reltoastrelid)
1748 {
1749 /* Recursively swap the contents of the toast tables */
1750 swap_relation_files(relform1->reltoastrelid,
1751 relform2->reltoastrelid,
1754 is_internal,
1755 frozenXid,
1758 }
1759 else
1760 {
1761 /* caller messed up */
1762 elog(ERROR, "cannot swap toast files by content when there's only one");
1763 }
1764 }
1765 else
1766 {
1767 /*
1768 * We swapped the ownership links, so we need to change dependency
1769 * data to match.
1770 *
1771 * NOTE: it is possible that only one table has a toast table.
1772 *
1773 * NOTE: at present, a TOAST table's only dependency is the one on
1774 * its owning table. If more are ever created, we'd need to use
1775 * something more selective than deleteDependencyRecordsFor() to
1776 * get rid of just the link we want.
1777 */
1780 long count;
1781
1782 /*
1783 * We disallow this case for system catalogs, to avoid the
1784 * possibility that the catalog we're rebuilding is one of the
1785 * ones the dependency changes would change. It's too late to be
1786 * making any data changes to the target catalog.
1787 */
1789 elog(ERROR, "cannot swap toast files by links for system catalogs");
1790
1791 /* Delete old dependencies */
1792 if (relform1->reltoastrelid)
1793 {
1795 relform1->reltoastrelid,
1796 false);
1797 if (count != 1)
1798 elog(ERROR, "expected one dependency record for TOAST table, found %ld",
1799 count);
1800 }
1801 if (relform2->reltoastrelid)
1802 {
1804 relform2->reltoastrelid,
1805 false);
1806 if (count != 1)
1807 elog(ERROR, "expected one dependency record for TOAST table, found %ld",
1808 count);
1809 }
1810
1811 /* Register new dependencies */
1813 baseobject.objectSubId = 0;
1815 toastobject.objectSubId = 0;
1816
1817 if (relform1->reltoastrelid)
1818 {
1819 baseobject.objectId = r1;
1820 toastobject.objectId = relform1->reltoastrelid;
1823 }
1824
1825 if (relform2->reltoastrelid)
1826 {
1827 baseobject.objectId = r2;
1828 toastobject.objectId = relform2->reltoastrelid;
1831 }
1832 }
1833 }
1834
1835 /*
1836 * If we're swapping two toast tables by content, do the same for their
1837 * valid index. The swap can actually be safely done only if the relations
1838 * have indexes.
1839 */
1841 relform1->relkind == RELKIND_TOASTVALUE &&
1842 relform2->relkind == RELKIND_TOASTVALUE)
1843 {
1846
1847 /* Get valid index for each relation */
1852
1857 is_internal,
1861 }
1862
1863 /* Clean up. */
1866
1868}
1869
1870/*
1871 * Remove the transient table that was built by make_new_heap, and finish
1872 * cleaning up (including rebuilding all indexes on the old heap).
1873 */
1874void
1876 bool is_system_catalog,
1878 bool check_constraints,
1879 bool is_internal,
1880 bool reindex,
1883 char newrelpersistence)
1884{
1885 ObjectAddress object;
1886 Oid mapped_tables[4];
1887 int i;
1888
1889 /* Report that we are now swapping relation files */
1892
1893 /* Zero out possible results from swapped_relation_files */
1894 memset(mapped_tables, 0, sizeof(mapped_tables));
1895
1896 /*
1897 * Swap the contents of the heap relations (including any toast tables).
1898 * Also set old heap's relfrozenxid to frozenXid.
1899 */
1902 swap_toast_by_content, is_internal,
1904
1905 /*
1906 * If it's a system catalog, queue a sinval message to flush all catcaches
1907 * on the catalog when we reach CommandCounterIncrement.
1908 */
1911
1912 if (reindex)
1913 {
1914 int reindex_flags;
1916
1917 /*
1918 * Rebuild each index on the relation (but not the toast table, which
1919 * is all-new at this point). It is important to do this before the
1920 * DROP step because if we are processing a system catalog that will
1921 * be used during DROP, we want to have its indexes available. There
1922 * is no advantage to the other order anyway because this is all
1923 * transactional, so no chance to reclaim disk space before commit. We
1924 * do not need a final CommandCounterIncrement() because
1925 * reindex_relation does it.
1926 *
1927 * Note: because index_build is called via reindex_relation, it will
1928 * never set indcheckxmin true for the indexes. This is OK even
1929 * though in some sense we are building new indexes rather than
1930 * rebuilding existing ones, because the new heap won't contain any
1931 * HOT chains at all, let alone broken ones, so it can't be necessary
1932 * to set indcheckxmin.
1933 */
1937
1938 /*
1939 * Ensure that the indexes have the same persistence as the parent
1940 * relation.
1941 */
1942 if (newrelpersistence == RELPERSISTENCE_UNLOGGED)
1944 else if (newrelpersistence == RELPERSISTENCE_PERMANENT)
1946
1947 /* Report that we are now reindexing relations */
1950
1952 }
1953
1954 /* Report that we are now doing clean up */
1957
1958 /*
1959 * If the relation being rebuilt is pg_class, swap_relation_files()
1960 * couldn't update pg_class's own pg_class entry (check comments in
1961 * swap_relation_files()), thus relfrozenxid was not updated. That's
1962 * annoying because a potential reason for doing a VACUUM FULL is a
1963 * imminent or actual anti-wraparound shutdown. So, now that we can
1964 * access the new relation using its indices, update relfrozenxid.
1965 * pg_class doesn't have a toast relation, so we don't need to update the
1966 * corresponding toast relation. Not that there's little point moving all
1967 * relfrozenxid updates here since swap_relation_files() needs to write to
1968 * pg_class for non-mapped relations anyway.
1969 */
1971 {
1975
1977
1980 elog(ERROR, "cache lookup failed for relation %u", OIDOldHeap);
1982
1983 relform->relfrozenxid = frozenXid;
1984 relform->relminmxid = cutoffMulti;
1985
1987
1989 }
1990
1991 /* Destroy new heap with old filenumber */
1992 object.classId = RelationRelationId;
1993 object.objectId = OIDNewHeap;
1994 object.objectSubId = 0;
1995
1996 if (!reindex)
1997 {
1998 /*
1999 * Make sure the changes in pg_class are visible. This is especially
2000 * important if !swap_toast_by_content, so that the correct TOAST
2001 * relation is dropped. (reindex_relation() above did not help in this
2002 * case))
2003 */
2005 }
2006
2007 /*
2008 * The new relation is local to our transaction and we know nothing
2009 * depends on it, so DROP_RESTRICT should be OK.
2010 */
2012
2013 /* performDeletion does CommandCounterIncrement at end */
2014
2015 /*
2016 * Now we must remove any relation mapping entries that we set up for the
2017 * transient table, as well as its toast table and toast index if any. If
2018 * we fail to do this before commit, the relmapper will complain about new
2019 * permanent map entries being added post-bootstrap.
2020 */
2021 for (i = 0; OidIsValid(mapped_tables[i]); i++)
2023
2024 /*
2025 * At this point, everything is kosher except that, if we did toast swap
2026 * by links, the toast table's name corresponds to the transient table.
2027 * The name is irrelevant to the backend because it's referenced by OID,
2028 * but users looking at the catalogs could be confused. Rename it to
2029 * prevent this problem.
2030 *
2031 * Note no lock required on the relation, because we already hold an
2032 * exclusive lock on it.
2033 */
2035 {
2037
2039 if (OidIsValid(newrel->rd_rel->reltoastrelid))
2040 {
2041 Oid toastidx;
2043
2044 /* Get the associated valid index to be renamed */
2045 toastidx = toast_get_valid_index(newrel->rd_rel->reltoastrelid,
2047
2048 /* rename the toast table ... */
2049 snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u",
2050 OIDOldHeap);
2051 RenameRelationInternal(newrel->rd_rel->reltoastrelid,
2052 NewToastName, true, false);
2053
2054 /* ... and its valid index too. */
2055 snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u_index",
2056 OIDOldHeap);
2057
2059 NewToastName, true, true);
2060
2061 /*
2062 * Reset the relrewrite for the toast. The command-counter
2063 * increment is required here as we are about to update the tuple
2064 * that is updated as part of RenameRelationInternal.
2065 */
2067 ResetRelRewrite(newrel->rd_rel->reltoastrelid);
2068 }
2070 }
2071
2072 /* if it's not a catalog table, clear any missing attribute settings */
2073 if (!is_system_catalog)
2074 {
2076
2080 }
2081}
2082
2083/*
2084 * Determine which relations to process, when REPACK/CLUSTER is called
2085 * without specifying a table name. The exact process depends on whether
2086 * USING INDEX was given or not, and in any case we only return tables and
2087 * materialized views that the current user has privileges to repack/cluster.
2088 *
2089 * If USING INDEX was given, we scan pg_index to find those that have
2090 * indisclustered set; if it was not given, scan pg_class and return all
2091 * tables.
2092 *
2093 * Return it as a list of RelToCluster in the given memory context.
2094 */
2095static List *
2097{
2099 TableScanDesc scan;
2100 HeapTuple tuple;
2101 List *rtcs = NIL;
2102
2103 if (usingindex)
2104 {
2105 ScanKeyData entry;
2106
2107 /*
2108 * For USING INDEX, scan pg_index to find those with indisclustered.
2109 */
2111 ScanKeyInit(&entry,
2114 BoolGetDatum(true));
2115 scan = table_beginscan_catalog(catalog, 1, &entry);
2116 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2117 {
2123
2124 index = (Form_pg_index) GETSTRUCT(tuple);
2125
2126 /*
2127 * Try to obtain a light lock on the index's table, to ensure it
2128 * doesn't go away while we collect the list. If we cannot, just
2129 * disregard it. Be sure to release this if we ultimately decide
2130 * not to process the table!
2131 */
2133 continue;
2134
2135 /* Verify that the table still exists; skip if not */
2138 {
2140 continue;
2141 }
2143
2144 /* Skip temp relations belonging to other sessions */
2145 if (classForm->relpersistence == RELPERSISTENCE_TEMP &&
2146 !isTempOrTempToastNamespace(classForm->relnamespace))
2147 {
2150 continue;
2151 }
2152
2154
2155 /* noisily skip rels which the user can't process */
2156 if (!repack_is_permitted_for_relation(cmd, index->indrelid,
2157 GetUserId()))
2158 {
2160 continue;
2161 }
2162
2163 /* Use a permanent memory context for the result list */
2166 rtc->tableOid = index->indrelid;
2167 rtc->indexOid = index->indexrelid;
2168 rtcs = lappend(rtcs, rtc);
2170 }
2171 }
2172 else
2173 {
2176
2177 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2178 {
2180 Form_pg_class class;
2182
2183 class = (Form_pg_class) GETSTRUCT(tuple);
2184
2185 /*
2186 * Try to obtain a light lock on the table, to ensure it doesn't
2187 * go away while we collect the list. If we cannot, just
2188 * disregard the table. Be sure to release this if we ultimately
2189 * decide not to process the table!
2190 */
2192 continue;
2193
2194 /* Verify that the table still exists */
2196 {
2198 continue;
2199 }
2200
2201 /* Can only process plain tables and matviews */
2202 if (class->relkind != RELKIND_RELATION &&
2203 class->relkind != RELKIND_MATVIEW)
2204 {
2206 continue;
2207 }
2208
2209 /* Skip temp relations belonging to other sessions */
2210 if (class->relpersistence == RELPERSISTENCE_TEMP &&
2211 !isTempOrTempToastNamespace(class->relnamespace))
2212 {
2214 continue;
2215 }
2216
2217 /* noisily skip rels which the user can't process */
2219 GetUserId()))
2220 {
2222 continue;
2223 }
2224
2225 /* Use a permanent memory context for the result list */
2228 rtc->tableOid = class->oid;
2229 rtc->indexOid = InvalidOid;
2230 rtcs = lappend(rtcs, rtc);
2232 }
2233 }
2234
2235 table_endscan(scan);
2237
2238 return rtcs;
2239}
2240
2241/*
2242 * Given a partitioned table or its index, return a list of RelToCluster for
2243 * all the leaf child tables/indexes.
2244 *
2245 * 'rel_is_index' tells whether 'relid' is that of an index (true) or of the
2246 * owning relation.
2247 */
2248static List *
2251{
2252 List *inhoids;
2253 List *rtcs = NIL;
2254
2255 /*
2256 * Do not lock the children until they're processed. Note that we do hold
2257 * a lock on the parent partitioned table.
2258 */
2261 {
2262 Oid table_oid,
2263 index_oid;
2266
2267 if (rel_is_index)
2268 {
2269 /* consider only leaf indexes */
2271 continue;
2272
2275 }
2276 else
2277 {
2278 /* consider only leaf relations */
2280 continue;
2281
2284 }
2285
2286 /*
2287 * It's possible that the user does not have privileges to CLUSTER the
2288 * leaf partition despite having them on the partitioned table. Skip
2289 * if so.
2290 */
2292 continue;
2293
2294 /* Use a permanent memory context for the result list */
2297 rtc->tableOid = table_oid;
2298 rtc->indexOid = index_oid;
2299 rtcs = lappend(rtcs, rtc);
2301 }
2302
2303 return rtcs;
2304}
2305
2306
2307/*
2308 * Return whether userid has privileges to REPACK relid. If not, this
2309 * function emits a WARNING.
2310 */
2311static bool
2313{
2315
2316 if (pg_class_aclcheck(relid, userid, ACL_MAINTAIN) == ACLCHECK_OK)
2317 return true;
2318
2320 errmsg("permission denied to execute %s on \"%s\", skipping it",
2322 get_rel_name(relid)));
2323
2324 return false;
2325}
2326
2327
2328/*
2329 * Given a RepackStmt with an indicated relation name, resolve the relation
2330 * name, obtain lock on it, then determine what to do based on the relation
2331 * type: if it's table and not partitioned, repack it as indicated (using an
2332 * existing clustered index, or following the given one), and return NULL.
2333 *
2334 * On the other hand, if the table is partitioned, do nothing further and
2335 * instead return the opened and locked relcache entry, so that caller can
2336 * process the partitions using the multiple-table handling code. In this
2337 * case, if an index name is given, it's up to the caller to resolve it.
2338 */
2339static Relation
2341 ClusterParams *params)
2342{
2343 Relation rel;
2344 Oid tableOid;
2345
2346 Assert(stmt->relation != NULL);
2347 Assert(stmt->command == REPACK_COMMAND_CLUSTER ||
2348 stmt->command == REPACK_COMMAND_REPACK);
2349
2350 /*
2351 * Make sure ANALYZE is specified if a column list is present.
2352 */
2353 if ((params->options & CLUOPT_ANALYZE) == 0 && stmt->relation->va_cols != NIL)
2354 ereport(ERROR,
2356 errmsg("ANALYZE option must be specified when a column list is provided"));
2357
2358 /* Find, lock, and check permissions on the table. */
2359 tableOid = RangeVarGetRelidExtended(stmt->relation->relation,
2360 lockmode,
2361 0,
2363 NULL);
2364 rel = table_open(tableOid, NoLock);
2365
2366 /*
2367 * Reject clustering a remote temp table ... their local buffer manager is
2368 * not going to cope.
2369 */
2370 if (RELATION_IS_OTHER_TEMP(rel))
2371 ereport(ERROR,
2373 /*- translator: first %s is name of a SQL command, eg. REPACK */
2374 errmsg("cannot execute %s on temporary tables of other sessions",
2375 RepackCommandAsString(stmt->command)));
2376
2377 /*
2378 * For partitioned tables, let caller handle this. Otherwise, process it
2379 * here and we're done.
2380 */
2381 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2382 return rel;
2383 else
2384 {
2385 Oid indexOid = InvalidOid;
2386
2387 indexOid = determine_clustered_index(rel, stmt->usingindex,
2388 stmt->indexname);
2389 if (OidIsValid(indexOid))
2390 check_index_is_clusterable(rel, indexOid, lockmode);
2391
2392 cluster_rel(stmt->command, rel, indexOid, params, isTopLevel);
2393
2394 /*
2395 * Do an analyze, if requested. We close the transaction and start a
2396 * new one, so that we don't hold the stronger lock for longer than
2397 * needed.
2398 */
2399 if (params->options & CLUOPT_ANALYZE)
2400 {
2402
2405
2408
2409 vac_params.options |= VACOPT_ANALYZE;
2410 if (params->options & CLUOPT_VERBOSE)
2411 vac_params.options |= VACOPT_VERBOSE;
2412 analyze_rel(tableOid, NULL, &vac_params,
2413 stmt->relation->va_cols, true, NULL);
2416 }
2417
2418 return NULL;
2419 }
2420}
2421
2422/*
2423 * Given a relation and the usingindex/indexname options in a
2424 * REPACK USING INDEX or CLUSTER command, return the OID of the
2425 * index to use for clustering the table.
2426 *
2427 * Caller must hold lock on the relation so that the set of indexes
2428 * doesn't change, and must call check_index_is_clusterable.
2429 */
2430static Oid
2431determine_clustered_index(Relation rel, bool usingindex, const char *indexname)
2432{
2433 Oid indexOid;
2434
2435 if (indexname == NULL && usingindex)
2436 {
2437 /*
2438 * If USING INDEX with no name is given, find a clustered index, or
2439 * error out if none.
2440 */
2441 indexOid = InvalidOid;
2443 {
2445 {
2446 indexOid = idxoid;
2447 break;
2448 }
2449 }
2450
2451 if (!OidIsValid(indexOid))
2452 ereport(ERROR,
2454 errmsg("there is no previously clustered index for table \"%s\"",
2456 }
2457 else if (indexname != NULL)
2458 {
2459 /* An index was specified; obtain its OID. */
2460 indexOid = get_relname_relid(indexname, rel->rd_rel->relnamespace);
2461 if (!OidIsValid(indexOid))
2462 ereport(ERROR,
2464 errmsg("index \"%s\" for table \"%s\" does not exist",
2465 indexname, RelationGetRelationName(rel)));
2466 }
2467 else
2468 indexOid = InvalidOid;
2469
2470 return indexOid;
2471}
2472
2473static const char *
2475{
2476 switch (cmd)
2477 {
2479 return "REPACK";
2481 return "VACUUM";
2483 return "CLUSTER";
2484 }
2485 return "???"; /* keep compiler quiet */
2486}
2487
2488/*
2489 * Apply all the changes stored in 'file'.
2490 */
2491static void
2493{
2494 ConcurrentChangeKind kind = '\0';
2495 Relation rel = chgcxt->cc_rel;
2499 bool have_old_tuple = false;
2501
2503 &TTSOpsVirtual);
2507 &TTSOpsVirtual);
2508
2510
2511 while (true)
2512 {
2513 size_t nread;
2515
2517
2518 nread = BufFileReadMaybeEOF(file, &kind, 1, true);
2519 if (nread == 0) /* done with the file? */
2520 break;
2521
2522 /*
2523 * If this is the old tuple for an update, read it into the tuple slot
2524 * and go to the next one. The update itself will be executed on the
2525 * next iteration, when we receive the NEW tuple.
2526 */
2527 if (kind == CHANGE_UPDATE_OLD)
2528 {
2529 restore_tuple(file, rel, old_update_tuple);
2530 have_old_tuple = true;
2531 continue;
2532 }
2533
2534 /*
2535 * Just before an UPDATE or DELETE, we must update the command
2536 * counter, because the change could refer to a tuple that we have
2537 * just inserted; and before an INSERT, we have to do this also if the
2538 * previous command was either update or delete.
2539 *
2540 * With this approach we don't spend so many CCIs for long strings of
2541 * only INSERTs, which can't affect one another.
2542 */
2543 if (kind == CHANGE_UPDATE_NEW || kind == CHANGE_DELETE ||
2544 (kind == CHANGE_INSERT && (prevkind == CHANGE_UPDATE_NEW ||
2546 {
2549 }
2550
2551 /*
2552 * Now restore the tuple into the slot and execute the change.
2553 */
2554 restore_tuple(file, rel, spilled_tuple);
2555
2556 if (kind == CHANGE_INSERT)
2557 {
2559 }
2560 else if (kind == CHANGE_DELETE)
2561 {
2562 bool found;
2563
2564 /* Find the tuple to be deleted */
2566 if (!found)
2567 elog(ERROR, "failed to find target tuple");
2569 }
2570 else if (kind == CHANGE_UPDATE_NEW)
2571 {
2572 TupleTableSlot *key;
2573 bool found;
2574
2575 if (have_old_tuple)
2576 key = old_update_tuple;
2577 else
2578 key = spilled_tuple;
2579
2580 /* Find the tuple to be updated or deleted. */
2581 found = find_target_tuple(rel, chgcxt, key, ondisk_tuple);
2582 if (!found)
2583 elog(ERROR, "failed to find target tuple");
2584
2585 /*
2586 * If 'tup' contains TOAST pointers, they point to the old
2587 * relation's toast. Copy the corresponding TOAST pointers for the
2588 * new relation from the existing tuple. (The fact that we
2589 * received a TOAST pointer here implies that the attribute hasn't
2590 * changed.)
2591 */
2593
2595
2597 have_old_tuple = false;
2598 }
2599 else
2600 elog(ERROR, "unrecognized kind of change: %d", kind);
2601
2602 ResetPerTupleExprContext(chgcxt->cc_estate);
2603 }
2604
2605 /* Cleanup. */
2609
2611}
2612
2613/*
2614 * Apply an insert from the spill of concurrent changes to the new copy of the
2615 * table.
2616 */
2617static void
2620{
2621 /* Put the tuple in the table, but make sure it won't be decoded */
2622 table_tuple_insert(rel, slot, GetCurrentCommandId(true),
2624
2625 /* Update indexes with this new tuple. */
2627 chgcxt->cc_estate,
2628 0,
2629 slot,
2630 NIL, NULL);
2632}
2633
2634/*
2635 * Apply an update from the spill of concurrent changes to the new copy of the
2636 * table.
2637 */
2638static void
2642{
2643 LockTupleMode lockmode;
2644 TM_FailureData tmfd;
2646 TM_Result res;
2647
2648 /*
2649 * Carry out the update, skipping logical decoding for it.
2650 */
2651 res = table_tuple_update(rel, &(ondisk_tuple->tts_tid), spilled_tuple,
2652 GetCurrentCommandId(true),
2656 false,
2657 &tmfd, &lockmode, &update_indexes);
2658 if (res != TM_Ok)
2659 ereport(ERROR,
2660 errmsg("failed to apply concurrent UPDATE"));
2661
2662 if (update_indexes != TU_None)
2663 {
2664 uint32 flags = EIIT_IS_UPDATE;
2665
2667 flags |= EIIT_ONLY_SUMMARIZING;
2669 chgcxt->cc_estate,
2670 flags,
2672 NIL, NULL);
2673 }
2674
2676}
2677
2678static void
2680{
2681 TM_Result res;
2682 TM_FailureData tmfd;
2683
2684 /*
2685 * Delete tuple from the new heap, skipping logical decoding for it.
2686 */
2687 res = table_tuple_delete(rel, &(slot->tts_tid),
2688 GetCurrentCommandId(true),
2691 false,
2692 &tmfd);
2693
2694 if (res != TM_Ok)
2695 ereport(ERROR,
2696 errmsg("failed to apply concurrent DELETE"));
2697
2699}
2700
2701/*
2702 * Read tuple from file and put it in the input slot. All memory is allocated
2703 * in the current memory context; caller is responsible for freeing it as
2704 * appropriate.
2705 *
2706 * External attributes are stored in separate memory chunks, in order to avoid
2707 * exceeding MaxAllocSize - that could happen if the individual attributes are
2708 * smaller than MaxAllocSize but the whole tuple is bigger.
2709 */
2710static void
2712{
2713 uint32 t_len;
2714 HeapTuple tup;
2715 int natt_ext;
2716
2717 /* Read the tuple. */
2718 BufFileReadExact(file, &t_len, sizeof(t_len));
2719 tup = (HeapTuple) palloc(HEAPTUPLESIZE + t_len);
2720 tup->t_data = (HeapTupleHeader) ((char *) tup + HEAPTUPLESIZE);
2721 BufFileReadExact(file, tup->t_data, t_len);
2722 tup->t_len = t_len;
2723 ItemPointerSetInvalid(&tup->t_self);
2724 tup->t_tableOid = RelationGetRelid(relation);
2725
2726 /*
2727 * Put the tuple we read in a slot. This deforms it, so that we can hack
2728 * the external attributes in place.
2729 */
2730 ExecForceStoreHeapTuple(tup, slot, false);
2731
2732 /*
2733 * Next, read any attributes we stored separately into the tts_values
2734 * array elements expecting them, if any. This matches
2735 * repack_store_change.
2736 */
2737 BufFileReadExact(file, &natt_ext, sizeof(natt_ext));
2738 if (natt_ext > 0)
2739 {
2740 TupleDesc desc = slot->tts_tupleDescriptor;
2741
2742 for (int i = 0; i < desc->natts; i++)
2743 {
2745 varlena *varlen;
2747 void *value;
2748 Size varlensz;
2749
2750 if (attr->attisdropped || attr->attlen != -1)
2751 continue;
2752 if (slot_attisnull(slot, i + 1))
2753 continue;
2756 continue;
2757 slot_getsomeattrs(slot, i + 1);
2758
2761
2764 BufFileReadExact(file, (char *) value + VARHDRSZ, varlensz - VARHDRSZ);
2765
2767 natt_ext--;
2768 if (natt_ext < 0)
2769 ereport(ERROR,
2771 errmsg("insufficient number of attributes stored separately"));
2772 }
2773 }
2774}
2775
2776/*
2777 * Adjust 'dest' replacing any EXTERNAL_ONDISK toast pointers with the
2778 * corresponding ones from 'src'.
2779 */
2780static void
2782{
2783 TupleDesc desc = dest->tts_tupleDescriptor;
2784
2785 for (int i = 0; i < desc->natts; i++)
2786 {
2789
2790 if (attr->attisdropped)
2791 continue;
2792 if (attr->attlen != -1)
2793 continue;
2794 if (slot_attisnull(dest, i + 1))
2795 continue;
2796
2797 slot_getsomeattrs(dest, i + 1);
2798
2799 varlena_dst = (varlena *) DatumGetPointer(dest->tts_values[i]);
2801 continue;
2802 slot_getsomeattrs(src, i + 1);
2803
2804 dest->tts_values[i] = src->tts_values[i];
2805 }
2806}
2807
2808/*
2809 * Find the tuple to be updated or deleted by the given data change, whose
2810 * tuple has already been loaded into locator.
2811 *
2812 * If the tuple is found, put it in retrieved and return true. If the tuple is
2813 * not found, return false.
2814 */
2815static bool
2818{
2819 Form_pg_index idx = chgcxt->cc_ident_index->rd_index;
2820 IndexScanDesc scan;
2821 bool retval = false;
2822
2823 /*
2824 * Scan key is passed by caller, so it does not have to be constructed
2825 * multiple times. Key entries have all fields initialized, except for
2826 * sk_argument.
2827 *
2828 * Use the incoming tuple to finalize the scan key.
2829 */
2830 for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
2831 {
2832 ScanKey entry = &chgcxt->cc_ident_key[i];
2833 AttrNumber attno = idx->indkey.values[i];
2834
2835 entry->sk_argument = locator->tts_values[attno - 1];
2836 Assert(!locator->tts_isnull[attno - 1]);
2837 }
2838
2839 /* XXX no instrumentation for now */
2840 scan = index_beginscan(rel, chgcxt->cc_ident_index, GetActiveSnapshot(),
2841 NULL, chgcxt->cc_ident_key_nentries, 0, 0);
2842 index_rescan(scan, chgcxt->cc_ident_key, chgcxt->cc_ident_key_nentries, NULL, 0);
2844 {
2845 /* Be wary of temporal constraints */
2846 if (scan->xs_recheck && !identity_key_equal(chgcxt, locator, retrieved))
2847 {
2849 continue;
2850 }
2851
2852 retval = true;
2853 break;
2854 }
2855 index_endscan(scan);
2856
2857 return retval;
2858}
2859
2860/*
2861 * Check whether the candidate tuple matches the locator tuple on all replica
2862 * identity key columns, using the same equality operators as the identity
2863 * index scan. The locator tuple has already been loaded into cc_ident_key.
2864 *
2865 * This is needed to filter lossy index matches, such as GiST multirange scans
2866 * used for temporal constraints.
2867 */
2868static bool
2871{
2872 slot_getsomeattrs(locator, chgcxt->cc_last_key_attno);
2873 slot_getsomeattrs(candidate, chgcxt->cc_last_key_attno);
2874
2875 for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
2876 {
2877 ScanKey entry = &chgcxt->cc_ident_key[i];
2878 AttrNumber attno = chgcxt->cc_ident_index->rd_index->indkey.values[i];
2879
2880 Assert(attno > 0);
2881
2882 if (locator->tts_isnull[attno - 1] != candidate->tts_isnull[attno - 1])
2883 return false;
2884
2885 if (locator->tts_isnull[attno - 1])
2886 continue;
2887
2889 entry->sk_collation,
2890 candidate->tts_values[attno - 1],
2891 entry->sk_argument)))
2892 return false;
2893 }
2894
2895 return true;
2896}
2897
2898/*
2899 * Decode and apply concurrent changes, up to (and including) the record whose
2900 * LSN is 'end_of_wal'.
2901 *
2902 * XXX the names "process_concurrent_changes" and "apply_concurrent_changes"
2903 * are far too similar to each other.
2904 */
2905static void
2907{
2908 DecodingWorkerShared *shared;
2909 char fname[MAXPGPATH];
2910 BufFile *file;
2911
2914
2915 /* Ask the worker for the file. */
2917 SpinLockAcquire(&shared->mutex);
2918 shared->lsn_upto = end_of_wal;
2919 shared->done = done;
2920 SpinLockRelease(&shared->mutex);
2921
2922 /*
2923 * The worker needs to finish processing of the current WAL record. Even
2924 * if it's idle, it'll need to close the output file. Thus we're likely to
2925 * wait, so prepare for sleep.
2926 */
2928 for (;;)
2929 {
2930 int last_exported;
2931
2932 SpinLockAcquire(&shared->mutex);
2933 last_exported = shared->last_exported;
2934 SpinLockRelease(&shared->mutex);
2935
2936 /*
2937 * Has the worker exported the file we are waiting for?
2938 */
2939 if (last_exported == chgcxt->cc_file_seq)
2940 break;
2941
2943 }
2945
2946 /* Open the file. */
2947 DecodingWorkerFileName(fname, shared->relid, chgcxt->cc_file_seq);
2948 file = BufFileOpenFileSet(&shared->sfs.fs, fname, O_RDONLY, false);
2950
2951 BufFileClose(file);
2952
2953 /* Get ready for the next file. */
2954 chgcxt->cc_file_seq++;
2955}
2956
2957/*
2958 * Initialize the ChangeContext struct for the given relation, with
2959 * the given index as identity index.
2960 */
2961static void
2963 Relation relation, Oid ident_index_id)
2964{
2965 chgcxt->cc_rel = relation;
2966
2967 /* Only initialize fields needed by ExecInsertIndexTuples(). */
2968 chgcxt->cc_estate = CreateExecutorState();
2969
2970 chgcxt->cc_rri = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
2971 InitResultRelInfo(chgcxt->cc_rri, relation, 0, 0, 0);
2972 ExecOpenIndices(chgcxt->cc_rri, false);
2973
2974 /*
2975 * The table's relcache entry already has the relcache entry for the
2976 * identity index; find that.
2977 */
2978 chgcxt->cc_ident_index = NULL;
2979 for (int i = 0; i < chgcxt->cc_rri->ri_NumIndices; i++)
2980 {
2982
2983 ind_rel = chgcxt->cc_rri->ri_IndexRelationDescs[i];
2984 if (ind_rel->rd_id == ident_index_id)
2985 {
2986 chgcxt->cc_ident_index = ind_rel;
2987 break;
2988 }
2989 }
2990 if (chgcxt->cc_ident_index == NULL)
2991 elog(ERROR, "failed to find identity index");
2992
2993 /* Set up for scanning said identity index */
2994 {
2996
2997 indexForm = chgcxt->cc_ident_index->rd_index;
2998 chgcxt->cc_ident_key_nentries = indexForm->indnkeyatts;
2999 chgcxt->cc_ident_key = (ScanKey) palloc_array(ScanKeyData, indexForm->indnkeyatts);
3000 for (int i = 0; i < indexForm->indnkeyatts; i++)
3001 {
3002 ScanKey entry;
3003 Oid opfamily,
3004 opcintype,
3005 opno,
3006 opcode;
3008
3009 entry = &chgcxt->cc_ident_key[i];
3010
3011 opfamily = chgcxt->cc_ident_index->rd_opfamily[i];
3012 opcintype = chgcxt->cc_ident_index->rd_opcintype[i];
3014 chgcxt->cc_ident_index->rd_rel->relam,
3015 opfamily, false);
3017 elog(ERROR, "could not find equality strategy for index operator family %u for type %u",
3018 opfamily, opcintype);
3019 opno = get_opfamily_member(opfamily, opcintype, opcintype,
3020 eq_strategy);
3021 if (!OidIsValid(opno))
3022 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3023 eq_strategy, opcintype, opcintype, opfamily);
3024 opcode = get_opcode(opno);
3025 if (!OidIsValid(opcode))
3026 elog(ERROR, "missing oprcode for operator %u", opno);
3027
3028 /* Initialize everything but argument. */
3029 ScanKeyInit(entry,
3030 i + 1,
3031 eq_strategy, opcode,
3032 (Datum) 0);
3033 entry->sk_collation = chgcxt->cc_ident_index->rd_indcollation[i];
3034 }
3035 }
3036
3037 /* Determine the last column we must deform to read the identity */
3038 chgcxt->cc_last_key_attno = InvalidAttrNumber;
3039 for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
3040 {
3041 AttrNumber attno = chgcxt->cc_ident_index->rd_index->indkey.values[i];
3042
3043 Assert(attno > 0);
3044 chgcxt->cc_last_key_attno = Max(chgcxt->cc_last_key_attno, attno);
3045 }
3046
3047 chgcxt->cc_file_seq = WORKER_FILE_SNAPSHOT + 1;
3048}
3049
3050/*
3051 * Free up resources taken by a ChangeContext.
3052 */
3053static void
3055{
3056 ExecCloseIndices(chgcxt->cc_rri);
3057 FreeExecutorState(chgcxt->cc_estate);
3058 /* XXX are these pfrees necessary? */
3059 pfree(chgcxt->cc_rri);
3060 pfree(chgcxt->cc_ident_key);
3061}
3062
3063/*
3064 * The final steps of rebuild_relation() for concurrent processing.
3065 *
3066 * On entry, NewHeap is locked in AccessExclusiveLock mode. OldHeap and its
3067 * clustering index (if one is passed) are still locked in a mode that allows
3068 * concurrent data changes. On exit, both tables and their indexes are closed,
3069 * but locked in AccessExclusiveLock mode.
3070 */
3071static void
3075{
3080 ListCell *lc,
3081 *lc2;
3082 char relpersistence;
3083 bool is_system_catalog;
3085 XLogRecPtr end_of_wal;
3086 List *indexrels;
3088
3091
3092 /*
3093 * Unlike the exclusive case, we build new indexes for the new relation
3094 * rather than swapping the storage and reindexing the old relation. The
3095 * point is that the index build can take some time, so we do it before we
3096 * get AccessExclusiveLock on the old heap and therefore we cannot swap
3097 * the heap storage yet.
3098 *
3099 * index_create() will lock the new indexes using AccessExclusiveLock - no
3100 * need to change that. At the same time, we use ShareUpdateExclusiveLock
3101 * to lock the existing indexes - that should be enough to prevent others
3102 * from changing them while we're repacking the relation. The lock on
3103 * table should prevent others from changing the index column list, but
3104 * might not be enough for commands like ALTER INDEX ... SET ... (Those
3105 * are not necessarily dangerous, but can make user confused if the
3106 * changes they do get lost due to REPACK.)
3107 */
3109
3110 /*
3111 * The identity index in the new relation appears in the same relative
3112 * position as the corresponding index in the old relation. Find it.
3113 */
3116 {
3117 if (identIdx == ind_old)
3118 {
3119 int pos = foreach_current_index(ind_old);
3120
3121 if (list_length(ind_oids_new) <= pos)
3122 elog(ERROR, "list of new indexes too short");
3124 break;
3125 }
3126 }
3128 elog(ERROR, "could not find index matching \"%s\" at the new relation",
3130
3131 /* Gather information to apply concurrent changes. */
3133
3134 /*
3135 * During testing, wait for another backend to perform concurrent data
3136 * changes which we will process below.
3137 */
3138 INJECTION_POINT("repack-concurrently-before-lock", NULL);
3139
3140 /*
3141 * Flush all WAL records inserted so far (possibly except for the last
3142 * incomplete page; see GetInsertRecPtr), to minimize the amount of data
3143 * we need to flush while holding exclusive lock on the source table.
3144 */
3146 end_of_wal = GetFlushRecPtr(NULL);
3147
3148 /*
3149 * Apply concurrent changes first time, to minimize the time we need to
3150 * hold AccessExclusiveLock. (Quite some amount of WAL could have been
3151 * written during the data copying and index creation.)
3152 */
3153 process_concurrent_changes(end_of_wal, &chgcxt, false);
3154
3155 /*
3156 * Acquire AccessExclusiveLock on the table, its TOAST relation (if there
3157 * is one), all its indexes, so that we can swap the files.
3158 */
3160
3161 /*
3162 * Lock all indexes now, not only the clustering one: all indexes need to
3163 * have their files swapped. While doing that, store their relation
3164 * references in a zero-terminated array, to handle predicate locks below.
3165 */
3166 indexrels = NIL;
3168 {
3170
3172
3173 /*
3174 * Some things about the index may have changed before we locked the
3175 * index, such as ALTER INDEX RENAME. We don't need to do anything
3176 * here to absorb those changes in the new index.
3177 */
3179 }
3180
3181 /*
3182 * Lock the OldHeap's TOAST relation exclusively - again, the lock is
3183 * needed to swap the files.
3184 */
3185 if (OidIsValid(OldHeap->rd_rel->reltoastrelid))
3186 LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
3187
3188 /*
3189 * Tuples and pages of the old heap will be gone, but the heap will stay.
3190 */
3193 {
3196 }
3198
3199 /*
3200 * Flush WAL again, to make sure that all changes committed while we were
3201 * waiting for the exclusive lock are available for decoding.
3202 */
3204 end_of_wal = GetFlushRecPtr(NULL);
3205
3206 /*
3207 * Apply the concurrent changes again. Indicate that the decoding worker
3208 * won't be needed anymore.
3209 */
3210 process_concurrent_changes(end_of_wal, &chgcxt, true);
3211
3212 /* Remember info about rel before closing OldHeap */
3213 relpersistence = OldHeap->rd_rel->relpersistence;
3215
3218
3219 /*
3220 * Even ShareUpdateExclusiveLock should have prevented others from
3221 * creating / dropping indexes (even using the CONCURRENTLY option), so we
3222 * do not need to check whether the lists match.
3223 */
3225 {
3228 Oid mapped_tables[4] = {0};
3229
3232 false, /* swap_toast_by_content */
3233 true,
3237
3238#ifdef USE_ASSERT_CHECKING
3239
3240 /*
3241 * Concurrent processing is not supported for system relations, so
3242 * there should be no mapped tables.
3243 */
3244 for (int i = 0; i < 4; i++)
3246#endif
3247 }
3248
3249 /* The new indexes must be visible for deletion. */
3251
3252 /* Close the old heap but keep lock until transaction commit. */
3254 /* Close the new heap. (We didn't have to open its indexes). */
3256
3257 /* Cleanup what we don't need anymore. (And close the identity index.) */
3259
3260 /*
3261 * Swap the relations and their TOAST relations and TOAST indexes. This
3262 * also drops the new relation and its indexes.
3263 *
3264 * (System catalogs are currently not supported.)
3265 */
3269 false, /* swap_toast_by_content */
3270 false,
3271 true,
3272 false, /* reindex */
3274 relpersistence);
3275}
3276
3277/*
3278 * Build indexes on NewHeap according to those on OldHeap.
3279 *
3280 * OldIndexes is the list of index OIDs on OldHeap. The contained indexes end
3281 * up locked using ShareUpdateExclusiveLock.
3282 *
3283 * A list of OIDs of the corresponding indexes created on NewHeap is
3284 * returned. The order of items does match, so we can use these arrays to swap
3285 * index storage.
3286 */
3287static List *
3319
3320/*
3321 * Create a transient copy of a constraint -- supported by a transient
3322 * copy of the index that supports the original constraint.
3323 *
3324 * When repacking a table that contains exclusion constraints, the executor
3325 * relies on these constraints being properly catalogued. These copies are
3326 * to support that.
3327 *
3328 * We don't need the constraints for anything else (the original constraints
3329 * will be there once repack completes), so we add pg_depend entries so that
3330 * the are dropped when the transient table is dropped.
3331 */
3332static void
3334{
3336 Relation rel;
3337 TupleDesc desc;
3338 SysScanDesc scan;
3339 HeapTuple tup;
3341
3344
3345 /*
3346 * Retrieve the constraints supported by the old index and create an
3347 * identical one that points to the new index.
3348 */
3352 ObjectIdGetDatum(old_index->rd_index->indrelid));
3354 NULL, 1, &skey);
3355 desc = RelationGetDescr(rel);
3356 while (HeapTupleIsValid(tup = systable_getnext(scan)))
3357 {
3359 Oid oid;
3361 bool nulls[Natts_pg_constraint] = {0};
3362 bool replaces[Natts_pg_constraint] = {0};
3365
3366 if (conform->conindid != RelationGetRelid(old_index))
3367 continue;
3368
3372 replaces[Anum_pg_constraint_oid - 1] = true;
3377
3378 new_tup = heap_modify_tuple(tup, desc, values, nulls, replaces);
3379
3380 /* Insert it into the catalog. */
3382
3383 /* Create a dependency so it's removed when we drop the new heap. */
3386 }
3387 systable_endscan(scan);
3388
3390
3392}
3393
3394/*
3395 * Try to start a background worker to perform logical decoding of data
3396 * changes applied to relation while REPACK CONCURRENTLY is copying its
3397 * contents to a new table.
3398 */
3399static void
3401{
3402 Size size;
3403 dsm_segment *seg;
3404 DecodingWorkerShared *shared;
3405 shm_mq *mq;
3408
3409 /* Setup shared memory. */
3410 size = BUFFERALIGN(offsetof(DecodingWorkerShared, error_queue)) +
3412 seg = dsm_create(size, 0);
3413 shared = (DecodingWorkerShared *) dsm_segment_address(seg);
3414 shared->initialized = false;
3415 shared->lsn_upto = InvalidXLogRecPtr;
3416 shared->done = false;
3417 SharedFileSetInit(&shared->sfs, seg);
3418 shared->last_exported = -1;
3419 SpinLockInit(&shared->mutex);
3420 shared->dbid = MyDatabaseId;
3421
3422 /*
3423 * This is the UserId set in cluster_rel(). Security context shouldn't be
3424 * needed for decoding worker.
3425 */
3426 shared->roleid = GetUserId();
3427 shared->relid = relid;
3428 ConditionVariableInit(&shared->cv);
3429 shared->backend_proc = MyProc;
3430 shared->backend_pid = MyProcPid;
3432
3433 mq = shm_mq_create((char *) BUFFERALIGN(shared->error_queue),
3436 mqh = shm_mq_attach(mq, seg, NULL);
3437
3438 memset(&bgw, 0, sizeof(bgw));
3439 snprintf(bgw.bgw_name, BGW_MAXLEN,
3440 "REPACK decoding worker for relation \"%s\"",
3441 get_rel_name(relid));
3442 snprintf(bgw.bgw_type, BGW_MAXLEN, "REPACK decoding worker");
3443 bgw.bgw_flags = BGWORKER_SHMEM_ACCESS |
3445 bgw.bgw_start_time = BgWorkerStart_RecoveryFinished;
3446 bgw.bgw_restart_time = BGW_NEVER_RESTART;
3447 snprintf(bgw.bgw_library_name, MAXPGPATH, "postgres");
3448 snprintf(bgw.bgw_function_name, BGW_MAXLEN, "RepackWorkerMain");
3449 bgw.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(seg));
3450 bgw.bgw_notify_pid = MyProcPid;
3451
3454 ereport(ERROR,
3456 errmsg("out of background worker slots"),
3457 errhint("You might need to increase \"%s\".", "max_worker_processes"));
3458
3459 decoding_worker->seg = seg;
3461
3462 /*
3463 * The decoding setup must be done before the caller can have XID assigned
3464 * for any reason, otherwise the worker might end up in a deadlock,
3465 * waiting for the caller's transaction to end. Therefore wait here until
3466 * the worker indicates that it has the logical decoding initialized.
3467 */
3469 for (;;)
3470 {
3471 bool initialized;
3472
3473 SpinLockAcquire(&shared->mutex);
3474 initialized = shared->initialized;
3475 SpinLockRelease(&shared->mutex);
3476
3477 if (initialized)
3478 break;
3479
3481 }
3483}
3484
3485/*
3486 * Stop the decoding worker and cleanup the related resources.
3487 *
3488 * The worker stops on its own when it knows there is no more work to do, but
3489 * we need to stop it explicitly at least on ERROR in the launching backend.
3490 */
3491static void
3493{
3494 BgwHandleStatus status;
3495
3496 /* Haven't reached the worker startup? */
3497 if (decoding_worker == NULL)
3498 return;
3499
3500 /* Could not register the worker? */
3501 if (decoding_worker->handle == NULL)
3502 return;
3503
3505 /* The worker should really exit before the REPACK command does. */
3509
3510 if (status == BGWH_POSTMASTER_DIED)
3511 ereport(FATAL,
3513 errmsg("postmaster exited during REPACK command"));
3514
3516
3517 /*
3518 * If we could not cancel the current sleep due to ERROR, do that before
3519 * we detach from the shared memory the condition variable is located in.
3520 * If we did not, the bgworker ERROR handling code would try and fail
3521 * badly.
3522 */
3524
3528}
3529
3530/*
3531 * Get the initial snapshot from the decoding worker.
3532 */
3533static Snapshot
3535{
3536 DecodingWorkerShared *shared;
3537 char fname[MAXPGPATH];
3538 BufFile *file;
3540 char *snap_space;
3541 Snapshot snapshot;
3542
3543 shared = (DecodingWorkerShared *) dsm_segment_address(worker->seg);
3544
3545 /*
3546 * The worker needs to initialize the logical decoding, which usually
3547 * takes some time. Therefore it makes sense to prepare for the sleep
3548 * first.
3549 */
3551 for (;;)
3552 {
3553 int last_exported;
3554
3555 SpinLockAcquire(&shared->mutex);
3556 last_exported = shared->last_exported;
3557 SpinLockRelease(&shared->mutex);
3558
3559 /*
3560 * Has the worker exported the file we are waiting for?
3561 */
3562 if (last_exported == WORKER_FILE_SNAPSHOT)
3563 break;
3564
3566 }
3568
3569 /* Read the snapshot from a file. */
3571 file = BufFileOpenFileSet(&shared->sfs.fs, fname, O_RDONLY, false);
3572 BufFileReadExact(file, &snap_size, sizeof(snap_size));
3573 snap_space = (char *) palloc(snap_size);
3575 BufFileClose(file);
3576
3577 /* Restore it. */
3578 snapshot = RestoreSnapshot(snap_space);
3580
3581 return snapshot;
3582}
3583
3584/*
3585 * Generate worker's file name into 'fname', which must be of size MAXPGPATH.
3586 * If relations of the same 'relid' happen to be processed at the same time,
3587 * they must be from different databases and therefore different backends must
3588 * be involved.
3589 */
3590void
3592{
3593 /* The PID is already present in the fileset name, so we needn't add it */
3594 snprintf(fname, MAXPGPATH, "%u-%u", relid, seq);
3595}
3596
3597/*
3598 * Handle receipt of an interrupt indicating a repack worker message.
3599 *
3600 * Note: this is called within a signal handler! All we can do is set
3601 * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
3602 * ProcessRepackMessages().
3603 */
3604void
3606{
3607 InterruptPending = true;
3608 RepackMessagePending = true;
3610}
3611
3612/*
3613 * Process any queued protocol messages received from the repack worker.
3614 */
3615void
3617{
3618 MemoryContext oldcontext;
3620
3621 /*
3622 * Nothing to do if we haven't launched the worker yet or have already
3623 * terminated it.
3624 */
3625 if (decoding_worker == NULL)
3626 return;
3627
3628 /*
3629 * This is invoked from ProcessInterrupts(), and since some of the
3630 * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
3631 * for recursive calls if more signals are received while this runs. It's
3632 * unclear that recursive entry would be safe, and it doesn't seem useful
3633 * even if it is safe, so let's block interrupts until done.
3634 */
3636
3637 /*
3638 * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
3639 * don't want to risk leaking data into long-lived contexts, so let's do
3640 * our work here in a private context that we can reset on each use.
3641 */
3642 if (hpm_context == NULL) /* first time through? */
3644 "ProcessRepackMessages",
3646 else
3648
3649 oldcontext = MemoryContextSwitchTo(hpm_context);
3650
3651 /* OK to process messages. Reset the flag saying there are more to do. */
3652 RepackMessagePending = false;
3653
3654 /*
3655 * Read as many messages as we can from the worker, but stop when no more
3656 * messages can be read from the worker without blocking.
3657 */
3658 while (true)
3659 {
3660 shm_mq_result res;
3661 Size nbytes;
3662 void *data;
3663
3665 &data, true);
3666 if (res == SHM_MQ_WOULD_BLOCK)
3667 break;
3668 else if (res == SHM_MQ_SUCCESS)
3669 {
3670 StringInfoData msg;
3671
3672 initStringInfo(&msg);
3673 appendBinaryStringInfo(&msg, data, nbytes);
3675 pfree(msg.data);
3676 }
3677 else
3678 {
3679 /*
3680 * The decoding worker is special in that it exits as soon as it
3681 * has its work done. Thus the DETACHED result code is fine.
3682 */
3683 Assert(res == SHM_MQ_DETACHED);
3684
3685 break;
3686 }
3687 }
3688
3689 MemoryContextSwitchTo(oldcontext);
3690
3691 /* Might as well clear the context on our way out */
3693
3695}
3696
3697/*
3698 * Process a single protocol message received from a single parallel worker.
3699 */
3700static void
3702{
3703 char msgtype;
3704
3705 msgtype = pq_getmsgbyte(msg);
3706
3707 switch (msgtype)
3708 {
3711 {
3713
3714 /* Parse ErrorResponse or NoticeResponse. */
3716
3717 /* Death of a worker isn't enough justification for suicide. */
3718 edata.elevel = Min(edata.elevel, ERROR);
3719
3720 /*
3721 * Add a context line to show that this is a message
3722 * propagated from the worker. Otherwise, it can sometimes be
3723 * confusing to understand what actually happened.
3724 */
3725 if (edata.context)
3726 edata.context = psprintf("%s\n%s", edata.context,
3727 _("REPACK decoding worker"));
3728 else
3729 edata.context = pstrdup(_("REPACK decoding worker"));
3730
3731 /* Rethrow error or print notice. */
3733
3734 break;
3735 }
3736
3737 default:
3738 {
3739 elog(ERROR, "unrecognized message type received from decoding worker: %c (message length %d bytes)",
3740 msgtype, msg->len);
3741 }
3742 }
3743}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:263
@ ACLCHECK_OK
Definition acl.h:184
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4083
StrategyNumber IndexAmTranslateCompareType(CompareType cmptype, Oid amoid, Oid opfamily, bool missing_ok)
Definition amapi.c:161
int16 AttrNumber
Definition attnum.h:21
#define InvalidAttrNumber
Definition attnum.h:23
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
void pgstat_progress_incr_param(int index, int64 incr)
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_end_command(void)
@ PROGRESS_COMMAND_REPACK
void TerminateBackgroundWorker(BackgroundWorkerHandle *handle)
Definition bgworker.c:1319
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition bgworker.c:1280
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition bgworker.c:1068
#define BGW_NEVER_RESTART
Definition bgworker.h:92
BgwHandleStatus
Definition bgworker.h:111
@ BGWH_POSTMASTER_DIED
Definition bgworker.h:115
@ BgWorkerStart_RecoveryFinished
Definition bgworker.h:88
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition bgworker.h:60
#define BGWORKER_SHMEM_ACCESS
Definition bgworker.h:53
#define BGW_MAXLEN
Definition bgworker.h:93
uint32 BlockNumber
Definition block.h:31
static Datum values[MAXATTR]
Definition bootstrap.c:190
BufFile * BufFileOpenFileSet(FileSet *fileset, const char *name, int mode, bool missing_ok)
Definition buffile.c:292
void BufFileReadExact(BufFile *file, void *ptr, size_t size)
Definition buffile.c:655
size_t BufFileReadMaybeEOF(BufFile *file, void *ptr, size_t size, bool eofOK)
Definition buffile.c:665
void BufFileClose(BufFile *file)
Definition buffile.c:413
#define RelationGetNumberOfBlocks(reln)
Definition bufmgr.h:309
#define NameStr(name)
Definition c.h:835
#define Min(x, y)
Definition c.h:1091
#define PG_USED_FOR_ASSERTS_ONLY
Definition c.h:249
#define Max(x, y)
Definition c.h:1085
#define BUFFERALIGN(LEN)
Definition c.h:898
#define VARHDRSZ
Definition c.h:781
#define Assert(condition)
Definition c.h:943
TransactionId MultiXactId
Definition c.h:746
int32_t int32
Definition c.h:620
uint64_t uint64
Definition c.h:625
uint32_t uint32
Definition c.h:624
float float4
Definition c.h:713
uint32 TransactionId
Definition c.h:736
#define OidIsValid(objectId)
Definition c.h:858
size_t Size
Definition c.h:689
bool IsToastRelation(Relation relation)
Definition catalog.c:206
bool IsSystemRelation(Relation relation)
Definition catalog.c:74
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:448
bool IsCatalogRelation(Relation relation)
Definition catalog.c:104
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition catalog.c:86
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
@ COMPARE_EQ
Definition cmptype.h:36
void analyze_rel(Oid relid, RangeVar *relation, const VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
Definition analyze.c:110
bool ConditionVariableCancelSleep(void)
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
void ConditionVariableInit(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
bool defGetBoolean(DefElem *def)
Definition define.c:93
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition dependency.c:279
@ DEPENDENCY_AUTO
Definition dependency.h:34
@ DEPENDENCY_INTERNAL
Definition dependency.h:35
#define PERFORM_DELETION_INTERNAL
Definition dependency.h:92
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition dsm.c:1131
void dsm_detach(dsm_segment *seg)
Definition dsm.c:811
void * dsm_segment_address(dsm_segment *seg)
Definition dsm.c:1103
dsm_segment * dsm_create(Size size, int flags)
Definition dsm.c:524
void ThrowErrorData(ErrorData *edata)
Definition elog.c:2091
int errcode(int sqlerrcode)
Definition elog.c:875
#define _(x)
Definition elog.c:96
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:42
#define PG_TRY(...)
Definition elog.h:374
#define WARNING
Definition elog.h:37
#define DEBUG2
Definition elog.h:30
#define PG_END_TRY(...)
Definition elog.h:399
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define PG_FINALLY(...)
Definition elog.h:391
#define INFO
Definition elog.h:35
#define ereport(elevel,...)
Definition elog.h:152
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
List * ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, EState *estate, uint32 flags, TupleTableSlot *slot, List *arbiterIndexes, bool *specConflict)
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition execMain.c:1271
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
const TupleTableSlotOps TTSOpsVirtual
Definition execTuples.c:84
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
void FreeExecutorState(EState *estate)
Definition execUtils.c:197
EState * CreateExecutorState(void)
Definition execUtils.c:90
#define ResetPerTupleExprContext(estate)
Definition executor.h:676
#define EIIT_IS_UPDATE
Definition executor.h:757
#define GetPerTupleMemoryContext(estate)
Definition executor.h:672
#define EIIT_ONLY_SUMMARIZING
Definition executor.h:759
#define palloc_object(type)
Definition fe_memutils.h:89
#define palloc_array(type, count)
Definition fe_memutils.h:91
#define palloc0_object(type)
Definition fe_memutils.h:90
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition fmgr.c:1151
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:612
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:523
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
volatile sig_atomic_t InterruptPending
Definition globals.c:32
int MyProcPid
Definition globals.c:49
ProcNumber MyProcNumber
Definition globals.c:92
bool allowSystemTableMods
Definition globals.c:132
struct Latch * MyLatch
Definition globals.c:65
Oid MyDatabaseId
Definition globals.c:96
int NewGUCNestLevel(void)
Definition guc.c:2142
void RestrictSearchPath(void)
Definition guc.c:2153
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition guc.c:2169
void RelationClearMissing(Relation rel)
Definition heap.c:1981
Oid heap_create_with_catalog(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid reltypeid, Oid reloftypeid, Oid ownerid, Oid accessmtd, TupleDesc tupdesc, List *cooked_constraints, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, OnCommitAction oncommit, Datum reloptions, bool use_user_acl, bool allow_system_table_mods, bool is_internal, Oid relrewrite, ObjectAddress *typaddress)
Definition heap.c:1137
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1435
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1118
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition heaptuple.c:456
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
#define HEAPTUPLESIZE
Definition htup.h:73
HeapTupleData * HeapTuple
Definition htup.h:71
HeapTupleHeaderData * HeapTupleHeader
Definition htup.h:23
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
#define stmt
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition index.c:3604
bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params)
Definition index.c:3969
Oid index_create_copy(Relation heapRelation, uint16 flags, Oid oldIndexId, Oid tablespaceOid, const char *newName)
Definition index.c:1306
#define INDEX_CREATE_SUPPRESS_PROGRESS
Definition index.h:74
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition index.h:169
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition index.h:167
#define REINDEX_REL_FORCE_INDEXES_PERMANENT
Definition index.h:170
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition index.h:168
bool index_getnext_slot(IndexScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition indexam.c:698
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, IndexScanInstrumentation *instrument, int nkeys, int norderbys, uint32 flags)
Definition indexam.c:257
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
void index_endscan(IndexScanDesc scan)
Definition indexam.c:394
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition indexam.c:368
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition indexcmds.c:2634
void CatalogTupleUpdateWithInfo(Relation heapRel, const ItemPointerData *otid, HeapTuple tup, CatalogIndexState indstate)
Definition indexing.c:337
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition indexing.c:61
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition indexing.c:43
static struct @177 value
#define INJECTION_POINT(name, arg)
void CacheInvalidateCatalog(Oid catalogId)
Definition inval.c:1612
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition inval.c:1669
int i
Definition isn.c:77
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition itemptr.h:184
void SetLatch(Latch *latch)
Definition latch.c:290
List * lappend(List *list, void *datum)
Definition list.c:339
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
void list_free(List *list)
Definition list.c:1546
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:151
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:229
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:107
bool CheckRelationLockedByMe(Relation relation, LOCKMODE lockmode, bool orstronger)
Definition lmgr.c:334
bool CheckRelationOidLockedByMe(Oid relid, LOCKMODE lockmode, bool orstronger)
Definition lmgr.c:351
int LOCKMODE
Definition lockdefs.h:26
#define NoLock
Definition lockdefs.h:34
#define AccessExclusiveLock
Definition lockdefs.h:43
#define AccessShareLock
Definition lockdefs.h:36
#define ShareUpdateExclusiveLock
Definition lockdefs.h:39
#define RowExclusiveLock
Definition lockdefs.h:38
LockTupleMode
Definition lockoptions.h:51
char * get_rel_name(Oid relid)
Definition lsyscache.c:2159
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2234
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2183
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1516
bool get_index_isclustered(Oid index_oid)
Definition lsyscache.c:3879
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition lsyscache.c:170
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3599
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition lsyscache.c:2116
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
char * pstrdup(const char *in)
Definition mcxt.c:1910
void pfree(void *pointer)
Definition mcxt.c:1619
MemoryContext TopMemoryContext
Definition mcxt.c:167
void * palloc(Size size)
Definition mcxt.c:1390
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:475
MemoryContext PortalContext
Definition mcxt.c:176
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h:138
#define SECURITY_RESTRICTED_OPERATION
Definition miscadmin.h:331
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition miscinit.c:613
Oid GetUserId(void)
Definition miscinit.c:470
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition miscinit.c:620
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition multixact.c:2865
#define MultiXactIdIsValid(multi)
Definition multixact.h:29
#define InvalidMultiXactId
Definition multixact.h:25
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition namespace.c:3745
Oid LookupCreationNamespace(const char *nspname)
Definition namespace.c:3500
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition namespace.c:442
static char * errmsg
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
#define ObjectAddressSet(addr, class_id, object_id)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
RepackCommand
@ REPACK_COMMAND_REPACK
@ REPACK_COMMAND_CLUSTER
@ REPACK_COMMAND_VACUUMFULL
#define ACL_MAINTAIN
Definition parsenodes.h:90
@ DROP_RESTRICT
static int verbose
#define ERRCODE_DATA_CORRUPTED
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
#define NAMEDATALEN
#define MAXPGPATH
END_CATALOG_STRUCT typedef FormData_pg_constraint * Form_pg_constraint
const void * data
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition pg_depend.c:47
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition pg_depend.c:459
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition pg_depend.c:303
END_CATALOG_STRUCT typedef FormData_pg_index * Form_pg_index
Definition pg_index.h:74
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:550
#define foreach_current_index(var_or_cell)
Definition pg_list.h:435
static Oid list_nth_oid(const List *list, int n)
Definition pg_list.h:353
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
#define foreach_node(type, var, lst)
Definition pg_list.h:528
#define foreach_oid(var, lst)
Definition pg_list.h:503
#define lfirst_oid(lc)
Definition pg_list.h:174
const char * pg_rusage_show(const PGRUsage *ru0)
Definition pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition pg_rusage.c:27
bool plan_cluster_use_sort(Oid tableOid, Oid indexOid)
Definition planner.c:7161
#define snprintf
Definition port.h:261
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
static Datum UInt32GetDatum(uint32 X)
Definition postgres.h:232
#define PointerGetDatum(X)
Definition postgres.h:354
#define InvalidOid
unsigned int Oid
int pq_getmsgbyte(StringInfo msg)
Definition pqformat.c:398
void pq_parse_errornotice(StringInfo msg, ErrorData *edata)
Definition pqmq.c:229
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition predicate.c:3052
static int fb(int x)
@ ONCOMMIT_NOOP
Definition primnodes.h:59
#define PROGRESS_REPACK_PHASE_CATCH_UP
Definition progress.h:103
#define PROGRESS_REPACK_PHASE
Definition progress.h:86
#define PROGRESS_REPACK_COMMAND
Definition progress.h:85
#define PROGRESS_REPACK_PHASE_SWAP_REL_FILES
Definition progress.h:104
#define PROGRESS_REPACK_HEAP_TUPLES_DELETED
Definition progress.h:91
#define PROGRESS_REPACK_HEAP_TUPLES_UPDATED
Definition progress.h:90
#define PROGRESS_REPACK_PHASE_FINAL_CLEANUP
Definition progress.h:106
#define PROGRESS_REPACK_PHASE_REBUILD_INDEX
Definition progress.h:105
#define PROGRESS_REPACK_HEAP_TUPLES_INSERTED
Definition progress.h:89
#define PqMsg_ErrorResponse
Definition protocol.h:44
#define PqMsg_NoticeResponse
Definition protocol.h:49
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationGetDescr(relation)
Definition rel.h:542
#define RelationIsMapped(relation)
Definition rel.h:565
#define RelationGetRelationName(relation)
Definition rel.h:550
#define RelationIsPopulated(relation)
Definition rel.h:697
#define RELATION_IS_OTHER_TEMP(relation)
Definition rel.h:678
#define RelationGetNamespace(relation)
Definition rel.h:557
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4837
void RelationAssumeNewRelfilelocator(Relation relation)
Definition relcache.c:3978
void RelationMapRemoveMapping(Oid relationId)
Definition relmapper.c:439
RelFileNumber RelationMapOidToFilenumber(Oid relationId, bool shared)
Definition relmapper.c:166
void RelationMapUpdateMap(Oid relationId, RelFileNumber fileNumber, bool shared, bool immediate)
Definition relmapper.c:326
Oid RelFileNumber
Definition relpath.h:25
#define RelFileNumberIsValid(relnumber)
Definition relpath.h:27
static bool cluster_rel_recheck(RepackCommand cmd, Relation OldHeap, Oid indexOid, Oid userid, LOCKMODE lmode, int options)
Definition repack.c:699
static void restore_tuple(BufFile *file, Relation relation, TupleTableSlot *slot)
Definition repack.c:2711
static void start_repack_decoding_worker(Oid relid)
Definition repack.c:3400
static void check_concurrent_repack_requirements(Relation rel, Oid *ident_idx_p)
Definition repack.c:886
static bool find_target_tuple(Relation rel, ChangeContext *chgcxt, TupleTableSlot *locator, TupleTableSlot *retrieved)
Definition repack.c:2816
static List * get_tables_to_repack_partitioned(RepackCommand cmd, Oid relid, bool rel_is_index, MemoryContext permcxt)
Definition repack.c:2249
void finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap, bool is_system_catalog, bool swap_toast_by_content, bool check_constraints, bool is_internal, bool reindex, TransactionId frozenXid, MultiXactId cutoffMulti, char newrelpersistence)
Definition repack.c:1875
static Relation process_single_relation(RepackStmt *stmt, LOCKMODE lockmode, bool isTopLevel, ClusterParams *params)
Definition repack.c:2340
void check_index_is_clusterable(Relation OldHeap, Oid indexOid, LOCKMODE lockmode)
Definition repack.c:760
static void release_change_context(ChangeContext *chgcxt)
Definition repack.c:3054
static bool repack_is_permitted_for_relation(RepackCommand cmd, Oid relid, Oid userid)
Definition repack.c:2312
void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
Definition repack.c:244
static void stop_repack_decoding_worker(void)
Definition repack.c:3492
static LOCKMODE RepackLockLevel(bool concurrent)
Definition repack.c:478
static void apply_concurrent_delete(Relation rel, TupleTableSlot *slot)
Definition repack.c:2679
static void ProcessRepackMessage(StringInfo msg)
Definition repack.c:3701
volatile sig_atomic_t RepackMessagePending
Definition repack.c:150
void cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid, ClusterParams *params, bool isTopLevel)
Definition repack.c:511
static List * get_tables_to_repack(RepackCommand cmd, bool usingindex, MemoryContext permcxt)
Definition repack.c:2096
static const char * RepackCommandAsString(RepackCommand cmd)
Definition repack.c:2474
void DecodingWorkerFileName(char *fname, Oid relid, uint32 seq)
Definition repack.c:3591
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, Oid NewAccessMethod, char relpersistence, LOCKMODE lockmode)
Definition repack.c:1118
static void initialize_change_context(ChangeContext *chgcxt, Relation relation, Oid ident_index_id)
Definition repack.c:2962
static bool identity_key_equal(ChangeContext *chgcxt, TupleTableSlot *locator, TupleTableSlot *candidate)
Definition repack.c:2869
static void process_concurrent_changes(XLogRecPtr end_of_wal, ChangeContext *chgcxt, bool done)
Definition repack.c:2906
static void copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex, Snapshot snapshot, bool verbose, bool *pSwapToastByContent, TransactionId *pFreezeXid, MultiXactId *pCutoffMulti)
Definition repack.c:1247
static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, Oid identIdx, TransactionId frozenXid, MultiXactId cutoffMulti)
Definition repack.c:3072
static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot, ChangeContext *chgcxt)
Definition repack.c:2618
static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt)
Definition repack.c:2492
static void rebuild_relation(Relation OldHeap, Relation index, bool verbose, Oid ident_idx)
Definition repack.c:971
void HandleRepackMessageInterrupt(void)
Definition repack.c:3605
static Snapshot get_initial_snapshot(DecodingWorker *worker)
Definition repack.c:3534
void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal)
Definition repack.c:820
static void adjust_toast_pointers(Relation relation, TupleTableSlot *dest, TupleTableSlot *src)
Definition repack.c:2781
#define WORKER_FILE_SNAPSHOT
Definition repack.c:98
static void swap_relation_files(Oid r1, Oid r2, bool target_is_pg_class, bool swap_toast_by_content, bool is_internal, TransactionId frozenXid, MultiXactId cutoffMulti, Oid *mapped_tables)
Definition repack.c:1493
static Oid determine_clustered_index(Relation rel, bool usingindex, const char *indexname)
Definition repack.c:2431
void ProcessRepackMessages(void)
Definition repack.c:3616
static void copy_index_constraints(Relation old_index, Oid new_index_id, Oid new_heap_id)
Definition repack.c:3333
static void apply_concurrent_update(Relation rel, TupleTableSlot *spilled_tuple, TupleTableSlot *ondisk_tuple, ChangeContext *chgcxt)
Definition repack.c:2639
static DecodingWorker * decoding_worker
Definition repack.c:144
static List * build_new_indexes(Relation NewHeap, Relation OldHeap, List *OldIndexes)
Definition repack.c:3288
#define CLUOPT_VERBOSE
Definition repack.h:25
#define CLUOPT_ANALYZE
Definition repack.h:28
#define CLUOPT_CONCURRENT
Definition repack.h:29
#define CLUOPT_RECHECK_ISCLUSTERED
Definition repack.h:27
#define CLUOPT_RECHECK
Definition repack.h:26
#define CHANGE_UPDATE_OLD
#define CHANGE_DELETE
#define CHANGE_UPDATE_NEW
char ConcurrentChangeKind
#define CHANGE_INSERT
#define REPACK_ERROR_QUEUE_SIZE
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
@ ForwardScanDirection
Definition sdir.h:28
void SharedFileSetInit(SharedFileSet *fileset, dsm_segment *seg)
shm_mq * shm_mq_create(void *address, Size size)
Definition shm_mq.c:179
void shm_mq_detach(shm_mq_handle *mqh)
Definition shm_mq.c:845
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition shm_mq.c:208
shm_mq_result shm_mq_receive(shm_mq_handle *mqh, Size *nbytesp, void **datap, bool nowait)
Definition shm_mq.c:574
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition shm_mq.c:292
shm_mq_result
Definition shm_mq.h:39
@ SHM_MQ_SUCCESS
Definition shm_mq.h:40
@ SHM_MQ_WOULD_BLOCK
Definition shm_mq.h:41
@ SHM_MQ_DETACHED
Definition shm_mq.h:42
ScanKeyData * ScanKey
Definition skey.h:75
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
Snapshot RestoreSnapshot(char *start_address)
Definition snapmgr.c:1793
void UpdateActiveSnapshotCommandId(void)
Definition snapmgr.c:744
void PopActiveSnapshot(void)
Definition snapmgr.c:775
Snapshot GetActiveSnapshot(void)
Definition snapmgr.c:800
#define InvalidSnapshot
Definition snapshot.h:119
static void SpinLockRelease(volatile slock_t *lock)
Definition spin.h:62
static void SpinLockAcquire(volatile slock_t *lock)
Definition spin.h:56
static void SpinLockInit(volatile slock_t *lock)
Definition spin.h:50
void relation_close(Relation relation, LOCKMODE lockmode)
Definition relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition relation.c:48
Oid GetRelationIdentityOrPK(Relation rel)
Definition relation.c:905
PGPROC * MyProc
Definition proc.c:71
void BecomeLockGroupLeader(void)
Definition proc.c:2042
uint16 StrategyNumber
Definition stratnum.h:22
#define InvalidStrategy
Definition stratnum.h:24
#define BTEqualStrategyNumber
Definition stratnum.h:31
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition stringinfo.c:281
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
int cc_file_seq
Definition repack.c:125
int cc_ident_key_nentries
Definition repack.c:119
Relation cc_rel
Definition repack.c:106
AttrNumber cc_last_key_attno
Definition repack.c:122
Relation cc_ident_index
Definition repack.c:117
ScanKey cc_ident_key
Definition repack.c:118
EState * cc_estate
Definition repack.c:110
ResultRelInfo * cc_rri
Definition repack.c:109
uint32 options
Definition repack.h:34
bool attisdropped
Definition tupdesc.h:78
ConditionVariable cv
char error_queue[FLEXIBLE_ARRAY_MEMBER]
dsm_segment * seg
Definition repack.c:137
BackgroundWorkerHandle * handle
Definition repack.c:134
shm_mq_handle * error_mqh
Definition repack.c:140
Definition pg_list.h:54
Oid indexOid
Definition repack.c:91
Oid tableOid
Definition repack.c:90
Form_pg_class rd_rel
Definition rel.h:111
Datum sk_argument
Definition skey.h:72
FmgrInfo sk_func
Definition skey.h:71
Oid sk_collation
Definition skey.h:70
TupleDesc tts_tupleDescriptor
Definition tuptable.h:129
bool * tts_isnull
Definition tuptable.h:133
ItemPointerData tts_tid
Definition tuptable.h:142
Datum * tts_values
Definition tuptable.h:131
TransactionId FreezeLimit
Definition vacuum.h:288
TransactionId OldestXmin
Definition vacuum.h:278
TransactionId relfrozenxid
Definition vacuum.h:262
MultiXactId relminmxid
Definition vacuum.h:263
MultiXactId MultiXactCutoff
Definition vacuum.h:289
Definition type.h:97
Definition c.h:776
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
#define SearchSysCacheExists1(cacheId, key1)
Definition syscache.h:100
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:60
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, ScanKeyData *key)
Definition tableam.c:113
const TupleTableSlotOps * table_slot_callbacks(Relation relation)
Definition tableam.c:59
TU_UpdateIndexes
Definition tableam.h:133
@ TU_Summarizing
Definition tableam.h:141
@ TU_None
Definition tableam.h:135
static void table_endscan(TableScanDesc scan)
Definition tableam.h:1061
#define TABLE_INSERT_NO_LOGICAL
Definition tableam.h:286
TM_Result
Definition tableam.h:95
@ TM_Ok
Definition tableam.h:100
static void table_relation_copy_for_cluster(Relation OldTable, Relation NewTable, Relation OldIndex, bool use_sort, TransactionId OldestXmin, Snapshot snapshot, TransactionId *xid_cutoff, MultiXactId *multi_cutoff, double *num_tuples, double *tups_vacuumed, double *tups_recently_dead)
Definition tableam.h:1746
static void table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid, uint32 options, BulkInsertStateData *bistate)
Definition tableam.h:1458
#define TABLE_DELETE_NO_LOGICAL
Definition tableam.h:290
#define TABLE_UPDATE_NO_LOGICAL
Definition tableam.h:293
static TM_Result table_tuple_update(Relation rel, ItemPointer otid, TupleTableSlot *slot, CommandId cid, uint32 options, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
Definition tableam.h:1598
static TM_Result table_tuple_delete(Relation rel, ItemPointer tid, CommandId cid, uint32 options, Snapshot snapshot, Snapshot crosscheck, bool wait, TM_FailureData *tmfd)
Definition tableam.h:1549
void ResetRelRewrite(Oid myrelid)
Definition tablecmds.c:4420
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition tablecmds.c:4473
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition tablecmds.c:4327
void RangeVarCallbackMaintainsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Oid toast_get_valid_index(Oid toastoid, LOCKMODE lock)
void NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode, Oid OIDOldToast)
Definition toasting.c:65
#define InvalidTransactionId
Definition transam.h:31
#define TransactionIdIsValid(xid)
Definition transam.h:41
#define TransactionIdIsNormal(xid)
Definition transam.h:42
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:195
static void slot_getsomeattrs(TupleTableSlot *slot, int attnum)
Definition tuptable.h:376
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition tuptable.h:476
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition tuptable.h:403
bool vacuum_get_cutoffs(Relation rel, const VacuumParams *params, struct VacuumCutoffs *cutoffs)
Definition vacuum.c:1106
#define VACOPT_VERBOSE
Definition vacuum.h:181
#define VACOPT_ANALYZE
Definition vacuum.h:180
static bool VARATT_IS_EXTERNAL_ONDISK(const void *PTR)
Definition varatt.h:361
static Size VARSIZE_ANY(const void *PTR)
Definition varatt.h:460
static bool VARATT_IS_EXTERNAL_INDIRECT(const void *PTR)
Definition varatt.h:368
static bool initialized
Definition win32ntdll.c:36
void CommandCounterIncrement(void)
Definition xact.c:1130
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition xact.c:3698
void StartTransactionCommand(void)
Definition xact.c:3109
void CommitTransactionCommand(void)
Definition xact.c:3207
CommandId GetCurrentCommandId(bool used)
Definition xact.c:831
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
Definition xlog.c:6997
XLogRecPtr GetXLogInsertEndRecPtr(void)
Definition xlog.c:10108
void XLogFlush(XLogRecPtr record)
Definition xlog.c:2801
uint64 XLogRecPtr
Definition xlogdefs.h:21
#define InvalidXLogRecPtr
Definition xlogdefs.h:28