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