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