PostgreSQL Source Code  git master
cluster.h File Reference
#include "nodes/parsenodes.h"
#include "storage/lock.h"
#include "utils/relcache.h"
Include dependency graph for cluster.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void cluster (ClusterStmt *stmt, bool isTopLevel)
 
void cluster_rel (Oid tableOid, Oid indexOid, int options)
 
void check_index_is_clusterable (Relation OldHeap, Oid indexOid, bool recheck, LOCKMODE lockmode)
 
void mark_index_clustered (Relation rel, Oid indexOid, bool is_internal)
 
Oid make_new_heap (Oid OIDOldHeap, Oid NewTableSpace, char relpersistence, LOCKMODE lockmode)
 
void finish_heap_swap (Oid OIDOldHeap, Oid OIDNewHeap, bool is_system_catalog, bool swap_toast_by_content, bool check_constraints, bool is_internal, TransactionId frozenXid, MultiXactId minMulti, char newrelpersistence)
 

Function Documentation

◆ check_index_is_clusterable()

void check_index_is_clusterable ( Relation  OldHeap,
Oid  indexOid,
bool  recheck,
LOCKMODE  lockmode 
)

Definition at line 419 of file cluster.c.

References IndexAmRoutine::amclusterable, ereport, errcode(), errmsg(), ERROR, heap_attisnull(), index_close(), index_open(), NoLock, RelationData::rd_indam, RelationData::rd_index, RelationData::rd_indextuple, RelationGetRelationName, and RelationGetRelid.

Referenced by ATExecClusterOn(), and cluster_rel().

420 {
421  Relation OldIndex;
422 
423  OldIndex = index_open(indexOid, lockmode);
424 
425  /*
426  * Check that index is in fact an index on the given relation
427  */
428  if (OldIndex->rd_index == NULL ||
429  OldIndex->rd_index->indrelid != RelationGetRelid(OldHeap))
430  ereport(ERROR,
431  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
432  errmsg("\"%s\" is not an index for table \"%s\"",
433  RelationGetRelationName(OldIndex),
434  RelationGetRelationName(OldHeap))));
435 
436  /* Index AM must allow clustering */
437  if (!OldIndex->rd_indam->amclusterable)
438  ereport(ERROR,
439  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
440  errmsg("cannot cluster on index \"%s\" because access method does not support clustering",
441  RelationGetRelationName(OldIndex))));
442 
443  /*
444  * Disallow clustering on incomplete indexes (those that might not index
445  * every row of the relation). We could relax this by making a separate
446  * seqscan pass over the table to copy the missing rows, but that seems
447  * expensive and tedious.
448  */
449  if (!heap_attisnull(OldIndex->rd_indextuple, Anum_pg_index_indpred, NULL))
450  ereport(ERROR,
451  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
452  errmsg("cannot cluster on partial index \"%s\"",
453  RelationGetRelationName(OldIndex))));
454 
455  /*
456  * Disallow if index is left over from a failed CREATE INDEX CONCURRENTLY;
457  * it might well not contain entries for every heap row, or might not even
458  * be internally consistent. (But note that we don't check indcheckxmin;
459  * the worst consequence of following broken HOT chains would be that we
460  * might put recently-dead tuples out-of-order in the new table, and there
461  * is little harm in that.)
462  */
463  if (!OldIndex->rd_index->indisvalid)
464  ereport(ERROR,
465  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
466  errmsg("cannot cluster on invalid index \"%s\"",
467  RelationGetRelationName(OldIndex))));
468 
469  /* Drop relcache refcnt on OldIndex, but keep lock */
470  index_close(OldIndex, NoLock);
471 }
struct IndexAmRoutine * rd_indam
Definition: rel.h:188
int errcode(int sqlerrcode)
Definition: elog.c:610
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
struct HeapTupleData * rd_indextuple
Definition: rel.h:176
Form_pg_index rd_index
Definition: rel.h:174
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:490
bool amclusterable
Definition: amapi.h:237
#define ereport(elevel,...)
Definition: elog.h:144
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define RelationGetRelid(relation)
Definition: rel.h:456
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ cluster()

void cluster ( ClusterStmt stmt,
bool  isTopLevel 
)

Definition at line 102 of file cluster.c.

References AccessExclusiveLock, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, CLUOPT_RECHECK, cluster_rel(), CommitTransactionCommand(), ereport, errcode(), errmsg(), ERROR, get_index_isclustered(), get_relname_relid(), get_tables_to_cluster(), GetTransactionSnapshot(), ClusterStmt::indexname, RelToCluster::indexOid, InvalidOid, lfirst, lfirst_oid, MemoryContextDelete(), NoLock, OidIsValid, ClusterStmt::options, PopActiveSnapshot(), PortalContext, PreventInTransactionBlock(), PushActiveSnapshot(), RangeVarCallbackOwnsTable(), RangeVarGetRelidExtended(), RelationData::rd_rel, ClusterStmt::relation, RELATION_IS_OTHER_TEMP, RelationGetIndexList(), RangeVar::relname, StartTransactionCommand(), table_close(), table_open(), and RelToCluster::tableOid.

Referenced by standard_ProcessUtility(), start_postmaster(), and stop_postmaster().

103 {
104  if (stmt->relation != NULL)
105  {
106  /* This is the single-relation case. */
107  Oid tableOid,
108  indexOid = InvalidOid;
109  Relation rel;
110 
111  /* Find, lock, and check permissions on the table */
112  tableOid = RangeVarGetRelidExtended(stmt->relation,
114  0,
116  rel = table_open(tableOid, NoLock);
117 
118  /*
119  * Reject clustering a remote temp table ... their local buffer
120  * manager is not going to cope.
121  */
122  if (RELATION_IS_OTHER_TEMP(rel))
123  ereport(ERROR,
124  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
125  errmsg("cannot cluster temporary tables of other sessions")));
126 
127  /*
128  * Reject clustering a partitioned table.
129  */
130  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
131  ereport(ERROR,
132  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
133  errmsg("cannot cluster a partitioned table")));
134 
135  if (stmt->indexname == NULL)
136  {
137  ListCell *index;
138 
139  /* We need to find the index that has indisclustered set. */
140  foreach(index, RelationGetIndexList(rel))
141  {
142  indexOid = lfirst_oid(index);
143  if (get_index_isclustered(indexOid))
144  break;
145  indexOid = InvalidOid;
146  }
147 
148  if (!OidIsValid(indexOid))
149  ereport(ERROR,
150  (errcode(ERRCODE_UNDEFINED_OBJECT),
151  errmsg("there is no previously clustered index for table \"%s\"",
152  stmt->relation->relname)));
153  }
154  else
155  {
156  /*
157  * The index is expected to be in the same namespace as the
158  * relation.
159  */
160  indexOid = get_relname_relid(stmt->indexname,
161  rel->rd_rel->relnamespace);
162  if (!OidIsValid(indexOid))
163  ereport(ERROR,
164  (errcode(ERRCODE_UNDEFINED_OBJECT),
165  errmsg("index \"%s\" for table \"%s\" does not exist",
166  stmt->indexname, stmt->relation->relname)));
167  }
168 
169  /* close relation, keep lock till commit */
170  table_close(rel, NoLock);
171 
172  /* Do the job. */
173  cluster_rel(tableOid, indexOid, stmt->options);
174  }
175  else
176  {
177  /*
178  * This is the "multi relation" case. We need to cluster all tables
179  * that have some index with indisclustered set.
180  */
181  MemoryContext cluster_context;
182  List *rvs;
183  ListCell *rv;
184 
185  /*
186  * We cannot run this form of CLUSTER inside a user transaction block;
187  * we'd be holding locks way too long.
188  */
189  PreventInTransactionBlock(isTopLevel, "CLUSTER");
190 
191  /*
192  * Create special memory context for cross-transaction storage.
193  *
194  * Since it is a child of PortalContext, it will go away even in case
195  * of error.
196  */
197  cluster_context = AllocSetContextCreate(PortalContext,
198  "Cluster",
200 
201  /*
202  * Build the list of relations to cluster. Note that this lives in
203  * cluster_context.
204  */
205  rvs = get_tables_to_cluster(cluster_context);
206 
207  /* Commit to get out of starting transaction */
210 
211  /* Ok, now that we've got them all, cluster them one by one */
212  foreach(rv, rvs)
213  {
214  RelToCluster *rvtc = (RelToCluster *) lfirst(rv);
215 
216  /* Start a new transaction for each relation. */
218  /* functions in indexes may want a snapshot set */
220  /* Do the job. */
221  cluster_rel(rvtc->tableOid, rvtc->indexOid,
222  stmt->options | CLUOPT_RECHECK);
225  }
226 
227  /* Start a new transaction for the cleanup work. */
229 
230  /* Clean up working storage */
231  MemoryContextDelete(cluster_context);
232  }
233 }
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:15412
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void CommitTransactionCommand(void)
Definition: xact.c:2947
int errcode(int sqlerrcode)
Definition: elog.c:610
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
#define OidIsValid(objectId)
Definition: c.h:651
void cluster_rel(Oid tableOid, Oid indexOid, int options)
Definition: cluster.c:253
Oid tableOid
Definition: cluster.c:65
MemoryContext PortalContext
Definition: mcxt.c:53
Definition: type.h:89
char * relname
Definition: primnodes.h:68
char * indexname
Definition: parsenodes.h:3211
#define ERROR
Definition: elog.h:43
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1797
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3380
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:236
static List * get_tables_to_cluster(MemoryContext cluster_context)
Definition: cluster.c:1513
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:190
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:593
void StartTransactionCommand(void)
Definition: xact.c:2846
bool get_index_isclustered(Oid index_oid)
Definition: lsyscache.c:3380
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4507
Oid indexOid
Definition: cluster.c:66
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
RangeVar * relation
Definition: parsenodes.h:3210
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ cluster_rel()

void cluster_rel ( Oid  tableOid,
Oid  indexOid,
int  options 
)

Definition at line 253 of file cluster.c.

References AccessExclusiveLock, CHECK_FOR_INTERRUPTS, check_index_is_clusterable(), CheckTableNotInUse(), CLUOPT_RECHECK, CLUOPT_VERBOSE, ereport, errcode(), errmsg(), ERROR, get_index_isclustered(), GetUserId(), ObjectIdGetDatum, OidIsValid, pg_class_ownercheck(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), PROGRESS_CLUSTER_COMMAND, PROGRESS_CLUSTER_COMMAND_CLUSTER, PROGRESS_CLUSTER_COMMAND_VACUUM_FULL, PROGRESS_COMMAND_CLUSTER, RelationData::rd_rel, rebuild_relation(), relation_close(), RELATION_IS_OTHER_TEMP, RelationIsPopulated, RELOID, SearchSysCacheExists1, TransferPredicateLocksToHeapRelation(), try_relation_open(), and verbose.

Referenced by cluster(), and vacuum_rel().

254 {
255  Relation OldHeap;
256  bool verbose = ((options & CLUOPT_VERBOSE) != 0);
257  bool recheck = ((options & CLUOPT_RECHECK) != 0);
258 
259  /* Check for user-requested abort. */
261 
263  if (OidIsValid(indexOid))
266  else
269 
270  /*
271  * We grab exclusive access to the target rel and index for the duration
272  * of the transaction. (This is redundant for the single-transaction
273  * case, since cluster() already did it.) The index lock is taken inside
274  * check_index_is_clusterable.
275  */
276  OldHeap = try_relation_open(tableOid, AccessExclusiveLock);
277 
278  /* If the table has gone away, we can skip processing it */
279  if (!OldHeap)
280  {
282  return;
283  }
284 
285  /*
286  * Since we may open a new transaction for each relation, we have to check
287  * that the relation still is what we think it is.
288  *
289  * If this is a single-transaction CLUSTER, we can skip these tests. We
290  * *must* skip the one on indisclustered since it would reject an attempt
291  * to cluster a not-previously-clustered index.
292  */
293  if (recheck)
294  {
295  /* Check that the user still owns the relation */
296  if (!pg_class_ownercheck(tableOid, GetUserId()))
297  {
300  return;
301  }
302 
303  /*
304  * Silently skip a temp table for a remote session. Only doing this
305  * check in the "recheck" case is appropriate (which currently means
306  * somebody is executing a database-wide CLUSTER), because there is
307  * another check in cluster() which will stop any attempt to cluster
308  * remote temp tables by name. There is another check in cluster_rel
309  * which is redundant, but we leave it for extra safety.
310  */
311  if (RELATION_IS_OTHER_TEMP(OldHeap))
312  {
315  return;
316  }
317 
318  if (OidIsValid(indexOid))
319  {
320  /*
321  * Check that the index still exists
322  */
324  {
327  return;
328  }
329 
330  /*
331  * Check that the index is still the one with indisclustered set.
332  */
333  if (!get_index_isclustered(indexOid))
334  {
337  return;
338  }
339  }
340  }
341 
342  /*
343  * We allow VACUUM FULL, but not CLUSTER, on shared catalogs. CLUSTER
344  * would work in most respects, but the index would only get marked as
345  * indisclustered in the current database, leading to unexpected behavior
346  * if CLUSTER were later invoked in another database.
347  */
348  if (OidIsValid(indexOid) && OldHeap->rd_rel->relisshared)
349  ereport(ERROR,
350  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
351  errmsg("cannot cluster a shared catalog")));
352 
353  /*
354  * Don't process temp tables of other backends ... their local buffer
355  * manager is not going to cope.
356  */
357  if (RELATION_IS_OTHER_TEMP(OldHeap))
358  {
359  if (OidIsValid(indexOid))
360  ereport(ERROR,
361  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
362  errmsg("cannot cluster temporary tables of other sessions")));
363  else
364  ereport(ERROR,
365  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
366  errmsg("cannot vacuum temporary tables of other sessions")));
367  }
368 
369  /*
370  * Also check for active uses of the relation in the current transaction,
371  * including open scans and pending AFTER trigger events.
372  */
373  CheckTableNotInUse(OldHeap, OidIsValid(indexOid) ? "CLUSTER" : "VACUUM");
374 
375  /* Check heap and index are valid to cluster on */
376  if (OidIsValid(indexOid))
377  check_index_is_clusterable(OldHeap, indexOid, recheck, AccessExclusiveLock);
378 
379  /*
380  * Quietly ignore the request if this is a materialized view which has not
381  * been populated from its query. No harm is done because there is no data
382  * to deal with, and we don't want to throw an error if this is part of a
383  * multi-relation request -- for example, CLUSTER was run on the entire
384  * database.
385  */
386  if (OldHeap->rd_rel->relkind == RELKIND_MATVIEW &&
387  !RelationIsPopulated(OldHeap))
388  {
391  return;
392  }
393 
394  /*
395  * All predicate locks on the tuples or pages are about to be made
396  * invalid, because we move tuples around. Promote them to relation
397  * locks. Predicate locks on indexes will be promoted when they are
398  * reindexed.
399  */
401 
402  /* rebuild_relation does all the dirty work */
403  rebuild_relation(OldHeap, indexOid, verbose);
404 
405  /* NB: rebuild_relation does table_close() on OldHeap */
406 
408 }
#define RelationIsPopulated(relation)
Definition: rel.h:612
Oid GetUserId(void)
Definition: miscinit.c:450
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3210
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
int errcode(int sqlerrcode)
Definition: elog.c:610
Form_pg_class rd_rel
Definition: rel.h:109
#define OidIsValid(objectId)
Definition: c.h:651
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:89
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:183
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static void rebuild_relation(Relation OldHeap, Oid indexOid, bool verbose)
Definition: cluster.c:552
#define PROGRESS_CLUSTER_COMMAND_VACUUM_FULL
Definition: progress.h:75
#define PROGRESS_CLUSTER_COMMAND_CLUSTER
Definition: progress.h:74
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3533
#define PROGRESS_CLUSTER_COMMAND
Definition: progress.h:55
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3077
static int verbose
void pgstat_progress_end_command(void)
Definition: pgstat.c:3282
#define ereport(elevel,...)
Definition: elog.h:144
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:593
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
bool get_index_isclustered(Oid index_oid)
Definition: lsyscache.c:3380
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:824
void check_index_is_clusterable(Relation OldHeap, Oid indexOid, bool recheck, LOCKMODE lockmode)
Definition: cluster.c:419
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99

◆ finish_heap_swap()

void finish_heap_swap ( Oid  OIDOldHeap,
Oid  OIDNewHeap,
bool  is_system_catalog,
bool  swap_toast_by_content,
bool  check_constraints,
bool  is_internal,
TransactionId  frozenXid,
MultiXactId  minMulti,
char  newrelpersistence 
)

Definition at line 1324 of file cluster.c.

References CacheInvalidateCatalog(), CatalogTupleUpdate(), DROP_RESTRICT, elog, ERROR, GETSTRUCT, HeapTupleIsValid, i, NAMEDATALEN, NoLock, ObjectIdGetDatum, OidIsValid, PERFORM_DELETION_INTERNAL, performDeletion(), pgstat_progress_update_param(), PROGRESS_CLUSTER_PHASE, PROGRESS_CLUSTER_PHASE_FINAL_CLEANUP, PROGRESS_CLUSTER_PHASE_REBUILD_INDEX, PROGRESS_CLUSTER_PHASE_SWAP_REL_FILES, RelationData::rd_rel, REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_FORCE_INDEXES_PERMANENT, REINDEX_REL_FORCE_INDEXES_UNLOGGED, REINDEX_REL_SUPPRESS_INDEX_USE, reindex_relation(), relation_close(), RelationClearMissing(), RelationMapRemoveMapping(), RELOID, RenameRelationInternal(), RowExclusiveLock, SearchSysCacheCopy1, snprintf, swap_relation_files(), HeapTupleData::t_self, table_close(), table_open(), and toast_get_valid_index().

Referenced by ATRewriteTables(), rebuild_relation(), and refresh_by_heap_swap().

1332 {
1333  ObjectAddress object;
1334  Oid mapped_tables[4];
1335  int reindex_flags;
1336  int i;
1337 
1338  /* Report that we are now swapping relation files */
1341 
1342  /* Zero out possible results from swapped_relation_files */
1343  memset(mapped_tables, 0, sizeof(mapped_tables));
1344 
1345  /*
1346  * Swap the contents of the heap relations (including any toast tables).
1347  * Also set old heap's relfrozenxid to frozenXid.
1348  */
1349  swap_relation_files(OIDOldHeap, OIDNewHeap,
1350  (OIDOldHeap == RelationRelationId),
1351  swap_toast_by_content, is_internal,
1352  frozenXid, cutoffMulti, mapped_tables);
1353 
1354  /*
1355  * If it's a system catalog, queue a sinval message to flush all catcaches
1356  * on the catalog when we reach CommandCounterIncrement.
1357  */
1358  if (is_system_catalog)
1359  CacheInvalidateCatalog(OIDOldHeap);
1360 
1361  /*
1362  * Rebuild each index on the relation (but not the toast table, which is
1363  * all-new at this point). It is important to do this before the DROP
1364  * step because if we are processing a system catalog that will be used
1365  * during DROP, we want to have its indexes available. There is no
1366  * advantage to the other order anyway because this is all transactional,
1367  * so no chance to reclaim disk space before commit. We do not need a
1368  * final CommandCounterIncrement() because reindex_relation does it.
1369  *
1370  * Note: because index_build is called via reindex_relation, it will never
1371  * set indcheckxmin true for the indexes. This is OK even though in some
1372  * sense we are building new indexes rather than rebuilding existing ones,
1373  * because the new heap won't contain any HOT chains at all, let alone
1374  * broken ones, so it can't be necessary to set indcheckxmin.
1375  */
1376  reindex_flags = REINDEX_REL_SUPPRESS_INDEX_USE;
1377  if (check_constraints)
1378  reindex_flags |= REINDEX_REL_CHECK_CONSTRAINTS;
1379 
1380  /*
1381  * Ensure that the indexes have the same persistence as the parent
1382  * relation.
1383  */
1384  if (newrelpersistence == RELPERSISTENCE_UNLOGGED)
1385  reindex_flags |= REINDEX_REL_FORCE_INDEXES_UNLOGGED;
1386  else if (newrelpersistence == RELPERSISTENCE_PERMANENT)
1387  reindex_flags |= REINDEX_REL_FORCE_INDEXES_PERMANENT;
1388 
1389  /* Report that we are now reindexing relations */
1392 
1393  reindex_relation(OIDOldHeap, reindex_flags, 0);
1394 
1395  /* Report that we are now doing clean up */
1398 
1399  /*
1400  * If the relation being rebuild is pg_class, swap_relation_files()
1401  * couldn't update pg_class's own pg_class entry (check comments in
1402  * swap_relation_files()), thus relfrozenxid was not updated. That's
1403  * annoying because a potential reason for doing a VACUUM FULL is a
1404  * imminent or actual anti-wraparound shutdown. So, now that we can
1405  * access the new relation using its indices, update relfrozenxid.
1406  * pg_class doesn't have a toast relation, so we don't need to update the
1407  * corresponding toast relation. Not that there's little point moving all
1408  * relfrozenxid updates here since swap_relation_files() needs to write to
1409  * pg_class for non-mapped relations anyway.
1410  */
1411  if (OIDOldHeap == RelationRelationId)
1412  {
1413  Relation relRelation;
1414  HeapTuple reltup;
1415  Form_pg_class relform;
1416 
1417  relRelation = table_open(RelationRelationId, RowExclusiveLock);
1418 
1419  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(OIDOldHeap));
1420  if (!HeapTupleIsValid(reltup))
1421  elog(ERROR, "cache lookup failed for relation %u", OIDOldHeap);
1422  relform = (Form_pg_class) GETSTRUCT(reltup);
1423 
1424  relform->relfrozenxid = frozenXid;
1425  relform->relminmxid = cutoffMulti;
1426 
1427  CatalogTupleUpdate(relRelation, &reltup->t_self, reltup);
1428 
1429  table_close(relRelation, RowExclusiveLock);
1430  }
1431 
1432  /* Destroy new heap with old filenode */
1433  object.classId = RelationRelationId;
1434  object.objectId = OIDNewHeap;
1435  object.objectSubId = 0;
1436 
1437  /*
1438  * The new relation is local to our transaction and we know nothing
1439  * depends on it, so DROP_RESTRICT should be OK.
1440  */
1442 
1443  /* performDeletion does CommandCounterIncrement at end */
1444 
1445  /*
1446  * Now we must remove any relation mapping entries that we set up for the
1447  * transient table, as well as its toast table and toast index if any. If
1448  * we fail to do this before commit, the relmapper will complain about new
1449  * permanent map entries being added post-bootstrap.
1450  */
1451  for (i = 0; OidIsValid(mapped_tables[i]); i++)
1452  RelationMapRemoveMapping(mapped_tables[i]);
1453 
1454  /*
1455  * At this point, everything is kosher except that, if we did toast swap
1456  * by links, the toast table's name corresponds to the transient table.
1457  * The name is irrelevant to the backend because it's referenced by OID,
1458  * but users looking at the catalogs could be confused. Rename it to
1459  * prevent this problem.
1460  *
1461  * Note no lock required on the relation, because we already hold an
1462  * exclusive lock on it.
1463  */
1464  if (!swap_toast_by_content)
1465  {
1466  Relation newrel;
1467 
1468  newrel = table_open(OIDOldHeap, NoLock);
1469  if (OidIsValid(newrel->rd_rel->reltoastrelid))
1470  {
1471  Oid toastidx;
1472  char NewToastName[NAMEDATALEN];
1473 
1474  /* Get the associated valid index to be renamed */
1475  toastidx = toast_get_valid_index(newrel->rd_rel->reltoastrelid,
1476  NoLock);
1477 
1478  /* rename the toast table ... */
1479  snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u",
1480  OIDOldHeap);
1481  RenameRelationInternal(newrel->rd_rel->reltoastrelid,
1482  NewToastName, true, false);
1483 
1484  /* ... and its valid index too. */
1485  snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u_index",
1486  OIDOldHeap);
1487 
1488  RenameRelationInternal(toastidx,
1489  NewToastName, true, true);
1490  }
1491  relation_close(newrel, NoLock);
1492  }
1493 
1494  /* if it's not a catalog table, clear any missing attribute settings */
1495  if (!is_system_catalog)
1496  {
1497  Relation newrel;
1498 
1499  newrel = table_open(OIDOldHeap, NoLock);
1500  RelationClearMissing(newrel);
1501  relation_close(newrel, NoLock);
1502  }
1503 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
#define PROGRESS_CLUSTER_PHASE_SWAP_REL_FILES
Definition: progress.h:69
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:141
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define NAMEDATALEN
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:312
void RelationClearMissing(Relation rel)
Definition: heap.c:2069
static void swap_relation_files(Oid r1, Oid r2, bool target_is_pg_class, bool swap_toast_by_content, bool is_internal, TransactionId frozenXid, MultiXactId cutoffMulti, Oid *mapped_tables)
Definition: cluster.c:966
void CacheInvalidateCatalog(Oid catalogId)
Definition: inval.c:1254
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:143
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
void RelationMapRemoveMapping(Oid relationId)
Definition: relmapper.c:373
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:142
#define PROGRESS_CLUSTER_PHASE_FINAL_CLEANUP
Definition: progress.h:71
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define elog(elevel,...)
Definition: elog.h:214
int i
#define REINDEX_REL_FORCE_INDEXES_PERMANENT
Definition: index.h:144
#define PROGRESS_CLUSTER_PHASE_REBUILD_INDEX
Definition: progress.h:70
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition: tablecmds.c:3431
#define PROGRESS_CLUSTER_PHASE
Definition: progress.h:56
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3646
#define snprintf
Definition: port.h:193
Oid toast_get_valid_index(Oid toastoid, LOCKMODE lock)
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134

◆ make_new_heap()

Oid make_new_heap ( Oid  OIDOldHeap,
Oid  NewTableSpace,
char  relpersistence,
LOCKMODE  lockmode 
)

Definition at line 605 of file cluster.c.

References Assert, CommandCounterIncrement(), elog, ERROR, heap_create_with_catalog(), HeapTupleIsValid, InvalidOid, LookupCreationNamespace(), NAMEDATALEN, NewHeapCreateToastTable(), NIL, NoLock, ObjectIdGetDatum, OidIsValid, ONCOMMIT_NOOP, RelationData::rd_rel, RelationGetDescr, RelationGetNamespace, RelationIsMapped, ReleaseSysCache(), RELOID, SearchSysCache1(), snprintf, SysCacheGetAttr(), table_close(), and table_open().

Referenced by ATRewriteTables(), ExecRefreshMatView(), and rebuild_relation().

607 {
608  TupleDesc OldHeapDesc;
609  char NewHeapName[NAMEDATALEN];
610  Oid OIDNewHeap;
611  Oid toastid;
612  Relation OldHeap;
613  HeapTuple tuple;
614  Datum reloptions;
615  bool isNull;
616  Oid namespaceid;
617 
618  OldHeap = table_open(OIDOldHeap, lockmode);
619  OldHeapDesc = RelationGetDescr(OldHeap);
620 
621  /*
622  * Note that the NewHeap will not receive any of the defaults or
623  * constraints associated with the OldHeap; we don't need 'em, and there's
624  * no reason to spend cycles inserting them into the catalogs only to
625  * delete them.
626  */
627 
628  /*
629  * But we do want to use reloptions of the old heap for new heap.
630  */
631  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(OIDOldHeap));
632  if (!HeapTupleIsValid(tuple))
633  elog(ERROR, "cache lookup failed for relation %u", OIDOldHeap);
634  reloptions = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
635  &isNull);
636  if (isNull)
637  reloptions = (Datum) 0;
638 
639  if (relpersistence == RELPERSISTENCE_TEMP)
640  namespaceid = LookupCreationNamespace("pg_temp");
641  else
642  namespaceid = RelationGetNamespace(OldHeap);
643 
644  /*
645  * Create the new heap, using a temporary name in the same namespace as
646  * the existing table. NOTE: there is some risk of collision with user
647  * relnames. Working around this seems more trouble than it's worth; in
648  * particular, we can't create the new heap in a different namespace from
649  * the old, or we will have problems with the TEMP status of temp tables.
650  *
651  * Note: the new heap is not a shared relation, even if we are rebuilding
652  * a shared rel. However, we do make the new heap mapped if the source is
653  * mapped. This simplifies swap_relation_files, and is absolutely
654  * necessary for rebuilding pg_class, for reasons explained there.
655  */
656  snprintf(NewHeapName, sizeof(NewHeapName), "pg_temp_%u", OIDOldHeap);
657 
658  OIDNewHeap = heap_create_with_catalog(NewHeapName,
659  namespaceid,
660  NewTableSpace,
661  InvalidOid,
662  InvalidOid,
663  InvalidOid,
664  OldHeap->rd_rel->relowner,
665  OldHeap->rd_rel->relam,
666  OldHeapDesc,
667  NIL,
668  RELKIND_RELATION,
669  relpersistence,
670  false,
671  RelationIsMapped(OldHeap),
673  reloptions,
674  false,
675  true,
676  true,
677  OIDOldHeap,
678  NULL);
679  Assert(OIDNewHeap != InvalidOid);
680 
681  ReleaseSysCache(tuple);
682 
683  /*
684  * Advance command counter so that the newly-created relation's catalog
685  * tuples will be visible to table_open.
686  */
688 
689  /*
690  * If necessary, create a TOAST table for the new relation.
691  *
692  * If the relation doesn't have a TOAST table already, we can't need one
693  * for the new relation. The other way around is possible though: if some
694  * wide columns have been dropped, NewHeapCreateToastTable can decide that
695  * no TOAST table is needed for the new table.
696  *
697  * Note that NewHeapCreateToastTable ends with CommandCounterIncrement, so
698  * that the TOAST table will be visible for insertion.
699  */
700  toastid = OldHeap->rd_rel->reltoastrelid;
701  if (OidIsValid(toastid))
702  {
703  /* keep the existing toast table's reloptions, if any */
704  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(toastid));
705  if (!HeapTupleIsValid(tuple))
706  elog(ERROR, "cache lookup failed for relation %u", toastid);
707  reloptions = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_reloptions,
708  &isNull);
709  if (isNull)
710  reloptions = (Datum) 0;
711 
712  NewHeapCreateToastTable(OIDNewHeap, reloptions, lockmode);
713 
714  ReleaseSysCache(tuple);
715  }
716 
717  table_close(OldHeap, NoLock);
718 
719  return OIDNewHeap;
720 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:482
Oid LookupCreationNamespace(const char *nspname)
Definition: namespace.c:2936
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define NAMEDATALEN
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
#define RelationIsMapped(relation)
Definition: rel.h:505
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1021
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
Oid heap_create_with_catalog(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid reltypeid, Oid reloftypeid, Oid ownerid, Oid accessmtd, TupleDesc tupdesc, List *cooked_constraints, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, OnCommitAction oncommit, Datum reloptions, bool use_user_acl, bool allow_system_table_mods, bool is_internal, Oid relrewrite, ObjectAddress *typaddress)
Definition: heap.c:1137
#define elog(elevel,...)
Definition: elog.h:214
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define snprintf
Definition: port.h:193
#define RelationGetNamespace(relation)
Definition: rel.h:497
void NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
Definition: toasting.c:63

◆ mark_index_clustered()

void mark_index_clustered ( Relation  rel,
Oid  indexOid,
bool  is_internal 
)

Definition at line 479 of file cluster.c.

References CatalogTupleUpdate(), elog, ereport, errcode(), errmsg(), ERROR, get_index_isclustered(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, INDEXRELID, InvalidOid, InvokeObjectPostAlterHookArg, lfirst_oid, ObjectIdGetDatum, OidIsValid, RelationData::rd_rel, RelationGetIndexList(), RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), and table_open().

Referenced by ATExecClusterOn(), ATExecDropCluster(), and rebuild_relation().

480 {
481  HeapTuple indexTuple;
482  Form_pg_index indexForm;
483  Relation pg_index;
484  ListCell *index;
485 
486  /* Disallow applying to a partitioned table */
487  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
488  ereport(ERROR,
489  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
490  errmsg("cannot mark index clustered in partitioned table")));
491 
492  /*
493  * If the index is already marked clustered, no need to do anything.
494  */
495  if (OidIsValid(indexOid))
496  {
497  if (get_index_isclustered(indexOid))
498  return;
499  }
500 
501  /*
502  * Check each index of the relation and set/clear the bit as needed.
503  */
504  pg_index = table_open(IndexRelationId, RowExclusiveLock);
505 
506  foreach(index, RelationGetIndexList(rel))
507  {
508  Oid thisIndexOid = lfirst_oid(index);
509 
510  indexTuple = SearchSysCacheCopy1(INDEXRELID,
511  ObjectIdGetDatum(thisIndexOid));
512  if (!HeapTupleIsValid(indexTuple))
513  elog(ERROR, "cache lookup failed for index %u", thisIndexOid);
514  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
515 
516  /*
517  * Unset the bit if set. We know it's wrong because we checked this
518  * earlier.
519  */
520  if (indexForm->indisclustered)
521  {
522  indexForm->indisclustered = false;
523  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
524  }
525  else if (thisIndexOid == indexOid)
526  {
527  /* this was checked earlier, but let's be real sure */
528  if (!indexForm->indisvalid)
529  elog(ERROR, "cannot cluster on invalid index %u", indexOid);
530  indexForm->indisclustered = true;
531  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
532  }
533 
534  InvokeObjectPostAlterHookArg(IndexRelationId, thisIndexOid, 0,
535  InvalidOid, is_internal);
536 
537  heap_freetuple(indexTuple);
538  }
539 
540  table_close(pg_index, RowExclusiveLock);
541 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:610
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:178
Definition: type.h:89
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
bool get_index_isclustered(Oid index_oid)
Definition: lsyscache.c:3380
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4507
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define lfirst_oid(lc)
Definition: pg_list.h:192