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