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