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("REPACK (CONCURRENTLY) is not supported for partitioned tables"),
332 errhint("Consider running the command on individual partitions."));
333 }
334 else
337 errmsg("REPACK (CONCURRENTLY) requires an explicit table name"));
338 }
339
340 /*
341 * In order to avoid holding locks for too long, we want to process each
342 * table in its own transaction. This forces us to disallow running
343 * inside a user transaction block.
344 */
346
347 /* Also, we need a memory context to hold our list of relations */
349 "Repack",
351
352 /*
353 * Since we open a new transaction for each relation, we have to check
354 * that the relation still is what we think it is.
355 *
356 * In single-transaction CLUSTER, we don't need the overhead.
357 */
358 params.options |= CLUOPT_RECHECK;
359
360 /*
361 * If we don't have a relation yet, determine a relation list. If we do,
362 * then it must be a partitioned table, and we want to process its
363 * partitions.
364 */
365 if (rel == NULL)
366 {
367 Assert(stmt->indexname == NULL);
368 rtcs = get_tables_to_repack(stmt->command, stmt->usingindex,
371 }
372 else
373 {
374 Oid relid;
375 bool rel_is_index;
376
377 Assert(rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
378
379 /*
380 * If USING INDEX was specified, resolve the index name now and pass
381 * it down.
382 */
383 if (stmt->usingindex)
384 {
385 /*
386 * If no index name was specified when repacking a partitioned
387 * table, punt for now. Maybe we can improve this later.
388 */
389 if (!stmt->indexname)
390 {
391 if (stmt->command == REPACK_COMMAND_CLUSTER)
394 errmsg("there is no previously clustered index for table \"%s\"",
396 else
399 /*- translator: first %s is name of a SQL command, eg. REPACK */
400 errmsg("cannot execute %s on partitioned table \"%s\" USING INDEX with no index name",
401 RepackCommandAsString(stmt->command),
403 }
404
405 relid = determine_clustered_index(rel, stmt->usingindex,
406 stmt->indexname);
407 if (!OidIsValid(relid))
408 elog(ERROR, "unable to determine index to cluster on");
410
411 rel_is_index = true;
412 }
413 else
414 {
415 relid = RelationGetRelid(rel);
416 rel_is_index = false;
417 }
418
420 relid, rel_is_index,
422
423 /* close parent relation, releasing lock on it */
425 rel = NULL;
426 }
427
428 /* Commit to get out of starting transaction */
431
432 /* Cluster the tables, each in a separate transaction */
433 Assert(rel == NULL);
435 {
436 /* Start a new transaction for each relation. */
438
439 /*
440 * Open the target table, coping with the case where it has been
441 * dropped.
442 */
443 rel = try_table_open(rtc->tableOid, lockmode);
444 if (rel == NULL)
445 {
447 continue;
448 }
449
450 /* functions in indexes may want a snapshot set */
452
453 /* Process this table */
454 cluster_rel(stmt->command, rel, rtc->indexOid, &params, isTopLevel);
455 /* cluster_rel closes the relation, but keeps lock */
456
459 }
460
461 /* Start a new transaction for the cleanup work. */
463
464 /* Clean up working storage */
466}
467
468/*
469 * In the non-concurrent case, we obtain AccessExclusiveLock throughout the
470 * operation to avoid any lock-upgrade hazards. In the concurrent case, we
471 * grab ShareUpdateExclusiveLock (just like VACUUM) for most of the
472 * processing and only acquire AccessExclusiveLock at the end, to swap the
473 * relation -- supposedly for a short time.
474 */
475static LOCKMODE
476RepackLockLevel(bool concurrent)
477{
478 if (concurrent)
480 else
481 return AccessExclusiveLock;
482}
483
484/*
485 * cluster_rel
486 *
487 * This clusters the table by creating a new, clustered table and
488 * swapping the relfilenumbers of the new table and the old table, so
489 * the OID of the original table is preserved. Thus we do not lose
490 * GRANT, inheritance nor references to this table.
491 *
492 * Indexes are rebuilt too, via REINDEX. Since we are effectively bulk-loading
493 * the new table, it's better to create the indexes afterwards than to fill
494 * them incrementally while we load the table.
495 *
496 * If indexOid is InvalidOid, the table will be rewritten in physical order
497 * instead of index order.
498 *
499 * Note that, in the concurrent case, the function releases the lock at some
500 * point, in order to get AccessExclusiveLock for the final steps (i.e. to
501 * swap the relation files). To make things simpler, the caller should expect
502 * OldHeap to be closed on return, regardless CLUOPT_CONCURRENT. (The
503 * AccessExclusiveLock is kept till the end of the transaction.)
504 *
505 * 'cmd' indicates which command is being executed, to be used for error
506 * messages.
507 */
508void
510 ClusterParams *params, bool isTopLevel)
511{
512 Oid tableOid = RelationGetRelid(OldHeap);
515 Oid save_userid;
516 int save_sec_context;
517 int save_nestlevel;
518 bool verbose = ((params->options & CLUOPT_VERBOSE) != 0);
519 bool recheck = ((params->options & CLUOPT_RECHECK) != 0);
520 bool concurrent = ((params->options & CLUOPT_CONCURRENT) != 0);
522
523 /* Determine the lock mode to use. */
524 lmode = RepackLockLevel(concurrent);
525
526 /*
527 * Check some preconditions in the concurrent case. This also obtains the
528 * replica index OID.
529 */
530 if (concurrent)
532
533 /* Check for user-requested abort. */
535
538
539 /*
540 * Switch to the table owner's userid, so that any index functions are run
541 * as that user. Also lock down security-restricted operations and
542 * arrange to make GUC variable changes local to this command.
543 */
544 GetUserIdAndSecContext(&save_userid, &save_sec_context);
545 SetUserIdAndSecContext(OldHeap->rd_rel->relowner,
546 save_sec_context | SECURITY_RESTRICTED_OPERATION);
547 save_nestlevel = NewGUCNestLevel();
549
550 /*
551 * Recheck that the relation is still what it was when we started.
552 *
553 * Note that it's critical to skip this in single-relation CLUSTER;
554 * otherwise, we would reject an attempt to cluster using a
555 * not-previously-clustered index.
556 */
557 if (recheck &&
558 !cluster_rel_recheck(cmd, OldHeap, indexOid, save_userid,
559 lmode, params->options))
560 goto out;
561
562 /*
563 * We allow repacking shared catalogs only when not using an index. It
564 * would work to use an index in most respects, but the index would only
565 * get marked as indisclustered in the current database, leading to
566 * unexpected behavior if CLUSTER were later invoked in another database.
567 */
568 if (OidIsValid(indexOid) && OldHeap->rd_rel->relisshared)
571 /*- translator: first %s is name of a SQL command, eg. REPACK */
572 errmsg("cannot execute %s on a shared catalog",
574
575 /*
576 * The CONCURRENTLY case should have been rejected earlier because it does
577 * not support system catalogs.
578 */
579 Assert(!(OldHeap->rd_rel->relisshared && concurrent));
580
581 /*
582 * Don't process temp tables of other backends ... their local buffer
583 * manager is not going to cope.
584 */
588 /*- translator: first %s is name of a SQL command, eg. REPACK */
589 errmsg("cannot execute %s on temporary tables of other sessions",
591
592 /*
593 * Also check for active uses of the relation in the current transaction,
594 * including open scans and pending AFTER trigger events.
595 */
597
598 /* Check heap and index are valid to cluster on */
599 if (OidIsValid(indexOid))
600 {
601 /* verify the index is good and lock it */
603 /* also open it */
604 index = index_open(indexOid, NoLock);
605 }
606 else
607 index = NULL;
608
609 /*
610 * When allow_system_table_mods is turned off, we disallow repacking a
611 * catalog on a particular index unless that's already the clustered index
612 * for that catalog.
613 *
614 * XXX We don't check for this in CLUSTER, because it's historically been
615 * allowed.
616 */
617 if (cmd != REPACK_COMMAND_CLUSTER &&
618 !allowSystemTableMods && OidIsValid(indexOid) &&
619 IsCatalogRelation(OldHeap) && !index->rd_index->indisclustered)
622 errmsg("permission denied: \"%s\" is a system catalog",
624 errdetail("System catalogs can only be clustered by the index they're already clustered on, if any, unless \"%s\" is enabled.",
625 "allow_system_table_mods"));
626
627 /*
628 * Quietly ignore the request if this is a materialized view which has not
629 * been populated from its query. No harm is done because there is no data
630 * to deal with, and we don't want to throw an error if this is part of a
631 * multi-relation request -- for example, CLUSTER was run on the entire
632 * database.
633 */
634 if (OldHeap->rd_rel->relkind == RELKIND_MATVIEW &&
636 {
637 if (index)
640 goto out;
641 }
642
643 Assert(OldHeap->rd_rel->relkind == RELKIND_RELATION ||
644 OldHeap->rd_rel->relkind == RELKIND_MATVIEW ||
645 OldHeap->rd_rel->relkind == RELKIND_TOASTVALUE);
646
647 /*
648 * All predicate locks on the tuples or pages are about to be made
649 * invalid, because we move tuples around. Promote them to relation
650 * locks. Predicate locks on indexes will be promoted when they are
651 * reindexed.
652 *
653 * During concurrent processing, the heap as well as its indexes stay in
654 * operation, so we postpone this step until they are locked using
655 * AccessExclusiveLock near the end of the processing.
656 */
657 if (!concurrent)
659
660 /* rebuild_relation does all the dirty work */
661 PG_TRY();
662 {
664 }
665 PG_FINALLY();
666 {
667 if (concurrent)
668 {
669 /*
670 * Since during normal operation the worker was already asked to
671 * exit, stopping it explicitly is especially important on ERROR.
672 * However it still seems a good practice to make sure that the
673 * worker never survives the REPACK command.
674 */
676 }
677 }
678 PG_END_TRY();
679
680 /* rebuild_relation closes OldHeap, and index if valid */
681
682out:
683 /* Roll back any GUC changes executed by index functions */
684 AtEOXact_GUC(false, save_nestlevel);
685
686 /* Restore userid and security context */
687 SetUserIdAndSecContext(save_userid, save_sec_context);
688
690}
691
692/*
693 * Check if the table (and its index) still meets the requirements of
694 * cluster_rel().
695 */
696static bool
698 Oid userid, LOCKMODE lmode, int options)
699{
700 Oid tableOid = RelationGetRelid(OldHeap);
701
702 /* Check that the user still has privileges for the relation */
703 if (!repack_is_permitted_for_relation(cmd, tableOid, userid))
704 {
706 return false;
707 }
708
709 /*
710 * Silently skip a temp table for a remote session. Only doing this check
711 * in the "recheck" case is appropriate (which currently means somebody is
712 * executing a database-wide CLUSTER or on a partitioned table), because
713 * there is another check in cluster() which will stop any attempt to
714 * cluster remote temp tables by name. There is another check in
715 * cluster_rel which is redundant, but we leave it for extra safety.
716 */
718 {
720 return false;
721 }
722
723 if (OidIsValid(indexOid))
724 {
725 /*
726 * Check that the index still exists
727 */
729 {
731 return false;
732 }
733
734 /*
735 * Check that the index is still the one with indisclustered set, if
736 * needed.
737 */
738 if ((options & CLUOPT_RECHECK_ISCLUSTERED) != 0 &&
739 !get_index_isclustered(indexOid))
740 {
742 return false;
743 }
744 }
745
746 return true;
747}
748
749/*
750 * Verify that the specified heap and index are valid to cluster on
751 *
752 * Side effect: obtains lock on the index. The caller may
753 * in some cases already have a lock of the same strength on the table, but
754 * not in all cases so we can't rely on the table-level lock for
755 * protection here.
756 */
757void
759{
761
762 OldIndex = index_open(indexOid, lockmode);
763
764 /*
765 * Check that index is in fact an index on the given relation
766 */
767 if (OldIndex->rd_index == NULL ||
768 OldIndex->rd_index->indrelid != RelationGetRelid(OldHeap))
771 errmsg("\"%s\" is not an index for table \"%s\"",
774
775 /* Index AM must allow clustering */
776 if (!OldIndex->rd_indam->amclusterable)
779 errmsg("cannot cluster on index \"%s\" because access method does not support clustering",
781
782 /*
783 * Disallow clustering on incomplete indexes (those that might not index
784 * every row of the relation). We could relax this by making a separate
785 * seqscan pass over the table to copy the missing rows, but that seems
786 * expensive and tedious.
787 */
788 if (!heap_attisnull(OldIndex->rd_indextuple, Anum_pg_index_indpred, NULL))
791 errmsg("cannot cluster on partial index \"%s\"",
793
794 /*
795 * Disallow if index is left over from a failed CREATE INDEX CONCURRENTLY;
796 * it might well not contain entries for every heap row, or might not even
797 * be internally consistent. (But note that we don't check indcheckxmin;
798 * the worst consequence of following broken HOT chains would be that we
799 * might put recently-dead tuples out-of-order in the new table, and there
800 * is little harm in that.)
801 */
802 if (!OldIndex->rd_index->indisvalid)
805 errmsg("cannot cluster on invalid index \"%s\"",
807
808 /* Drop relcache refcnt on OldIndex, but keep lock */
810}
811
812/*
813 * mark_index_clustered: mark the specified index as the one clustered on
814 *
815 * With indexOid == InvalidOid, will mark all indexes of rel not-clustered.
816 */
817void
818mark_index_clustered(Relation rel, Oid indexOid, bool is_internal)
819{
824
825 Assert(rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
826
827 /*
828 * If the index is already marked clustered, no need to do anything.
829 */
830 if (OidIsValid(indexOid))
831 {
832 if (get_index_isclustered(indexOid))
833 return;
834 }
835
836 /*
837 * Check each index of the relation and set/clear the bit as needed.
838 */
840
841 foreach(index, RelationGetIndexList(rel))
842 {
844
848 elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
850
851 /*
852 * Unset the bit if set. We know it's wrong because we checked this
853 * earlier.
854 */
855 if (indexForm->indisclustered)
856 {
857 indexForm->indisclustered = false;
859 }
860 else if (thisIndexOid == indexOid)
861 {
862 /* this was checked earlier, but let's be real sure */
863 if (!indexForm->indisvalid)
864 elog(ERROR, "cannot cluster on invalid index %u", indexOid);
865 indexForm->indisclustered = true;
867 }
868
870 InvalidOid, is_internal);
871
873 }
874
876}
877
878/*
879 * Check if the CONCURRENTLY option is legal for the relation.
880 *
881 * *Ident_idx_p receives OID of the identity index.
882 */
883static void
885{
886 char relpersistence,
887 replident;
889
890 /* Data changes in system relations are not logically decoded. */
891 if (IsCatalogRelation(rel))
894 errmsg("cannot repack relation \"%s\"",
896 errhint("REPACK CONCURRENTLY is not supported for catalog relations."));
897
898 /*
899 * reorderbuffer.c does not seem to handle processing of TOAST relation
900 * alone.
901 */
902 if (IsToastRelation(rel))
905 errmsg("cannot repack relation \"%s\"",
907 errhint("REPACK CONCURRENTLY is not supported for TOAST relations"));
908
909 relpersistence = rel->rd_rel->relpersistence;
910 if (relpersistence != RELPERSISTENCE_PERMANENT)
913 errmsg("cannot repack relation \"%s\"",
915 errhint("REPACK CONCURRENTLY is only allowed for permanent relations."));
916
917 /* With NOTHING, WAL does not contain the old tuple. */
918 replident = rel->rd_rel->relreplident;
919 if (replident == REPLICA_IDENTITY_NOTHING)
922 errmsg("cannot repack relation \"%s\"",
924 errhint("Relation \"%s\" has insufficient replication identity.",
926
927 /*
928 * Obtain the replica identity index -- either one that has been set
929 * explicitly, or a non-deferrable primary key. If none of these cases
930 * apply, the table cannot be repacked concurrently. It might be possible
931 * to have repack work with a FULL replica identity; however that requires
932 * more work and is not implemented yet.
933 */
935 if (!OidIsValid(ident_idx))
938 errmsg("cannot process relation \"%s\"",
940 errhint("Relation \"%s\" has no identity index.",
942
944}
945
946
947/*
948 * rebuild_relation: rebuild an existing relation in index or physical order
949 *
950 * OldHeap: table to rebuild. See cluster_rel() for comments on the required
951 * lock strength.
952 *
953 * index: index to cluster by, or NULL to rewrite in physical order.
954 *
955 * ident_idx: identity index, to handle replaying of concurrent data changes
956 * to the new heap. InvalidOid if there's no CONCURRENTLY option.
957 *
958 * On entry, heap and index (if one is given) must be open, and the
959 * appropriate lock held on them -- AccessExclusiveLock for exclusive
960 * processing and ShareUpdateExclusiveLock for concurrent processing.
961 *
962 * On exit, they are closed, but still locked with AccessExclusiveLock.
963 * (The function handles the lock upgrade if 'concurrent' is true.)
964 */
965static void
968{
969 Oid tableOid = RelationGetRelid(OldHeap);
970 Oid accessMethod = OldHeap->rd_rel->relam;
971 Oid tableSpace = OldHeap->rd_rel->reltablespace;
974 char relpersistence;
978 bool concurrent = OidIsValid(ident_idx);
979 Snapshot snapshot = NULL;
980#if USE_ASSERT_CHECKING
982
983 lmode = RepackLockLevel(concurrent);
984
987#endif
988
989 if (concurrent)
990 {
991 /*
992 * The worker needs to be member of the locking group we're the leader
993 * of. We ought to become the leader before the worker starts. The
994 * worker will join the group as soon as it starts.
995 *
996 * This is to make sure that the deadlock described below is
997 * detectable by deadlock.c: if the worker waits for a transaction to
998 * complete and we are waiting for the worker output, then effectively
999 * we (i.e. this backend) are waiting for that transaction.
1000 */
1002
1003 /*
1004 * Start the worker that decodes data changes applied while we're
1005 * copying the table contents.
1006 *
1007 * Note that the worker has to wait for all transactions with XID
1008 * already assigned to finish. If some of those transactions is
1009 * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
1010 * table (e.g. it runs CREATE INDEX), we can end up in a deadlock.
1011 * Not sure this risk is worth unlocking/locking the table (and its
1012 * clustering index) and checking again if it's still eligible for
1013 * REPACK CONCURRENTLY.
1014 */
1016
1017 /*
1018 * Wait until the worker has the initial snapshot and retrieve it.
1019 */
1021
1022 PushActiveSnapshot(snapshot);
1023 }
1024
1025 /* for CLUSTER or REPACK USING INDEX, mark the index as the one to use */
1026 if (index != NULL)
1028
1029 /* Remember info about rel before closing OldHeap */
1030 relpersistence = OldHeap->rd_rel->relpersistence;
1031
1032 /*
1033 * Create the transient table that will receive the re-ordered data.
1034 *
1035 * OldHeap is already locked, so no need to lock it again. make_new_heap
1036 * obtains AccessExclusiveLock on the new heap and its toast table.
1037 */
1038 OIDNewHeap = make_new_heap(tableOid, tableSpace,
1039 accessMethod,
1040 relpersistence,
1041 NoLock);
1044
1045 /* Copy the heap data into the new table in the desired order */
1048
1049 /* The historic snapshot won't be needed anymore. */
1050 if (snapshot)
1051 {
1054 }
1055
1056 if (concurrent)
1057 {
1059
1060 /*
1061 * Close the index, but keep the lock. Both heaps will be closed by
1062 * the following call.
1063 */
1064 if (index)
1066
1069
1072 }
1073 else
1074 {
1076
1077 /* Close relcache entries, but keep lock until transaction commit */
1079 if (index)
1081
1082 /*
1083 * Close the new relation so it can be dropped as soon as the storage
1084 * is swapped. The relation is not visible to others, so no need to
1085 * unlock it explicitly.
1086 */
1088
1089 /*
1090 * Swap the physical files of the target and transient tables, then
1091 * rebuild the target's indexes and throw away the transient table.
1092 */
1094 swap_toast_by_content, false, true,
1095 true, /* reindex */
1097 relpersistence);
1098 }
1099}
1100
1101
1102/*
1103 * Create the transient table that will be filled with new data during
1104 * CLUSTER, ALTER TABLE, and similar operations. The transient table
1105 * duplicates the logical structure of the OldHeap; but will have the
1106 * specified physical storage properties NewTableSpace, NewAccessMethod, and
1107 * relpersistence.
1108 *
1109 * After this, the caller should load the new heap with transferred/modified
1110 * data, then call finish_heap_swap to complete the operation.
1111 */
1112Oid
1114 char relpersistence, LOCKMODE lockmode)
1115{
1119 Oid toastid;
1121 HeapTuple tuple;
1122 Datum reloptions;
1123 bool isNull;
1125
1126 OldHeap = table_open(OIDOldHeap, lockmode);
1128
1129 /*
1130 * Note that the NewHeap will not receive any of the defaults or
1131 * constraints associated with the OldHeap; we don't need 'em, and there's
1132 * no reason to spend cycles inserting them into the catalogs only to
1133 * delete them.
1134 */
1135
1136 /*
1137 * But we do want to use reloptions of the old heap for new heap.
1138 */
1140 if (!HeapTupleIsValid(tuple))
1141 elog(ERROR, "cache lookup failed for relation %u", OIDOldHeap);
1142 reloptions = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
1143 &isNull);
1144 if (isNull)
1145 reloptions = (Datum) 0;
1146
1147 if (relpersistence == RELPERSISTENCE_TEMP)
1149 else
1151
1152 /*
1153 * Create the new heap, using a temporary name in the same namespace as
1154 * the existing table. NOTE: there is some risk of collision with user
1155 * relnames. Working around this seems more trouble than it's worth; in
1156 * particular, we can't create the new heap in a different namespace from
1157 * the old, or we will have problems with the TEMP status of temp tables.
1158 *
1159 * Note: the new heap is not a shared relation, even if we are rebuilding
1160 * a shared rel. However, we do make the new heap mapped if the source is
1161 * mapped. This simplifies swap_relation_files, and is absolutely
1162 * necessary for rebuilding pg_class, for reasons explained there.
1163 */
1164 snprintf(NewHeapName, sizeof(NewHeapName), "pg_temp_%u", OIDOldHeap);
1165
1169 InvalidOid,
1170 InvalidOid,
1171 InvalidOid,
1172 OldHeap->rd_rel->relowner,
1175 NIL,
1177 relpersistence,
1178 false,
1181 reloptions,
1182 false,
1183 true,
1184 true,
1185 OIDOldHeap,
1186 NULL);
1188
1189 ReleaseSysCache(tuple);
1190
1191 /*
1192 * Advance command counter so that the newly-created relation's catalog
1193 * tuples will be visible to table_open.
1194 */
1196
1197 /*
1198 * If necessary, create a TOAST table for the new relation.
1199 *
1200 * If the relation doesn't have a TOAST table already, we can't need one
1201 * for the new relation. The other way around is possible though: if some
1202 * wide columns have been dropped, NewHeapCreateToastTable can decide that
1203 * no TOAST table is needed for the new table.
1204 *
1205 * Note that NewHeapCreateToastTable ends with CommandCounterIncrement, so
1206 * that the TOAST table will be visible for insertion.
1207 */
1208 toastid = OldHeap->rd_rel->reltoastrelid;
1209 if (OidIsValid(toastid))
1210 {
1211 /* keep the existing toast table's reloptions, if any */
1213 if (!HeapTupleIsValid(tuple))
1214 elog(ERROR, "cache lookup failed for relation %u", toastid);
1215 reloptions = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
1216 &isNull);
1217 if (isNull)
1218 reloptions = (Datum) 0;
1219
1220 NewHeapCreateToastTable(OIDNewHeap, reloptions, lockmode, toastid);
1221
1222 ReleaseSysCache(tuple);
1223 }
1224
1226
1227 return OIDNewHeap;
1228}
1229
1230/*
1231 * Do the physical copying of table data.
1232 *
1233 * 'snapshot' and 'decoding_ctx': see table_relation_copy_for_cluster(). Pass
1234 * iff concurrent processing is required.
1235 *
1236 * There are three output parameters:
1237 * *pSwapToastByContent is set true if toast tables must be swapped by content.
1238 * *pFreezeXid receives the TransactionId used as freeze cutoff point.
1239 * *pCutoffMulti receives the MultiXactId used as a cutoff point.
1240 */
1241static void
1243 Snapshot snapshot, bool verbose, bool *pSwapToastByContent,
1245{
1251 VacuumParams params;
1252 struct VacuumCutoffs cutoffs;
1253 bool use_sort;
1254 double num_tuples = 0,
1255 tups_vacuumed = 0,
1257 BlockNumber num_pages;
1258 int elevel = verbose ? INFO : DEBUG2;
1259 PGRUsage ru0;
1260 char *nspname;
1261 bool concurrent = snapshot != NULL;
1263
1264 lmode = RepackLockLevel(concurrent);
1265
1267
1268 /* Store a copy of the namespace name for logging purposes */
1270
1271 /*
1272 * Their tuple descriptors should be exactly alike, but here we only need
1273 * assume that they have the same number of columns.
1274 */
1277 Assert(newTupDesc->natts == oldTupDesc->natts);
1278
1279 /*
1280 * If the OldHeap has a toast table, get lock on the toast table to keep
1281 * it from being vacuumed. This is needed because autovacuum processes
1282 * toast tables independently of their main tables, with no lock on the
1283 * latter. If an autovacuum were to start on the toast table after we
1284 * compute our OldestXmin below, it would use a later OldestXmin, and then
1285 * possibly remove as DEAD toast tuples belonging to main tuples we think
1286 * are only RECENTLY_DEAD. Then we'd fail while trying to copy those
1287 * tuples.
1288 *
1289 * We don't need to open the toast relation here, just lock it. The lock
1290 * will be held till end of transaction.
1291 */
1292 if (OldHeap->rd_rel->reltoastrelid)
1293 LockRelationOid(OldHeap->rd_rel->reltoastrelid, lmode);
1294
1295 /*
1296 * If both tables have TOAST tables, perform toast swap by content. It is
1297 * possible that the old table has a toast table but the new one doesn't,
1298 * if toastable columns have been dropped. In that case we have to do
1299 * swap by links. This is okay because swap by content is only essential
1300 * for system catalogs, and we don't support schema changes for them.
1301 */
1302 if (OldHeap->rd_rel->reltoastrelid && NewHeap->rd_rel->reltoastrelid &&
1303 !concurrent)
1304 {
1305 *pSwapToastByContent = true;
1306
1307 /*
1308 * When doing swap by content, any toast pointers written into NewHeap
1309 * must use the old toast table's OID, because that's where the toast
1310 * data will eventually be found. Set this up by setting rd_toastoid.
1311 * This also tells toast_save_datum() to preserve the toast value
1312 * OIDs, which we want so as not to invalidate toast pointers in
1313 * system catalog caches, and to avoid making multiple copies of a
1314 * single toast value.
1315 *
1316 * Note that we must hold NewHeap open until we are done writing data,
1317 * since the relcache will not guarantee to remember this setting once
1318 * the relation is closed. Also, this technique depends on the fact
1319 * that no one will try to read from the NewHeap until after we've
1320 * finished writing it and swapping the rels --- otherwise they could
1321 * follow the toast pointers to the wrong place. (It would actually
1322 * work for values copied over from the old toast table, but not for
1323 * any values that we toast which were previously not toasted.)
1324 *
1325 * This would not work with CONCURRENTLY because we may need to delete
1326 * TOASTed tuples from the new heap. With this hack, we'd delete them
1327 * from the old heap.
1328 */
1329 NewHeap->rd_toastoid = OldHeap->rd_rel->reltoastrelid;
1330 }
1331 else
1332 *pSwapToastByContent = false;
1333
1334 /*
1335 * Compute xids used to freeze and weed out dead tuples and multixacts.
1336 * Since we're going to rewrite the whole table anyway, there's no reason
1337 * not to be aggressive about this.
1338 */
1339 memset(&params, 0, sizeof(VacuumParams));
1340 vacuum_get_cutoffs(OldHeap, &params, &cutoffs);
1341
1342 /*
1343 * FreezeXid will become the table's new relfrozenxid, and that mustn't go
1344 * backwards, so take the max.
1345 */
1346 {
1347 TransactionId relfrozenxid = OldHeap->rd_rel->relfrozenxid;
1348
1351 cutoffs.FreezeLimit = relfrozenxid;
1352 }
1353
1354 /*
1355 * MultiXactCutoff, similarly, shouldn't go backwards either.
1356 */
1357 {
1358 MultiXactId relminmxid = OldHeap->rd_rel->relminmxid;
1359
1362 cutoffs.MultiXactCutoff = relminmxid;
1363 }
1364
1365 /*
1366 * Decide whether to use an indexscan or seqscan-and-optional-sort to scan
1367 * the OldHeap. We know how to use a sort to duplicate the ordering of a
1368 * btree index, and will use seqscan-and-sort for that case if the planner
1369 * tells us it's cheaper. Otherwise, always indexscan if an index is
1370 * provided, else plain seqscan.
1371 */
1372 if (OldIndex != NULL && OldIndex->rd_rel->relam == BTREE_AM_OID)
1375 else
1376 use_sort = false;
1377
1378 /* Log what we're doing */
1379 if (OldIndex != NULL && !use_sort)
1380 ereport(elevel,
1381 errmsg("repacking \"%s.%s\" using index scan on \"%s\"",
1382 nspname,
1385 else if (use_sort)
1386 ereport(elevel,
1387 errmsg("repacking \"%s.%s\" using sequential scan and sort",
1388 nspname,
1390 else
1391 ereport(elevel,
1392 errmsg("repacking \"%s.%s\" in physical order",
1393 nspname,
1395
1396 /*
1397 * Hand off the actual copying to AM specific function, the generic code
1398 * cannot know how to deal with visibility across AMs. Note that this
1399 * routine is allowed to set FreezeXid / MultiXactCutoff to different
1400 * values (e.g. because the AM doesn't use freezing).
1401 */
1403 cutoffs.OldestXmin, snapshot,
1404 &cutoffs.FreezeLimit,
1405 &cutoffs.MultiXactCutoff,
1406 &num_tuples, &tups_vacuumed,
1408
1409 /* return selected values to caller, get set as relfrozenxid/minmxid */
1410 *pFreezeXid = cutoffs.FreezeLimit;
1411 *pCutoffMulti = cutoffs.MultiXactCutoff;
1412
1413 /*
1414 * Reset rd_toastoid just to be tidy --- it shouldn't be looked at again.
1415 * In the CONCURRENTLY case, we need to set it again before applying the
1416 * concurrent changes.
1417 */
1418 NewHeap->rd_toastoid = InvalidOid;
1419
1421
1422 /* Log what we did */
1423 ereport(elevel,
1424 (errmsg("\"%s.%s\": found %.0f removable, %.0f nonremovable row versions in %u pages",
1425 nspname,
1427 tups_vacuumed, num_tuples,
1429 errdetail("%.0f dead row versions cannot be removed yet.\n"
1430 "%s.",
1432 pg_rusage_show(&ru0))));
1433
1434 /* Update pg_class to reflect the correct values of pages and tuples. */
1436
1440 elog(ERROR, "cache lookup failed for relation %u",
1443
1444 relform->relpages = num_pages;
1445 relform->reltuples = num_tuples;
1446
1447 /* Don't update the stats for pg_class. See swap_relation_files. */
1450 else
1452
1453 /* Clean up. */
1456
1457 /* Make the update visible */
1459}
1460
1461/*
1462 * Swap the physical files of two given relations.
1463 *
1464 * We swap the physical identity (reltablespace, relfilenumber) while keeping
1465 * the same logical identities of the two relations. relpersistence is also
1466 * swapped, which is critical since it determines where buffers live for each
1467 * relation.
1468 *
1469 * We can swap associated TOAST data in either of two ways: recursively swap
1470 * the physical content of the toast tables (and their indexes), or swap the
1471 * TOAST links in the given relations' pg_class entries. The former is needed
1472 * to manage rewrites of shared catalogs (where we cannot change the pg_class
1473 * links) while the latter is the only way to handle cases in which a toast
1474 * table is added or removed altogether.
1475 *
1476 * Additionally, the first relation is marked with relfrozenxid set to
1477 * frozenXid. It seems a bit ugly to have this here, but the caller would
1478 * have to do it anyway, so having it here saves a heap_update. Note: in
1479 * the swap-toast-links case, we assume we don't need to change the toast
1480 * table's relfrozenxid: the new version of the toast table should already
1481 * have relfrozenxid set to RecentXmin, which is good enough.
1482 *
1483 * Lastly, if r2 and its toast table and toast index (if any) are mapped,
1484 * their OIDs are emitted into mapped_tables[]. This is hacky but beats
1485 * having to look the information up again later in finish_heap_swap.
1486 */
1487static void
1490 bool is_internal,
1494{
1497 reltup2;
1499 relform2;
1503 char swptmpchr;
1504 Oid relam1,
1505 relam2;
1506
1507 /* We need writable copies of both pg_class tuples. */
1509
1512 elog(ERROR, "cache lookup failed for relation %u", r1);
1514
1517 elog(ERROR, "cache lookup failed for relation %u", r2);
1519
1520 relfilenumber1 = relform1->relfilenode;
1521 relfilenumber2 = relform2->relfilenode;
1522 relam1 = relform1->relam;
1523 relam2 = relform2->relam;
1524
1527 {
1528 /*
1529 * Normal non-mapped relations: swap relfilenumbers, reltablespaces,
1530 * relpersistence
1531 */
1533
1534 swaptemp = relform1->relfilenode;
1535 relform1->relfilenode = relform2->relfilenode;
1536 relform2->relfilenode = swaptemp;
1537
1538 swaptemp = relform1->reltablespace;
1539 relform1->reltablespace = relform2->reltablespace;
1540 relform2->reltablespace = swaptemp;
1541
1542 swaptemp = relform1->relam;
1543 relform1->relam = relform2->relam;
1544 relform2->relam = swaptemp;
1545
1546 swptmpchr = relform1->relpersistence;
1547 relform1->relpersistence = relform2->relpersistence;
1548 relform2->relpersistence = swptmpchr;
1549
1550 /* Also swap toast links, if we're swapping by links */
1552 {
1553 swaptemp = relform1->reltoastrelid;
1554 relform1->reltoastrelid = relform2->reltoastrelid;
1555 relform2->reltoastrelid = swaptemp;
1556 }
1557 }
1558 else
1559 {
1560 /*
1561 * Mapped-relation case. Here we have to swap the relation mappings
1562 * instead of modifying the pg_class columns. Both must be mapped.
1563 */
1566 elog(ERROR, "cannot swap mapped relation \"%s\" with non-mapped relation",
1567 NameStr(relform1->relname));
1568
1569 /*
1570 * We can't change the tablespace nor persistence of a mapped rel, and
1571 * we can't handle toast link swapping for one either, because we must
1572 * not apply any critical changes to its pg_class row. These cases
1573 * should be prevented by upstream permissions tests, so these checks
1574 * are non-user-facing emergency backstop.
1575 */
1576 if (relform1->reltablespace != relform2->reltablespace)
1577 elog(ERROR, "cannot change tablespace of mapped relation \"%s\"",
1578 NameStr(relform1->relname));
1579 if (relform1->relpersistence != relform2->relpersistence)
1580 elog(ERROR, "cannot change persistence of mapped relation \"%s\"",
1581 NameStr(relform1->relname));
1582 if (relform1->relam != relform2->relam)
1583 elog(ERROR, "cannot change access method of mapped relation \"%s\"",
1584 NameStr(relform1->relname));
1585 if (!swap_toast_by_content &&
1586 (relform1->reltoastrelid || relform2->reltoastrelid))
1587 elog(ERROR, "cannot swap toast by links for mapped relation \"%s\"",
1588 NameStr(relform1->relname));
1589
1590 /*
1591 * Fetch the mappings --- shouldn't fail, but be paranoid
1592 */
1595 elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
1596 NameStr(relform1->relname), r1);
1599 elog(ERROR, "could not find relation mapping for relation \"%s\", OID %u",
1600 NameStr(relform2->relname), r2);
1601
1602 /*
1603 * Send replacement mappings to relmapper. Note these won't actually
1604 * take effect until CommandCounterIncrement.
1605 */
1606 RelationMapUpdateMap(r1, relfilenumber2, relform1->relisshared, false);
1607 RelationMapUpdateMap(r2, relfilenumber1, relform2->relisshared, false);
1608
1609 /* Pass OIDs of mapped r2 tables back to caller */
1610 *mapped_tables++ = r2;
1611 }
1612
1613 /*
1614 * Recognize that rel1's relfilenumber (swapped from rel2) is new in this
1615 * subtransaction. The rel2 storage (swapped from rel1) may or may not be
1616 * new.
1617 */
1618 {
1619 Relation rel1,
1620 rel2;
1621
1624 rel2->rd_createSubid = rel1->rd_createSubid;
1625 rel2->rd_newRelfilelocatorSubid = rel1->rd_newRelfilelocatorSubid;
1626 rel2->rd_firstRelfilelocatorSubid = rel1->rd_firstRelfilelocatorSubid;
1630 }
1631
1632 /*
1633 * In the case of a shared catalog, these next few steps will only affect
1634 * our own database's pg_class row; but that's okay, because they are all
1635 * noncritical updates. That's also an important fact for the case of a
1636 * mapped catalog, because it's possible that we'll commit the map change
1637 * and then fail to commit the pg_class update.
1638 */
1639
1640 /* set rel1's frozen Xid and minimum MultiXid */
1641 if (relform1->relkind != RELKIND_INDEX)
1642 {
1645 relform1->relfrozenxid = frozenXid;
1646 relform1->relminmxid = cutoffMulti;
1647 }
1648
1649 /* swap size statistics too, since new rel has freshly-updated stats */
1650 {
1655
1656 swap_pages = relform1->relpages;
1657 relform1->relpages = relform2->relpages;
1658 relform2->relpages = swap_pages;
1659
1660 swap_tuples = relform1->reltuples;
1661 relform1->reltuples = relform2->reltuples;
1662 relform2->reltuples = swap_tuples;
1663
1664 swap_allvisible = relform1->relallvisible;
1665 relform1->relallvisible = relform2->relallvisible;
1666 relform2->relallvisible = swap_allvisible;
1667
1668 swap_allfrozen = relform1->relallfrozen;
1669 relform1->relallfrozen = relform2->relallfrozen;
1670 relform2->relallfrozen = swap_allfrozen;
1671 }
1672
1673 /*
1674 * Update the tuples in pg_class --- unless the target relation of the
1675 * swap is pg_class itself. In that case, there is zero point in making
1676 * changes because we'd be updating the old data that we're about to throw
1677 * away. Because the real work being done here for a mapped relation is
1678 * just to change the relation map settings, it's all right to not update
1679 * the pg_class rows in this case. The most important changes will instead
1680 * performed later, in finish_heap_swap() itself.
1681 */
1682 if (!target_is_pg_class)
1683 {
1685
1688 indstate);
1690 indstate);
1692 }
1693 else
1694 {
1695 /* no update ... but we do still need relcache inval */
1698 }
1699
1700 /*
1701 * Now that pg_class has been updated with its relevant information for
1702 * the swap, update the dependency of the relations to point to their new
1703 * table AM, if it has changed.
1704 */
1705 if (relam1 != relam2)
1706 {
1708 r1,
1710 relam1,
1711 relam2) != 1)
1712 elog(ERROR, "could not change access method dependency for relation \"%s.%s\"",
1714 get_rel_name(r1));
1716 r2,
1718 relam2,
1719 relam1) != 1)
1720 elog(ERROR, "could not change access method dependency for relation \"%s.%s\"",
1722 get_rel_name(r2));
1723 }
1724
1725 /*
1726 * Post alter hook for modified relations. The change to r2 is always
1727 * internal, but r1 depends on the invocation context.
1728 */
1730 InvalidOid, is_internal);
1732 InvalidOid, true);
1733
1734 /*
1735 * If we have toast tables associated with the relations being swapped,
1736 * deal with them too.
1737 */
1738 if (relform1->reltoastrelid || relform2->reltoastrelid)
1739 {
1741 {
1742 if (relform1->reltoastrelid && relform2->reltoastrelid)
1743 {
1744 /* Recursively swap the contents of the toast tables */
1745 swap_relation_files(relform1->reltoastrelid,
1746 relform2->reltoastrelid,
1749 is_internal,
1750 frozenXid,
1753 }
1754 else
1755 {
1756 /* caller messed up */
1757 elog(ERROR, "cannot swap toast files by content when there's only one");
1758 }
1759 }
1760 else
1761 {
1762 /*
1763 * We swapped the ownership links, so we need to change dependency
1764 * data to match.
1765 *
1766 * NOTE: it is possible that only one table has a toast table.
1767 *
1768 * NOTE: at present, a TOAST table's only dependency is the one on
1769 * its owning table. If more are ever created, we'd need to use
1770 * something more selective than deleteDependencyRecordsFor() to
1771 * get rid of just the link we want.
1772 */
1775 long count;
1776
1777 /*
1778 * We disallow this case for system catalogs, to avoid the
1779 * possibility that the catalog we're rebuilding is one of the
1780 * ones the dependency changes would change. It's too late to be
1781 * making any data changes to the target catalog.
1782 */
1784 elog(ERROR, "cannot swap toast files by links for system catalogs");
1785
1786 /* Delete old dependencies */
1787 if (relform1->reltoastrelid)
1788 {
1790 relform1->reltoastrelid,
1791 false);
1792 if (count != 1)
1793 elog(ERROR, "expected one dependency record for TOAST table, found %ld",
1794 count);
1795 }
1796 if (relform2->reltoastrelid)
1797 {
1799 relform2->reltoastrelid,
1800 false);
1801 if (count != 1)
1802 elog(ERROR, "expected one dependency record for TOAST table, found %ld",
1803 count);
1804 }
1805
1806 /* Register new dependencies */
1808 baseobject.objectSubId = 0;
1810 toastobject.objectSubId = 0;
1811
1812 if (relform1->reltoastrelid)
1813 {
1814 baseobject.objectId = r1;
1815 toastobject.objectId = relform1->reltoastrelid;
1818 }
1819
1820 if (relform2->reltoastrelid)
1821 {
1822 baseobject.objectId = r2;
1823 toastobject.objectId = relform2->reltoastrelid;
1826 }
1827 }
1828 }
1829
1830 /*
1831 * If we're swapping two toast tables by content, do the same for their
1832 * valid index. The swap can actually be safely done only if the relations
1833 * have indexes.
1834 */
1836 relform1->relkind == RELKIND_TOASTVALUE &&
1837 relform2->relkind == RELKIND_TOASTVALUE)
1838 {
1841
1842 /* Get valid index for each relation */
1847
1852 is_internal,
1856 }
1857
1858 /* Clean up. */
1861
1863}
1864
1865/*
1866 * Remove the transient table that was built by make_new_heap, and finish
1867 * cleaning up (including rebuilding all indexes on the old heap).
1868 */
1869void
1871 bool is_system_catalog,
1873 bool check_constraints,
1874 bool is_internal,
1875 bool reindex,
1878 char newrelpersistence)
1879{
1880 ObjectAddress object;
1881 Oid mapped_tables[4];
1882 int i;
1883
1884 /* Report that we are now swapping relation files */
1887
1888 /* Zero out possible results from swapped_relation_files */
1889 memset(mapped_tables, 0, sizeof(mapped_tables));
1890
1891 /*
1892 * Swap the contents of the heap relations (including any toast tables).
1893 * Also set old heap's relfrozenxid to frozenXid.
1894 */
1897 swap_toast_by_content, is_internal,
1899
1900 /*
1901 * If it's a system catalog, queue a sinval message to flush all catcaches
1902 * on the catalog when we reach CommandCounterIncrement.
1903 */
1906
1907 if (reindex)
1908 {
1909 int reindex_flags;
1911
1912 /*
1913 * Rebuild each index on the relation (but not the toast table, which
1914 * is all-new at this point). It is important to do this before the
1915 * DROP step because if we are processing a system catalog that will
1916 * be used during DROP, we want to have its indexes available. There
1917 * is no advantage to the other order anyway because this is all
1918 * transactional, so no chance to reclaim disk space before commit. We
1919 * do not need a final CommandCounterIncrement() because
1920 * reindex_relation does it.
1921 *
1922 * Note: because index_build is called via reindex_relation, it will
1923 * never set indcheckxmin true for the indexes. This is OK even
1924 * though in some sense we are building new indexes rather than
1925 * rebuilding existing ones, because the new heap won't contain any
1926 * HOT chains at all, let alone broken ones, so it can't be necessary
1927 * to set indcheckxmin.
1928 */
1932
1933 /*
1934 * Ensure that the indexes have the same persistence as the parent
1935 * relation.
1936 */
1937 if (newrelpersistence == RELPERSISTENCE_UNLOGGED)
1939 else if (newrelpersistence == RELPERSISTENCE_PERMANENT)
1941
1942 /* Report that we are now reindexing relations */
1945
1947 }
1948
1949 /* Report that we are now doing clean up */
1952
1953 /*
1954 * If the relation being rebuilt is pg_class, swap_relation_files()
1955 * couldn't update pg_class's own pg_class entry (check comments in
1956 * swap_relation_files()), thus relfrozenxid was not updated. That's
1957 * annoying because a potential reason for doing a VACUUM FULL is a
1958 * imminent or actual anti-wraparound shutdown. So, now that we can
1959 * access the new relation using its indices, update relfrozenxid.
1960 * pg_class doesn't have a toast relation, so we don't need to update the
1961 * corresponding toast relation. Not that there's little point moving all
1962 * relfrozenxid updates here since swap_relation_files() needs to write to
1963 * pg_class for non-mapped relations anyway.
1964 */
1966 {
1970
1972
1975 elog(ERROR, "cache lookup failed for relation %u", OIDOldHeap);
1977
1978 relform->relfrozenxid = frozenXid;
1979 relform->relminmxid = cutoffMulti;
1980
1982
1984 }
1985
1986 /* Destroy new heap with old filenumber */
1987 object.classId = RelationRelationId;
1988 object.objectId = OIDNewHeap;
1989 object.objectSubId = 0;
1990
1991 if (!reindex)
1992 {
1993 /*
1994 * Make sure the changes in pg_class are visible. This is especially
1995 * important if !swap_toast_by_content, so that the correct TOAST
1996 * relation is dropped. (reindex_relation() above did not help in this
1997 * case))
1998 */
2000 }
2001
2002 /*
2003 * The new relation is local to our transaction and we know nothing
2004 * depends on it, so DROP_RESTRICT should be OK.
2005 */
2007
2008 /* performDeletion does CommandCounterIncrement at end */
2009
2010 /*
2011 * Now we must remove any relation mapping entries that we set up for the
2012 * transient table, as well as its toast table and toast index if any. If
2013 * we fail to do this before commit, the relmapper will complain about new
2014 * permanent map entries being added post-bootstrap.
2015 */
2016 for (i = 0; OidIsValid(mapped_tables[i]); i++)
2018
2019 /*
2020 * At this point, everything is kosher except that, if we did toast swap
2021 * by links, the toast table's name corresponds to the transient table.
2022 * The name is irrelevant to the backend because it's referenced by OID,
2023 * but users looking at the catalogs could be confused. Rename it to
2024 * prevent this problem.
2025 *
2026 * Note no lock required on the relation, because we already hold an
2027 * exclusive lock on it.
2028 */
2030 {
2032
2034 if (OidIsValid(newrel->rd_rel->reltoastrelid))
2035 {
2036 Oid toastidx;
2038
2039 /* Get the associated valid index to be renamed */
2040 toastidx = toast_get_valid_index(newrel->rd_rel->reltoastrelid,
2042
2043 /* rename the toast table ... */
2044 snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u",
2045 OIDOldHeap);
2046 RenameRelationInternal(newrel->rd_rel->reltoastrelid,
2047 NewToastName, true, false);
2048
2049 /* ... and its valid index too. */
2050 snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u_index",
2051 OIDOldHeap);
2052
2054 NewToastName, true, true);
2055
2056 /*
2057 * Reset the relrewrite for the toast. The command-counter
2058 * increment is required here as we are about to update the tuple
2059 * that is updated as part of RenameRelationInternal.
2060 */
2062 ResetRelRewrite(newrel->rd_rel->reltoastrelid);
2063 }
2065 }
2066
2067 /* if it's not a catalog table, clear any missing attribute settings */
2068 if (!is_system_catalog)
2069 {
2071
2075 }
2076}
2077
2078/*
2079 * Determine which relations to process, when REPACK/CLUSTER is called
2080 * without specifying a table name. The exact process depends on whether
2081 * USING INDEX was given or not, and in any case we only return tables and
2082 * materialized views that the current user has privileges to repack/cluster.
2083 *
2084 * If USING INDEX was given, we scan pg_index to find those that have
2085 * indisclustered set; if it was not given, scan pg_class and return all
2086 * tables.
2087 *
2088 * Return it as a list of RelToCluster in the given memory context.
2089 */
2090static List *
2092{
2094 TableScanDesc scan;
2095 HeapTuple tuple;
2096 List *rtcs = NIL;
2097
2098 if (usingindex)
2099 {
2100 ScanKeyData entry;
2101
2102 /*
2103 * For USING INDEX, scan pg_index to find those with indisclustered.
2104 */
2106 ScanKeyInit(&entry,
2109 BoolGetDatum(true));
2110 scan = table_beginscan_catalog(catalog, 1, &entry);
2111 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2112 {
2118
2119 index = (Form_pg_index) GETSTRUCT(tuple);
2120
2121 /*
2122 * Try to obtain a light lock on the index's table, to ensure it
2123 * doesn't go away while we collect the list. If we cannot, just
2124 * disregard it. Be sure to release this if we ultimately decide
2125 * not to process the table!
2126 */
2128 continue;
2129
2130 /* Verify that the table still exists; skip if not */
2133 {
2135 continue;
2136 }
2138
2139 /* Skip temp relations belonging to other sessions */
2140 if (classForm->relpersistence == RELPERSISTENCE_TEMP &&
2141 !isTempOrTempToastNamespace(classForm->relnamespace))
2142 {
2145 continue;
2146 }
2147
2149
2150 /* noisily skip rels which the user can't process */
2151 if (!repack_is_permitted_for_relation(cmd, index->indrelid,
2152 GetUserId()))
2153 {
2155 continue;
2156 }
2157
2158 /* Use a permanent memory context for the result list */
2161 rtc->tableOid = index->indrelid;
2162 rtc->indexOid = index->indexrelid;
2163 rtcs = lappend(rtcs, rtc);
2165 }
2166 }
2167 else
2168 {
2171
2172 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2173 {
2175 Form_pg_class class;
2177
2178 class = (Form_pg_class) GETSTRUCT(tuple);
2179
2180 /*
2181 * Try to obtain a light lock on the table, to ensure it doesn't
2182 * go away while we collect the list. If we cannot, just
2183 * disregard the table. Be sure to release this if we ultimately
2184 * decide not to process the table!
2185 */
2187 continue;
2188
2189 /* Verify that the table still exists */
2191 {
2193 continue;
2194 }
2195
2196 /* Can only process plain tables and matviews */
2197 if (class->relkind != RELKIND_RELATION &&
2198 class->relkind != RELKIND_MATVIEW)
2199 {
2201 continue;
2202 }
2203
2204 /* Skip temp relations belonging to other sessions */
2205 if (class->relpersistence == RELPERSISTENCE_TEMP &&
2206 !isTempOrTempToastNamespace(class->relnamespace))
2207 {
2209 continue;
2210 }
2211
2212 /* noisily skip rels which the user can't process */
2214 GetUserId()))
2215 {
2217 continue;
2218 }
2219
2220 /* Use a permanent memory context for the result list */
2223 rtc->tableOid = class->oid;
2224 rtc->indexOid = InvalidOid;
2225 rtcs = lappend(rtcs, rtc);
2227 }
2228 }
2229
2230 table_endscan(scan);
2232
2233 return rtcs;
2234}
2235
2236/*
2237 * Given a partitioned table or its index, return a list of RelToCluster for
2238 * all the leaf child tables/indexes.
2239 *
2240 * 'rel_is_index' tells whether 'relid' is that of an index (true) or of the
2241 * owning relation.
2242 */
2243static List *
2246{
2247 List *inhoids;
2248 List *rtcs = NIL;
2249
2250 /*
2251 * Do not lock the children until they're processed. Note that we do hold
2252 * a lock on the parent partitioned table.
2253 */
2256 {
2257 Oid table_oid,
2258 index_oid;
2261
2262 if (rel_is_index)
2263 {
2264 /* consider only leaf indexes */
2266 continue;
2267
2270 }
2271 else
2272 {
2273 /* consider only leaf relations */
2275 continue;
2276
2279 }
2280
2281 /*
2282 * It's possible that the user does not have privileges to CLUSTER the
2283 * leaf partition despite having them on the partitioned table. Skip
2284 * if so.
2285 */
2287 continue;
2288
2289 /* Use a permanent memory context for the result list */
2292 rtc->tableOid = table_oid;
2293 rtc->indexOid = index_oid;
2294 rtcs = lappend(rtcs, rtc);
2296 }
2297
2298 return rtcs;
2299}
2300
2301
2302/*
2303 * Return whether userid has privileges to REPACK relid. If not, this
2304 * function emits a WARNING.
2305 */
2306static bool
2308{
2310
2311 if (pg_class_aclcheck(relid, userid, ACL_MAINTAIN) == ACLCHECK_OK)
2312 return true;
2313
2315 errmsg("permission denied to execute %s on \"%s\", skipping it",
2317 get_rel_name(relid)));
2318
2319 return false;
2320}
2321
2322
2323/*
2324 * Given a RepackStmt with an indicated relation name, resolve the relation
2325 * name, obtain lock on it, then determine what to do based on the relation
2326 * type: if it's table and not partitioned, repack it as indicated (using an
2327 * existing clustered index, or following the given one), and return NULL.
2328 *
2329 * On the other hand, if the table is partitioned, do nothing further and
2330 * instead return the opened and locked relcache entry, so that caller can
2331 * process the partitions using the multiple-table handling code. In this
2332 * case, if an index name is given, it's up to the caller to resolve it.
2333 */
2334static Relation
2336 ClusterParams *params)
2337{
2338 Relation rel;
2339 Oid tableOid;
2340
2341 Assert(stmt->relation != NULL);
2342 Assert(stmt->command == REPACK_COMMAND_CLUSTER ||
2343 stmt->command == REPACK_COMMAND_REPACK);
2344
2345 /*
2346 * Make sure ANALYZE is specified if a column list is present.
2347 */
2348 if ((params->options & CLUOPT_ANALYZE) == 0 && stmt->relation->va_cols != NIL)
2349 ereport(ERROR,
2351 errmsg("ANALYZE option must be specified when a column list is provided"));
2352
2353 /* Find, lock, and check permissions on the table. */
2354 tableOid = RangeVarGetRelidExtended(stmt->relation->relation,
2355 lockmode,
2356 0,
2358 NULL);
2359 rel = table_open(tableOid, NoLock);
2360
2361 /*
2362 * Reject clustering a remote temp table ... their local buffer manager is
2363 * not going to cope.
2364 */
2365 if (RELATION_IS_OTHER_TEMP(rel))
2366 ereport(ERROR,
2368 /*- translator: first %s is name of a SQL command, eg. REPACK */
2369 errmsg("cannot execute %s on temporary tables of other sessions",
2370 RepackCommandAsString(stmt->command)));
2371
2372 /*
2373 * For partitioned tables, let caller handle this. Otherwise, process it
2374 * here and we're done.
2375 */
2376 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2377 return rel;
2378 else
2379 {
2380 Oid indexOid = InvalidOid;
2381
2382 indexOid = determine_clustered_index(rel, stmt->usingindex,
2383 stmt->indexname);
2384 if (OidIsValid(indexOid))
2385 check_index_is_clusterable(rel, indexOid, lockmode);
2386
2387 cluster_rel(stmt->command, rel, indexOid, params, isTopLevel);
2388
2389 /*
2390 * Do an analyze, if requested. We close the transaction and start a
2391 * new one, so that we don't hold the stronger lock for longer than
2392 * needed.
2393 */
2394 if (params->options & CLUOPT_ANALYZE)
2395 {
2397
2400
2403
2404 vac_params.options |= VACOPT_ANALYZE;
2405 if (params->options & CLUOPT_VERBOSE)
2406 vac_params.options |= VACOPT_VERBOSE;
2407 analyze_rel(tableOid, NULL, &vac_params,
2408 stmt->relation->va_cols, true, NULL);
2411 }
2412
2413 return NULL;
2414 }
2415}
2416
2417/*
2418 * Given a relation and the usingindex/indexname options in a
2419 * REPACK USING INDEX or CLUSTER command, return the OID of the
2420 * index to use for clustering the table.
2421 *
2422 * Caller must hold lock on the relation so that the set of indexes
2423 * doesn't change, and must call check_index_is_clusterable.
2424 */
2425static Oid
2426determine_clustered_index(Relation rel, bool usingindex, const char *indexname)
2427{
2428 Oid indexOid;
2429
2430 if (indexname == NULL && usingindex)
2431 {
2432 /*
2433 * If USING INDEX with no name is given, find a clustered index, or
2434 * error out if none.
2435 */
2436 indexOid = InvalidOid;
2438 {
2440 {
2441 indexOid = idxoid;
2442 break;
2443 }
2444 }
2445
2446 if (!OidIsValid(indexOid))
2447 ereport(ERROR,
2449 errmsg("there is no previously clustered index for table \"%s\"",
2451 }
2452 else if (indexname != NULL)
2453 {
2454 /* An index was specified; obtain its OID. */
2455 indexOid = get_relname_relid(indexname, rel->rd_rel->relnamespace);
2456 if (!OidIsValid(indexOid))
2457 ereport(ERROR,
2459 errmsg("index \"%s\" for table \"%s\" does not exist",
2460 indexname, RelationGetRelationName(rel)));
2461 }
2462 else
2463 indexOid = InvalidOid;
2464
2465 return indexOid;
2466}
2467
2468static const char *
2470{
2471 switch (cmd)
2472 {
2474 return "REPACK";
2476 return "VACUUM";
2478 return "CLUSTER";
2479 }
2480 return "???"; /* keep compiler quiet */
2481}
2482
2483/*
2484 * Apply all the changes stored in 'file'.
2485 */
2486static void
2488{
2489 ConcurrentChangeKind kind = '\0';
2490 Relation rel = chgcxt->cc_rel;
2494 bool have_old_tuple = false;
2496
2498 &TTSOpsVirtual);
2502 &TTSOpsVirtual);
2503
2505
2506 while (true)
2507 {
2508 size_t nread;
2510
2512
2513 nread = BufFileReadMaybeEOF(file, &kind, 1, true);
2514 if (nread == 0) /* done with the file? */
2515 break;
2516
2517 /*
2518 * If this is the old tuple for an update, read it into the tuple slot
2519 * and go to the next one. The update itself will be executed on the
2520 * next iteration, when we receive the NEW tuple.
2521 */
2522 if (kind == CHANGE_UPDATE_OLD)
2523 {
2524 restore_tuple(file, rel, old_update_tuple);
2525 have_old_tuple = true;
2526 continue;
2527 }
2528
2529 /*
2530 * Just before an UPDATE or DELETE, we must update the command
2531 * counter, because the change could refer to a tuple that we have
2532 * just inserted; and before an INSERT, we have to do this also if the
2533 * previous command was either update or delete.
2534 *
2535 * With this approach we don't spend so many CCIs for long strings of
2536 * only INSERTs, which can't affect one another.
2537 */
2538 if (kind == CHANGE_UPDATE_NEW || kind == CHANGE_DELETE ||
2539 (kind == CHANGE_INSERT && (prevkind == CHANGE_UPDATE_NEW ||
2541 {
2544 }
2545
2546 /*
2547 * Now restore the tuple into the slot and execute the change.
2548 */
2549 restore_tuple(file, rel, spilled_tuple);
2550
2551 if (kind == CHANGE_INSERT)
2552 {
2554 }
2555 else if (kind == CHANGE_DELETE)
2556 {
2557 bool found;
2558
2559 /* Find the tuple to be deleted */
2561 if (!found)
2562 elog(ERROR, "failed to find target tuple");
2564 }
2565 else if (kind == CHANGE_UPDATE_NEW)
2566 {
2567 TupleTableSlot *key;
2568 bool found;
2569
2570 if (have_old_tuple)
2571 key = old_update_tuple;
2572 else
2573 key = spilled_tuple;
2574
2575 /* Find the tuple to be updated or deleted. */
2576 found = find_target_tuple(rel, chgcxt, key, ondisk_tuple);
2577 if (!found)
2578 elog(ERROR, "failed to find target tuple");
2579
2580 /*
2581 * If 'tup' contains TOAST pointers, they point to the old
2582 * relation's toast. Copy the corresponding TOAST pointers for the
2583 * new relation from the existing tuple. (The fact that we
2584 * received a TOAST pointer here implies that the attribute hasn't
2585 * changed.)
2586 */
2588
2590
2592 have_old_tuple = false;
2593 }
2594 else
2595 elog(ERROR, "unrecognized kind of change: %d", kind);
2596
2597 ResetPerTupleExprContext(chgcxt->cc_estate);
2598 }
2599
2600 /* Cleanup. */
2604
2606}
2607
2608/*
2609 * Apply an insert from the spill of concurrent changes to the new copy of the
2610 * table.
2611 */
2612static void
2615{
2616 /* Put the tuple in the table, but make sure it won't be decoded */
2617 table_tuple_insert(rel, slot, GetCurrentCommandId(true),
2619
2620 /* Update indexes with this new tuple. */
2622 chgcxt->cc_estate,
2623 0,
2624 slot,
2625 NIL, NULL);
2627}
2628
2629/*
2630 * Apply an update from the spill of concurrent changes to the new copy of the
2631 * table.
2632 */
2633static void
2637{
2638 LockTupleMode lockmode;
2639 TM_FailureData tmfd;
2641 TM_Result res;
2642
2643 /*
2644 * Carry out the update, skipping logical decoding for it.
2645 */
2646 res = table_tuple_update(rel, &(ondisk_tuple->tts_tid), spilled_tuple,
2647 GetCurrentCommandId(true),
2651 false,
2652 &tmfd, &lockmode, &update_indexes);
2653 if (res != TM_Ok)
2654 ereport(ERROR,
2655 errmsg("failed to apply concurrent UPDATE"));
2656
2657 if (update_indexes != TU_None)
2658 {
2659 uint32 flags = EIIT_IS_UPDATE;
2660
2662 flags |= EIIT_ONLY_SUMMARIZING;
2664 chgcxt->cc_estate,
2665 flags,
2667 NIL, NULL);
2668 }
2669
2671}
2672
2673static void
2675{
2676 TM_Result res;
2677 TM_FailureData tmfd;
2678
2679 /*
2680 * Delete tuple from the new heap, skipping logical decoding for it.
2681 */
2682 res = table_tuple_delete(rel, &(slot->tts_tid),
2683 GetCurrentCommandId(true),
2686 false,
2687 &tmfd);
2688
2689 if (res != TM_Ok)
2690 ereport(ERROR,
2691 errmsg("failed to apply concurrent DELETE"));
2692
2694}
2695
2696/*
2697 * Read tuple from file and put it in the input slot. All memory is allocated
2698 * in the current memory context; caller is responsible for freeing it as
2699 * appropriate.
2700 *
2701 * External attributes are stored in separate memory chunks, in order to avoid
2702 * exceeding MaxAllocSize - that could happen if the individual attributes are
2703 * smaller than MaxAllocSize but the whole tuple is bigger.
2704 */
2705static void
2707{
2708 uint32 t_len;
2709 HeapTuple tup;
2710 int natt_ext;
2711
2712 /* Read the tuple. */
2713 BufFileReadExact(file, &t_len, sizeof(t_len));
2714 tup = (HeapTuple) palloc(HEAPTUPLESIZE + t_len);
2715 tup->t_data = (HeapTupleHeader) ((char *) tup + HEAPTUPLESIZE);
2716 BufFileReadExact(file, tup->t_data, t_len);
2717 tup->t_len = t_len;
2718 ItemPointerSetInvalid(&tup->t_self);
2719 tup->t_tableOid = RelationGetRelid(relation);
2720
2721 /*
2722 * Put the tuple we read in a slot. This deforms it, so that we can hack
2723 * the external attributes in place.
2724 */
2725 ExecForceStoreHeapTuple(tup, slot, false);
2726
2727 /*
2728 * Next, read any attributes we stored separately into the tts_values
2729 * array elements expecting them, if any. This matches
2730 * repack_store_change.
2731 */
2732 BufFileReadExact(file, &natt_ext, sizeof(natt_ext));
2733 if (natt_ext > 0)
2734 {
2735 TupleDesc desc = slot->tts_tupleDescriptor;
2736
2737 for (int i = 0; i < desc->natts; i++)
2738 {
2740 varlena *varlen;
2742 void *value;
2743 Size varlensz;
2744
2745 if (attr->attisdropped || attr->attlen != -1)
2746 continue;
2747 if (slot_attisnull(slot, i + 1))
2748 continue;
2751 continue;
2752 slot_getsomeattrs(slot, i + 1);
2753
2756
2759 BufFileReadExact(file, (char *) value + VARHDRSZ, varlensz - VARHDRSZ);
2760
2762 natt_ext--;
2763 if (natt_ext < 0)
2764 ereport(ERROR,
2766 errmsg("insufficient number of attributes stored separately"));
2767 }
2768 }
2769}
2770
2771/*
2772 * Adjust 'dest' replacing any EXTERNAL_ONDISK toast pointers with the
2773 * corresponding ones from 'src'.
2774 */
2775static void
2777{
2778 TupleDesc desc = dest->tts_tupleDescriptor;
2779
2780 for (int i = 0; i < desc->natts; i++)
2781 {
2784
2785 if (attr->attisdropped)
2786 continue;
2787 if (attr->attlen != -1)
2788 continue;
2789 if (slot_attisnull(dest, i + 1))
2790 continue;
2791
2792 slot_getsomeattrs(dest, i + 1);
2793
2794 varlena_dst = (varlena *) DatumGetPointer(dest->tts_values[i]);
2796 continue;
2797 slot_getsomeattrs(src, i + 1);
2798
2799 dest->tts_values[i] = src->tts_values[i];
2800 }
2801}
2802
2803/*
2804 * Find the tuple to be updated or deleted by the given data change, whose
2805 * tuple has already been loaded into locator.
2806 *
2807 * If the tuple is found, put it in retrieved and return true. If the tuple is
2808 * not found, return false.
2809 */
2810static bool
2813{
2814 Form_pg_index idx = chgcxt->cc_ident_index->rd_index;
2815 IndexScanDesc scan;
2816 bool retval = false;
2817
2818 /*
2819 * Scan key is passed by caller, so it does not have to be constructed
2820 * multiple times. Key entries have all fields initialized, except for
2821 * sk_argument.
2822 *
2823 * Use the incoming tuple to finalize the scan key.
2824 */
2825 for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
2826 {
2827 ScanKey entry = &chgcxt->cc_ident_key[i];
2828 AttrNumber attno = idx->indkey.values[i];
2829
2830 entry->sk_argument = locator->tts_values[attno - 1];
2831 Assert(!locator->tts_isnull[attno - 1]);
2832 }
2833
2834 /* XXX no instrumentation for now */
2835 scan = index_beginscan(rel, chgcxt->cc_ident_index, GetActiveSnapshot(),
2836 NULL, chgcxt->cc_ident_key_nentries, 0, 0);
2837 index_rescan(scan, chgcxt->cc_ident_key, chgcxt->cc_ident_key_nentries, NULL, 0);
2839 {
2840 /* Be wary of temporal constraints */
2841 if (scan->xs_recheck && !identity_key_equal(chgcxt, locator, retrieved))
2842 {
2844 continue;
2845 }
2846
2847 retval = true;
2848 break;
2849 }
2850 index_endscan(scan);
2851
2852 return retval;
2853}
2854
2855/*
2856 * Check whether the candidate tuple matches the locator tuple on all replica
2857 * identity key columns, using the same equality operators as the identity
2858 * index scan. The locator tuple has already been loaded into cc_ident_key.
2859 *
2860 * This is needed to filter lossy index matches, such as GiST multirange scans
2861 * used for temporal constraints.
2862 */
2863static bool
2866{
2867 slot_getsomeattrs(locator, chgcxt->cc_last_key_attno);
2868 slot_getsomeattrs(candidate, chgcxt->cc_last_key_attno);
2869
2870 for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
2871 {
2872 ScanKey entry = &chgcxt->cc_ident_key[i];
2873 AttrNumber attno = chgcxt->cc_ident_index->rd_index->indkey.values[i];
2874
2875 Assert(attno > 0);
2876
2877 if (locator->tts_isnull[attno - 1] != candidate->tts_isnull[attno - 1])
2878 return false;
2879
2880 if (locator->tts_isnull[attno - 1])
2881 continue;
2882
2884 entry->sk_collation,
2885 candidate->tts_values[attno - 1],
2886 entry->sk_argument)))
2887 return false;
2888 }
2889
2890 return true;
2891}
2892
2893/*
2894 * Decode and apply concurrent changes, up to (and including) the record whose
2895 * LSN is 'end_of_wal'.
2896 *
2897 * XXX the names "process_concurrent_changes" and "apply_concurrent_changes"
2898 * are far too similar to each other.
2899 */
2900static void
2902{
2903 DecodingWorkerShared *shared;
2904 char fname[MAXPGPATH];
2905 BufFile *file;
2906
2909
2910 /* Ask the worker for the file. */
2912 SpinLockAcquire(&shared->mutex);
2913 shared->lsn_upto = end_of_wal;
2914 shared->done = done;
2915 SpinLockRelease(&shared->mutex);
2916
2917 /*
2918 * The worker needs to finish processing of the current WAL record. Even
2919 * if it's idle, it'll need to close the output file. Thus we're likely to
2920 * wait, so prepare for sleep.
2921 */
2923 for (;;)
2924 {
2925 int last_exported;
2926
2927 SpinLockAcquire(&shared->mutex);
2928 last_exported = shared->last_exported;
2929 SpinLockRelease(&shared->mutex);
2930
2931 /*
2932 * Has the worker exported the file we are waiting for?
2933 */
2934 if (last_exported == chgcxt->cc_file_seq)
2935 break;
2936
2938 }
2940
2941 /* Open the file. */
2942 DecodingWorkerFileName(fname, shared->relid, chgcxt->cc_file_seq);
2943 file = BufFileOpenFileSet(&shared->sfs.fs, fname, O_RDONLY, false);
2945
2946 BufFileClose(file);
2947
2948 /* Get ready for the next file. */
2949 chgcxt->cc_file_seq++;
2950}
2951
2952/*
2953 * Initialize the ChangeContext struct for the given relation, with
2954 * the given index as identity index.
2955 */
2956static void
2958 Relation relation, Oid ident_index_id)
2959{
2960 chgcxt->cc_rel = relation;
2961
2962 /* Only initialize fields needed by ExecInsertIndexTuples(). */
2963 chgcxt->cc_estate = CreateExecutorState();
2964
2965 chgcxt->cc_rri = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
2966 InitResultRelInfo(chgcxt->cc_rri, relation, 0, 0, 0);
2967 ExecOpenIndices(chgcxt->cc_rri, false);
2968
2969 /*
2970 * The table's relcache entry already has the relcache entry for the
2971 * identity index; find that.
2972 */
2973 chgcxt->cc_ident_index = NULL;
2974 for (int i = 0; i < chgcxt->cc_rri->ri_NumIndices; i++)
2975 {
2977
2978 ind_rel = chgcxt->cc_rri->ri_IndexRelationDescs[i];
2979 if (ind_rel->rd_id == ident_index_id)
2980 {
2981 chgcxt->cc_ident_index = ind_rel;
2982 break;
2983 }
2984 }
2985 if (chgcxt->cc_ident_index == NULL)
2986 elog(ERROR, "failed to find identity index");
2987
2988 /* Set up for scanning said identity index */
2989 {
2991
2992 indexForm = chgcxt->cc_ident_index->rd_index;
2993 chgcxt->cc_ident_key_nentries = indexForm->indnkeyatts;
2994 chgcxt->cc_ident_key = (ScanKey) palloc_array(ScanKeyData, indexForm->indnkeyatts);
2995 for (int i = 0; i < indexForm->indnkeyatts; i++)
2996 {
2997 ScanKey entry;
2998 Oid opfamily,
2999 opcintype,
3000 opno,
3001 opcode;
3003
3004 entry = &chgcxt->cc_ident_key[i];
3005
3006 opfamily = chgcxt->cc_ident_index->rd_opfamily[i];
3007 opcintype = chgcxt->cc_ident_index->rd_opcintype[i];
3009 chgcxt->cc_ident_index->rd_rel->relam,
3010 opfamily, false);
3012 elog(ERROR, "could not find equality strategy for index operator family %u for type %u",
3013 opfamily, opcintype);
3014 opno = get_opfamily_member(opfamily, opcintype, opcintype,
3015 eq_strategy);
3016 if (!OidIsValid(opno))
3017 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3018 eq_strategy, opcintype, opcintype, opfamily);
3019 opcode = get_opcode(opno);
3020 if (!OidIsValid(opcode))
3021 elog(ERROR, "missing oprcode for operator %u", opno);
3022
3023 /* Initialize everything but argument. */
3024 ScanKeyInit(entry,
3025 i + 1,
3026 eq_strategy, opcode,
3027 (Datum) 0);
3028 entry->sk_collation = chgcxt->cc_ident_index->rd_indcollation[i];
3029 }
3030 }
3031
3032 /* Determine the last column we must deform to read the identity */
3033 chgcxt->cc_last_key_attno = InvalidAttrNumber;
3034 for (int i = 0; i < chgcxt->cc_ident_key_nentries; i++)
3035 {
3036 AttrNumber attno = chgcxt->cc_ident_index->rd_index->indkey.values[i];
3037
3038 Assert(attno > 0);
3039 chgcxt->cc_last_key_attno = Max(chgcxt->cc_last_key_attno, attno);
3040 }
3041
3042 chgcxt->cc_file_seq = WORKER_FILE_SNAPSHOT + 1;
3043}
3044
3045/*
3046 * Free up resources taken by a ChangeContext.
3047 */
3048static void
3050{
3051 ExecCloseIndices(chgcxt->cc_rri);
3052 FreeExecutorState(chgcxt->cc_estate);
3053 /* XXX are these pfrees necessary? */
3054 pfree(chgcxt->cc_rri);
3055 pfree(chgcxt->cc_ident_key);
3056}
3057
3058/*
3059 * The final steps of rebuild_relation() for concurrent processing.
3060 *
3061 * On entry, NewHeap is locked in AccessExclusiveLock mode. OldHeap and its
3062 * clustering index (if one is passed) are still locked in a mode that allows
3063 * concurrent data changes. On exit, both tables and their indexes are closed,
3064 * but locked in AccessExclusiveLock mode.
3065 */
3066static void
3070{
3075 ListCell *lc,
3076 *lc2;
3077 char relpersistence;
3078 bool is_system_catalog;
3080 XLogRecPtr end_of_wal;
3081 List *indexrels;
3083
3086
3087 /*
3088 * Unlike the exclusive case, we build new indexes for the new relation
3089 * rather than swapping the storage and reindexing the old relation. The
3090 * point is that the index build can take some time, so we do it before we
3091 * get AccessExclusiveLock on the old heap and therefore we cannot swap
3092 * the heap storage yet.
3093 *
3094 * index_create() will lock the new indexes using AccessExclusiveLock - no
3095 * need to change that. At the same time, we use ShareUpdateExclusiveLock
3096 * to lock the existing indexes - that should be enough to prevent others
3097 * from changing them while we're repacking the relation. The lock on
3098 * table should prevent others from changing the index column list, but
3099 * might not be enough for commands like ALTER INDEX ... SET ... (Those
3100 * are not necessarily dangerous, but can make user confused if the
3101 * changes they do get lost due to REPACK.)
3102 */
3104
3105 /*
3106 * The identity index in the new relation appears in the same relative
3107 * position as the corresponding index in the old relation. Find it.
3108 */
3111 {
3112 if (identIdx == ind_old)
3113 {
3114 int pos = foreach_current_index(ind_old);
3115
3116 if (list_length(ind_oids_new) <= pos)
3117 elog(ERROR, "list of new indexes too short");
3119 break;
3120 }
3121 }
3123 elog(ERROR, "could not find index matching \"%s\" at the new relation",
3125
3126 /* Gather information to apply concurrent changes. */
3128
3129 /*
3130 * During testing, wait for another backend to perform concurrent data
3131 * changes which we will process below.
3132 */
3133 INJECTION_POINT("repack-concurrently-before-lock", NULL);
3134
3135 /*
3136 * Flush all WAL records inserted so far (possibly except for the last
3137 * incomplete page; see GetInsertRecPtr), to minimize the amount of data
3138 * we need to flush while holding exclusive lock on the source table.
3139 */
3141 end_of_wal = GetFlushRecPtr(NULL);
3142
3143 /*
3144 * Apply concurrent changes first time, to minimize the time we need to
3145 * hold AccessExclusiveLock. (Quite some amount of WAL could have been
3146 * written during the data copying and index creation.)
3147 */
3148 process_concurrent_changes(end_of_wal, &chgcxt, false);
3149
3150 /*
3151 * Acquire AccessExclusiveLock on the table, its TOAST relation (if there
3152 * is one), all its indexes, so that we can swap the files.
3153 */
3155
3156 /*
3157 * Lock all indexes now, not only the clustering one: all indexes need to
3158 * have their files swapped. While doing that, store their relation
3159 * references in a zero-terminated array, to handle predicate locks below.
3160 */
3161 indexrels = NIL;
3163 {
3165
3167
3168 /*
3169 * Some things about the index may have changed before we locked the
3170 * index, such as ALTER INDEX RENAME. We don't need to do anything
3171 * here to absorb those changes in the new index.
3172 */
3174 }
3175
3176 /*
3177 * Lock the OldHeap's TOAST relation exclusively - again, the lock is
3178 * needed to swap the files.
3179 */
3180 if (OidIsValid(OldHeap->rd_rel->reltoastrelid))
3181 LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
3182
3183 /*
3184 * Tuples and pages of the old heap will be gone, but the heap will stay.
3185 */
3188 {
3191 }
3193
3194 /*
3195 * Flush WAL again, to make sure that all changes committed while we were
3196 * waiting for the exclusive lock are available for decoding.
3197 */
3199 end_of_wal = GetFlushRecPtr(NULL);
3200
3201 /*
3202 * Apply the concurrent changes again. Indicate that the decoding worker
3203 * won't be needed anymore.
3204 */
3205 process_concurrent_changes(end_of_wal, &chgcxt, true);
3206
3207 /* Remember info about rel before closing OldHeap */
3208 relpersistence = OldHeap->rd_rel->relpersistence;
3210
3213
3214 /*
3215 * Even ShareUpdateExclusiveLock should have prevented others from
3216 * creating / dropping indexes (even using the CONCURRENTLY option), so we
3217 * do not need to check whether the lists match.
3218 */
3220 {
3223 Oid mapped_tables[4] = {0};
3224
3227 false, /* swap_toast_by_content */
3228 true,
3232
3233#ifdef USE_ASSERT_CHECKING
3234
3235 /*
3236 * Concurrent processing is not supported for system relations, so
3237 * there should be no mapped tables.
3238 */
3239 for (int i = 0; i < 4; i++)
3241#endif
3242 }
3243
3244 /* The new indexes must be visible for deletion. */
3246
3247 /* Close the old heap but keep lock until transaction commit. */
3249 /* Close the new heap. (We didn't have to open its indexes). */
3251
3252 /* Cleanup what we don't need anymore. (And close the identity index.) */
3254
3255 /*
3256 * Swap the relations and their TOAST relations and TOAST indexes. This
3257 * also drops the new relation and its indexes.
3258 *
3259 * (System catalogs are currently not supported.)
3260 */
3264 false, /* swap_toast_by_content */
3265 false,
3266 true,
3267 false, /* reindex */
3269 relpersistence);
3270}
3271
3272/*
3273 * Build indexes on NewHeap according to those on OldHeap.
3274 *
3275 * OldIndexes is the list of index OIDs on OldHeap. The contained indexes end
3276 * up locked using ShareUpdateExclusiveLock.
3277 *
3278 * A list of OIDs of the corresponding indexes created on NewHeap is
3279 * returned. The order of items does match, so we can use these arrays to swap
3280 * index storage.
3281 */
3282static List *
3314
3315/*
3316 * Create a transient copy of a constraint -- supported by a transient
3317 * copy of the index that supports the original constraint.
3318 *
3319 * When repacking a table that contains exclusion constraints, the executor
3320 * relies on these constraints being properly catalogued. These copies are
3321 * to support that.
3322 *
3323 * We don't need the constraints for anything else (the original constraints
3324 * will be there once repack completes), so we add pg_depend entries so that
3325 * the are dropped when the transient table is dropped.
3326 */
3327static void
3329{
3331 Relation rel;
3332 TupleDesc desc;
3333 SysScanDesc scan;
3334 HeapTuple tup;
3336
3339
3340 /*
3341 * Retrieve the constraints supported by the old index and create an
3342 * identical one that points to the new index.
3343 */
3347 ObjectIdGetDatum(old_index->rd_index->indrelid));
3349 NULL, 1, &skey);
3350 desc = RelationGetDescr(rel);
3351 while (HeapTupleIsValid(tup = systable_getnext(scan)))
3352 {
3354 Oid oid;
3356 bool nulls[Natts_pg_constraint] = {0};
3357 bool replaces[Natts_pg_constraint] = {0};
3360
3361 if (conform->conindid != RelationGetRelid(old_index))
3362 continue;
3363
3367 replaces[Anum_pg_constraint_oid - 1] = true;
3372
3373 new_tup = heap_modify_tuple(tup, desc, values, nulls, replaces);
3374
3375 /* Insert it into the catalog. */
3377
3378 /* Create a dependency so it's removed when we drop the new heap. */
3381 }
3382 systable_endscan(scan);
3383
3385
3387}
3388
3389/*
3390 * Try to start a background worker to perform logical decoding of data
3391 * changes applied to relation while REPACK CONCURRENTLY is copying its
3392 * contents to a new table.
3393 */
3394static void
3396{
3397 Size size;
3398 dsm_segment *seg;
3399 DecodingWorkerShared *shared;
3400 shm_mq *mq;
3403
3404 /* Setup shared memory. */
3405 size = BUFFERALIGN(offsetof(DecodingWorkerShared, error_queue)) +
3407 seg = dsm_create(size, 0);
3408 shared = (DecodingWorkerShared *) dsm_segment_address(seg);
3409 shared->initialized = false;
3410 shared->lsn_upto = InvalidXLogRecPtr;
3411 shared->done = false;
3412 SharedFileSetInit(&shared->sfs, seg);
3413 shared->last_exported = -1;
3414 SpinLockInit(&shared->mutex);
3415 shared->dbid = MyDatabaseId;
3416
3417 /*
3418 * This is the UserId set in cluster_rel(). Security context shouldn't be
3419 * needed for decoding worker.
3420 */
3421 shared->roleid = GetUserId();
3422 shared->relid = relid;
3423 ConditionVariableInit(&shared->cv);
3424 shared->backend_proc = MyProc;
3425 shared->backend_pid = MyProcPid;
3427
3428 mq = shm_mq_create((char *) BUFFERALIGN(shared->error_queue),
3431 mqh = shm_mq_attach(mq, seg, NULL);
3432
3433 memset(&bgw, 0, sizeof(bgw));
3434 snprintf(bgw.bgw_name, BGW_MAXLEN,
3435 "REPACK decoding worker for relation \"%s\"",
3436 get_rel_name(relid));
3437 snprintf(bgw.bgw_type, BGW_MAXLEN, "REPACK decoding worker");
3438 bgw.bgw_flags = BGWORKER_SHMEM_ACCESS |
3440 bgw.bgw_start_time = BgWorkerStart_RecoveryFinished;
3441 bgw.bgw_restart_time = BGW_NEVER_RESTART;
3442 snprintf(bgw.bgw_library_name, MAXPGPATH, "postgres");
3443 snprintf(bgw.bgw_function_name, BGW_MAXLEN, "RepackWorkerMain");
3444 bgw.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(seg));
3445 bgw.bgw_notify_pid = MyProcPid;
3446
3449 ereport(ERROR,
3451 errmsg("out of background worker slots"),
3452 errhint("You might need to increase \"%s\".", "max_worker_processes"));
3453
3454 decoding_worker->seg = seg;
3456
3457 /*
3458 * The decoding setup must be done before the caller can have XID assigned
3459 * for any reason, otherwise the worker might end up in a deadlock,
3460 * waiting for the caller's transaction to end. Therefore wait here until
3461 * the worker indicates that it has the logical decoding initialized.
3462 */
3464 for (;;)
3465 {
3466 bool initialized;
3467
3468 SpinLockAcquire(&shared->mutex);
3469 initialized = shared->initialized;
3470 SpinLockRelease(&shared->mutex);
3471
3472 if (initialized)
3473 break;
3474
3476 }
3478}
3479
3480/*
3481 * Stop the decoding worker and cleanup the related resources.
3482 *
3483 * The worker stops on its own when it knows there is no more work to do, but
3484 * we need to stop it explicitly at least on ERROR in the launching backend.
3485 */
3486static void
3488{
3489 BgwHandleStatus status;
3490
3491 /* Haven't reached the worker startup? */
3492 if (decoding_worker == NULL)
3493 return;
3494
3495 /* Could not register the worker? */
3496 if (decoding_worker->handle == NULL)
3497 return;
3498
3500 /* The worker should really exit before the REPACK command does. */
3504
3505 if (status == BGWH_POSTMASTER_DIED)
3506 ereport(FATAL,
3508 errmsg("postmaster exited during REPACK command"));
3509
3511
3512 /*
3513 * If we could not cancel the current sleep due to ERROR, do that before
3514 * we detach from the shared memory the condition variable is located in.
3515 * If we did not, the bgworker ERROR handling code would try and fail
3516 * badly.
3517 */
3519
3523}
3524
3525/*
3526 * Get the initial snapshot from the decoding worker.
3527 */
3528static Snapshot
3530{
3531 DecodingWorkerShared *shared;
3532 char fname[MAXPGPATH];
3533 BufFile *file;
3535 char *snap_space;
3536 Snapshot snapshot;
3537
3538 shared = (DecodingWorkerShared *) dsm_segment_address(worker->seg);
3539
3540 /*
3541 * The worker needs to initialize the logical decoding, which usually
3542 * takes some time. Therefore it makes sense to prepare for the sleep
3543 * first.
3544 */
3546 for (;;)
3547 {
3548 int last_exported;
3549
3550 SpinLockAcquire(&shared->mutex);
3551 last_exported = shared->last_exported;
3552 SpinLockRelease(&shared->mutex);
3553
3554 /*
3555 * Has the worker exported the file we are waiting for?
3556 */
3557 if (last_exported == WORKER_FILE_SNAPSHOT)
3558 break;
3559
3561 }
3563
3564 /* Read the snapshot from a file. */
3566 file = BufFileOpenFileSet(&shared->sfs.fs, fname, O_RDONLY, false);
3567 BufFileReadExact(file, &snap_size, sizeof(snap_size));
3568 snap_space = (char *) palloc(snap_size);
3570 BufFileClose(file);
3571
3572 /* Restore it. */
3573 snapshot = RestoreSnapshot(snap_space);
3575
3576 return snapshot;
3577}
3578
3579/*
3580 * Generate worker's file name into 'fname', which must be of size MAXPGPATH.
3581 * If relations of the same 'relid' happen to be processed at the same time,
3582 * they must be from different databases and therefore different backends must
3583 * be involved.
3584 */
3585void
3587{
3588 /* The PID is already present in the fileset name, so we needn't add it */
3589 snprintf(fname, MAXPGPATH, "%u-%u", relid, seq);
3590}
3591
3592/*
3593 * Handle receipt of an interrupt indicating a repack worker message.
3594 *
3595 * Note: this is called within a signal handler! All we can do is set
3596 * a flag that will cause the next CHECK_FOR_INTERRUPTS() to invoke
3597 * ProcessRepackMessages().
3598 */
3599void
3601{
3602 InterruptPending = true;
3603 RepackMessagePending = true;
3605}
3606
3607/*
3608 * Process any queued protocol messages received from the repack worker.
3609 */
3610void
3612{
3613 MemoryContext oldcontext;
3615
3616 /*
3617 * Nothing to do if we haven't launched the worker yet or have already
3618 * terminated it.
3619 */
3620 if (decoding_worker == NULL)
3621 return;
3622
3623 /*
3624 * This is invoked from ProcessInterrupts(), and since some of the
3625 * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
3626 * for recursive calls if more signals are received while this runs. It's
3627 * unclear that recursive entry would be safe, and it doesn't seem useful
3628 * even if it is safe, so let's block interrupts until done.
3629 */
3631
3632 /*
3633 * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
3634 * don't want to risk leaking data into long-lived contexts, so let's do
3635 * our work here in a private context that we can reset on each use.
3636 */
3637 if (hpm_context == NULL) /* first time through? */
3639 "ProcessRepackMessages",
3641 else
3643
3644 oldcontext = MemoryContextSwitchTo(hpm_context);
3645
3646 /* OK to process messages. Reset the flag saying there are more to do. */
3647 RepackMessagePending = false;
3648
3649 /*
3650 * Read as many messages as we can from the worker, but stop when no more
3651 * messages can be read from the worker without blocking.
3652 */
3653 while (true)
3654 {
3655 shm_mq_result res;
3656 Size nbytes;
3657 void *data;
3658
3660 &data, true);
3661 if (res == SHM_MQ_WOULD_BLOCK)
3662 break;
3663 else if (res == SHM_MQ_SUCCESS)
3664 {
3665 StringInfoData msg;
3666
3667 initStringInfo(&msg);
3668 appendBinaryStringInfo(&msg, data, nbytes);
3670 pfree(msg.data);
3671 }
3672 else
3673 {
3674 /*
3675 * The decoding worker is special in that it exits as soon as it
3676 * has its work done. Thus the DETACHED result code is fine.
3677 */
3678 Assert(res == SHM_MQ_DETACHED);
3679
3680 break;
3681 }
3682 }
3683
3684 MemoryContextSwitchTo(oldcontext);
3685
3686 /* Might as well clear the context on our way out */
3688
3690}
3691
3692/*
3693 * Process a single protocol message received from a single parallel worker.
3694 */
3695static void
3697{
3698 char msgtype;
3699
3700 msgtype = pq_getmsgbyte(msg);
3701
3702 switch (msgtype)
3703 {
3706 {
3708
3709 /* Parse ErrorResponse or NoticeResponse. */
3711
3712 /* Death of a worker isn't enough justification for suicide. */
3713 edata.elevel = Min(edata.elevel, ERROR);
3714
3715 /*
3716 * Add a context line to show that this is a message
3717 * propagated from the worker. Otherwise, it can sometimes be
3718 * confusing to understand what actually happened.
3719 */
3720 if (edata.context)
3721 edata.context = psprintf("%s\n%s", edata.context,
3722 _("REPACK decoding worker"));
3723 else
3724 edata.context = pstrdup(_("REPACK decoding worker"));
3725
3726 /* Rethrow error or print notice. */
3728
3729 break;
3730 }
3731
3732 default:
3733 {
3734 elog(ERROR, "unrecognized message type received from decoding worker: %c (message length %d bytes)",
3735 msgtype, msg->len);
3736 }
3737 }
3738}
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:688
#define RELATION_IS_OTHER_TEMP(relation)
Definition rel.h:669
#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:697
static void restore_tuple(BufFile *file, Relation relation, TupleTableSlot *slot)
Definition repack.c:2706
static void start_repack_decoding_worker(Oid relid)
Definition repack.c:3395
static void check_concurrent_repack_requirements(Relation rel, Oid *ident_idx_p)
Definition repack.c:884
static bool find_target_tuple(Relation rel, ChangeContext *chgcxt, TupleTableSlot *locator, TupleTableSlot *retrieved)
Definition repack.c:2811
static List * get_tables_to_repack_partitioned(RepackCommand cmd, Oid relid, bool rel_is_index, MemoryContext permcxt)
Definition repack.c:2244
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:1870
static Relation process_single_relation(RepackStmt *stmt, LOCKMODE lockmode, bool isTopLevel, ClusterParams *params)
Definition repack.c:2335
void check_index_is_clusterable(Relation OldHeap, Oid indexOid, LOCKMODE lockmode)
Definition repack.c:758
static void release_change_context(ChangeContext *chgcxt)
Definition repack.c:3049
static bool repack_is_permitted_for_relation(RepackCommand cmd, Oid relid, Oid userid)
Definition repack.c:2307
void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
Definition repack.c:244
static void stop_repack_decoding_worker(void)
Definition repack.c:3487
static LOCKMODE RepackLockLevel(bool concurrent)
Definition repack.c:476
static void apply_concurrent_delete(Relation rel, TupleTableSlot *slot)
Definition repack.c:2674
static void ProcessRepackMessage(StringInfo msg)
Definition repack.c:3696
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:509
static List * get_tables_to_repack(RepackCommand cmd, bool usingindex, MemoryContext permcxt)
Definition repack.c:2091
static const char * RepackCommandAsString(RepackCommand cmd)
Definition repack.c:2469
void DecodingWorkerFileName(char *fname, Oid relid, uint32 seq)
Definition repack.c:3586
Oid make_new_heap(Oid OIDOldHeap, Oid NewTableSpace, Oid NewAccessMethod, char relpersistence, LOCKMODE lockmode)
Definition repack.c:1113
static void initialize_change_context(ChangeContext *chgcxt, Relation relation, Oid ident_index_id)
Definition repack.c:2957
static bool identity_key_equal(ChangeContext *chgcxt, TupleTableSlot *locator, TupleTableSlot *candidate)
Definition repack.c:2864
static void process_concurrent_changes(XLogRecPtr end_of_wal, ChangeContext *chgcxt, bool done)
Definition repack.c:2901
static void copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex, Snapshot snapshot, bool verbose, bool *pSwapToastByContent, TransactionId *pFreezeXid, MultiXactId *pCutoffMulti)
Definition repack.c:1242
static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, Oid identIdx, TransactionId frozenXid, MultiXactId cutoffMulti)
Definition repack.c:3067
static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot, ChangeContext *chgcxt)
Definition repack.c:2613
static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt)
Definition repack.c:2487
static void rebuild_relation(Relation OldHeap, Relation index, bool verbose, Oid ident_idx)
Definition repack.c:966
void HandleRepackMessageInterrupt(void)
Definition repack.c:3600
static Snapshot get_initial_snapshot(DecodingWorker *worker)
Definition repack.c:3529
void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal)
Definition repack.c:818
static void adjust_toast_pointers(Relation relation, TupleTableSlot *dest, TupleTableSlot *src)
Definition repack.c:2776
#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:1488
static Oid determine_clustered_index(Relation rel, bool usingindex, const char *indexname)
Definition repack.c:2426
void ProcessRepackMessages(void)
Definition repack.c:3611
static void copy_index_constraints(Relation old_index, Oid new_index_id, Oid new_heap_id)
Definition repack.c:3328
static void apply_concurrent_update(Relation rel, TupleTableSlot *spilled_tuple, TupleTableSlot *ondisk_tuple, ChangeContext *chgcxt)
Definition repack.c:2634
static DecodingWorker * decoding_worker
Definition repack.c:144
static List * build_new_indexes(Relation NewHeap, Relation OldHeap, List *OldIndexes)
Definition repack.c:3283
#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