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