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