PostgreSQL Source Code  git master
index.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * index.c
4  * code to create and destroy POSTGRES index relations
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/catalog/index.c
12  *
13  *
14  * INTERFACE ROUTINES
15  * index_create() - Create a cataloged index relation
16  * index_drop() - Removes index relation from catalogs
17  * BuildIndexInfo() - Prepare to insert index tuples
18  * FormIndexDatum() - Construct datum vector for one index tuple
19  *
20  *-------------------------------------------------------------------------
21  */
22 #include "postgres.h"
23 
24 #include <unistd.h>
25 
26 #include "access/amapi.h"
27 #include "access/heapam.h"
28 #include "access/multixact.h"
29 #include "access/reloptions.h"
30 #include "access/relscan.h"
31 #include "access/sysattr.h"
32 #include "access/tableam.h"
34 #include "access/transam.h"
35 #include "access/visibilitymap.h"
36 #include "access/xact.h"
37 #include "bootstrap/bootstrap.h"
38 #include "catalog/binary_upgrade.h"
39 #include "catalog/catalog.h"
40 #include "catalog/dependency.h"
41 #include "catalog/heap.h"
42 #include "catalog/index.h"
43 #include "catalog/objectaccess.h"
44 #include "catalog/partition.h"
45 #include "catalog/pg_am.h"
46 #include "catalog/pg_collation.h"
47 #include "catalog/pg_constraint.h"
48 #include "catalog/pg_depend.h"
49 #include "catalog/pg_description.h"
50 #include "catalog/pg_inherits.h"
51 #include "catalog/pg_opclass.h"
52 #include "catalog/pg_operator.h"
53 #include "catalog/pg_tablespace.h"
54 #include "catalog/pg_trigger.h"
55 #include "catalog/pg_type.h"
56 #include "catalog/storage.h"
57 #include "commands/defrem.h"
58 #include "commands/event_trigger.h"
59 #include "commands/progress.h"
60 #include "commands/tablecmds.h"
61 #include "commands/tablespace.h"
62 #include "commands/trigger.h"
63 #include "executor/executor.h"
64 #include "miscadmin.h"
65 #include "nodes/makefuncs.h"
66 #include "nodes/nodeFuncs.h"
67 #include "optimizer/optimizer.h"
68 #include "parser/parser.h"
69 #include "pgstat.h"
70 #include "rewrite/rewriteManip.h"
71 #include "storage/bufmgr.h"
72 #include "storage/lmgr.h"
73 #include "storage/predicate.h"
74 #include "storage/procarray.h"
75 #include "storage/smgr.h"
76 #include "utils/builtins.h"
77 #include "utils/fmgroids.h"
78 #include "utils/guc.h"
79 #include "utils/inval.h"
80 #include "utils/lsyscache.h"
81 #include "utils/pg_locale.h"
82 #include "utils/memutils.h"
83 #include "utils/pg_rusage.h"
84 #include "utils/rel.h"
85 #include "utils/snapmgr.h"
86 #include "utils/syscache.h"
87 #include "utils/tuplesort.h"
88 
89 /* Potentially set by pg_upgrade_support functions */
91 
92 /*
93  * Pointer-free representation of variables used when reindexing system
94  * catalogs; we use this to propagate those values to parallel workers.
95  */
96 typedef struct
97 {
103 
104 /* non-export function prototypes */
105 static bool relationHasPrimaryKey(Relation rel);
106 static TupleDesc ConstructTupleDescriptor(Relation heapRelation,
107  IndexInfo *indexInfo,
108  List *indexColNames,
109  Oid accessMethodObjectId,
110  Oid *collationObjectId,
111  Oid *classObjectId);
112 static void InitializeAttributeOids(Relation indexRelation,
113  int numatts, Oid indexoid);
114 static void AppendAttributeTuples(Relation indexRelation, Datum *attopts);
115 static void UpdateIndexRelation(Oid indexoid, Oid heapoid,
116  Oid parentIndexId,
117  IndexInfo *indexInfo,
118  Oid *collationOids,
119  Oid *classOids,
120  int16 *coloptions,
121  bool primary,
122  bool isexclusion,
123  bool immediate,
124  bool isvalid,
125  bool isready);
126 static void index_update_stats(Relation rel,
127  bool hasindex,
128  double reltuples);
129 static void IndexCheckExclusion(Relation heapRelation,
130  Relation indexRelation,
131  IndexInfo *indexInfo);
132 static bool validate_index_callback(ItemPointer itemptr, void *opaque);
133 static bool ReindexIsCurrentlyProcessingIndex(Oid indexOid);
134 static void SetReindexProcessing(Oid heapOid, Oid indexOid);
135 static void ResetReindexProcessing(void);
136 static void SetReindexPending(List *indexes);
137 static void RemoveReindexPending(Oid indexOid);
138 
139 
140 /*
141  * relationHasPrimaryKey
142  * See whether an existing relation has a primary key.
143  *
144  * Caller must have suitable lock on the relation.
145  *
146  * Note: we intentionally do not check indisvalid here; that's because this
147  * is used to enforce the rule that there can be only one indisprimary index,
148  * and we want that to be true even if said index is invalid.
149  */
150 static bool
152 {
153  bool result = false;
154  List *indexoidlist;
155  ListCell *indexoidscan;
156 
157  /*
158  * Get the list of index OIDs for the table from the relcache, and look up
159  * each one in the pg_index syscache until we find one marked primary key
160  * (hopefully there isn't more than one such).
161  */
162  indexoidlist = RelationGetIndexList(rel);
163 
164  foreach(indexoidscan, indexoidlist)
165  {
166  Oid indexoid = lfirst_oid(indexoidscan);
167  HeapTuple indexTuple;
168 
169  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
170  if (!HeapTupleIsValid(indexTuple)) /* should not happen */
171  elog(ERROR, "cache lookup failed for index %u", indexoid);
172  result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
173  ReleaseSysCache(indexTuple);
174  if (result)
175  break;
176  }
177 
178  list_free(indexoidlist);
179 
180  return result;
181 }
182 
183 /*
184  * index_check_primary_key
185  * Apply special checks needed before creating a PRIMARY KEY index
186  *
187  * This processing used to be in DefineIndex(), but has been split out
188  * so that it can be applied during ALTER TABLE ADD PRIMARY KEY USING INDEX.
189  *
190  * We check for a pre-existing primary key, and that all columns of the index
191  * are simple column references (not expressions), and that all those
192  * columns are marked NOT NULL. If not, fail.
193  *
194  * We used to automatically change unmarked columns to NOT NULL here by doing
195  * our own local ALTER TABLE command. But that doesn't work well if we're
196  * executing one subcommand of an ALTER TABLE: the operations may not get
197  * performed in the right order overall. Now we expect that the parser
198  * inserted any required ALTER TABLE SET NOT NULL operations before trying
199  * to create a primary-key index.
200  *
201  * Caller had better have at least ShareLock on the table, else the not-null
202  * checking isn't trustworthy.
203  */
204 void
206  IndexInfo *indexInfo,
207  bool is_alter_table,
208  IndexStmt *stmt)
209 {
210  int i;
211 
212  /*
213  * If ALTER TABLE or CREATE TABLE .. PARTITION OF, check that there isn't
214  * already a PRIMARY KEY. In CREATE TABLE for an ordinary relation, we
215  * have faith that the parser rejected multiple pkey clauses; and CREATE
216  * INDEX doesn't have a way to say PRIMARY KEY, so it's no problem either.
217  */
218  if ((is_alter_table || heapRel->rd_rel->relispartition) &&
219  relationHasPrimaryKey(heapRel))
220  {
221  ereport(ERROR,
222  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
223  errmsg("multiple primary keys for table \"%s\" are not allowed",
224  RelationGetRelationName(heapRel))));
225  }
226 
227  /*
228  * Check that all of the attributes in a primary key are marked as not
229  * null. (We don't really expect to see that; it'd mean the parser messed
230  * up. But it seems wise to check anyway.)
231  */
232  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
233  {
234  AttrNumber attnum = indexInfo->ii_IndexAttrNumbers[i];
235  HeapTuple atttuple;
236  Form_pg_attribute attform;
237 
238  if (attnum == 0)
239  ereport(ERROR,
240  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
241  errmsg("primary keys cannot be expressions")));
242 
243  /* System attributes are never null, so no need to check */
244  if (attnum < 0)
245  continue;
246 
247  atttuple = SearchSysCache2(ATTNUM,
249  Int16GetDatum(attnum));
250  if (!HeapTupleIsValid(atttuple))
251  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
252  attnum, RelationGetRelid(heapRel));
253  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
254 
255  if (!attform->attnotnull)
256  ereport(ERROR,
257  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
258  errmsg("primary key column \"%s\" is not marked NOT NULL",
259  NameStr(attform->attname))));
260 
261  ReleaseSysCache(atttuple);
262  }
263 }
264 
265 /*
266  * ConstructTupleDescriptor
267  *
268  * Build an index tuple descriptor for a new index
269  */
270 static TupleDesc
272  IndexInfo *indexInfo,
273  List *indexColNames,
274  Oid accessMethodObjectId,
275  Oid *collationObjectId,
276  Oid *classObjectId)
277 {
278  int numatts = indexInfo->ii_NumIndexAttrs;
279  int numkeyatts = indexInfo->ii_NumIndexKeyAttrs;
280  ListCell *colnames_item = list_head(indexColNames);
281  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
282  IndexAmRoutine *amroutine;
283  TupleDesc heapTupDesc;
284  TupleDesc indexTupDesc;
285  int natts; /* #atts in heap rel --- for error checks */
286  int i;
287 
288  /* We need access to the index AM's API struct */
289  amroutine = GetIndexAmRoutineByAmId(accessMethodObjectId, false);
290 
291  /* ... and to the table's tuple descriptor */
292  heapTupDesc = RelationGetDescr(heapRelation);
293  natts = RelationGetForm(heapRelation)->relnatts;
294 
295  /*
296  * allocate the new tuple descriptor
297  */
298  indexTupDesc = CreateTemplateTupleDesc(numatts);
299 
300  /*
301  * Fill in the pg_attribute row.
302  */
303  for (i = 0; i < numatts; i++)
304  {
305  AttrNumber atnum = indexInfo->ii_IndexAttrNumbers[i];
306  Form_pg_attribute to = TupleDescAttr(indexTupDesc, i);
307  HeapTuple tuple;
308  Form_pg_type typeTup;
309  Form_pg_opclass opclassTup;
310  Oid keyType;
311 
313  to->attnum = i + 1;
314  to->attstattarget = -1;
315  to->attcacheoff = -1;
316  to->attislocal = true;
317  to->attcollation = (i < numkeyatts) ?
318  collationObjectId[i] : InvalidOid;
319 
320  /*
321  * Set the attribute name as specified by caller.
322  */
323  if (colnames_item == NULL) /* shouldn't happen */
324  elog(ERROR, "too few entries in colnames list");
325  namestrcpy(&to->attname, (const char *) lfirst(colnames_item));
326  colnames_item = lnext(indexColNames, colnames_item);
327 
328  /*
329  * For simple index columns, we copy some pg_attribute fields from the
330  * parent relation. For expressions we have to look at the expression
331  * result.
332  */
333  if (atnum != 0)
334  {
335  /* Simple index column */
336  const FormData_pg_attribute *from;
337 
338  Assert(atnum > 0); /* should've been caught above */
339 
340  if (atnum > natts) /* safety check */
341  elog(ERROR, "invalid column number %d", atnum);
342  from = TupleDescAttr(heapTupDesc,
343  AttrNumberGetAttrOffset(atnum));
344 
345  to->atttypid = from->atttypid;
346  to->attlen = from->attlen;
347  to->attndims = from->attndims;
348  to->atttypmod = from->atttypmod;
349  to->attbyval = from->attbyval;
350  to->attstorage = from->attstorage;
351  to->attalign = from->attalign;
352  to->attcompression = from->attcompression;
353  }
354  else
355  {
356  /* Expressional index */
357  Node *indexkey;
358 
359  if (indexpr_item == NULL) /* shouldn't happen */
360  elog(ERROR, "too few entries in indexprs list");
361  indexkey = (Node *) lfirst(indexpr_item);
362  indexpr_item = lnext(indexInfo->ii_Expressions, indexpr_item);
363 
364  /*
365  * Lookup the expression type in pg_type for the type length etc.
366  */
367  keyType = exprType(indexkey);
368  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
369  if (!HeapTupleIsValid(tuple))
370  elog(ERROR, "cache lookup failed for type %u", keyType);
371  typeTup = (Form_pg_type) GETSTRUCT(tuple);
372 
373  /*
374  * Assign some of the attributes values. Leave the rest.
375  */
376  to->atttypid = keyType;
377  to->attlen = typeTup->typlen;
378  to->attbyval = typeTup->typbyval;
379  to->attstorage = typeTup->typstorage;
380  to->attalign = typeTup->typalign;
381  to->atttypmod = exprTypmod(indexkey);
382 
383  /*
384  * For expression columns, set attcompression invalid, since
385  * there's no table column from which to copy the value. Whenever
386  * we actually need to compress a value, we'll use whatever the
387  * current value of default_compression_method is at that point
388  * in time.
389  */
390  to->attcompression = InvalidCompressionMethod;
391 
392  ReleaseSysCache(tuple);
393 
394  /*
395  * Make sure the expression yields a type that's safe to store in
396  * an index. We need this defense because we have index opclasses
397  * for pseudo-types such as "record", and the actually stored type
398  * had better be safe; eg, a named composite type is okay, an
399  * anonymous record type is not. The test is the same as for
400  * whether a table column is of a safe type (which is why we
401  * needn't check for the non-expression case).
402  */
403  CheckAttributeType(NameStr(to->attname),
404  to->atttypid, to->attcollation,
405  NIL, 0);
406  }
407 
408  /*
409  * We do not yet have the correct relation OID for the index, so just
410  * set it invalid for now. InitializeAttributeOids() will fix it
411  * later.
412  */
413  to->attrelid = InvalidOid;
414 
415  /*
416  * Check the opclass and index AM to see if either provides a keytype
417  * (overriding the attribute type). Opclass (if exists) takes
418  * precedence.
419  */
420  keyType = amroutine->amkeytype;
421 
422  if (i < indexInfo->ii_NumIndexKeyAttrs)
423  {
424  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(classObjectId[i]));
425  if (!HeapTupleIsValid(tuple))
426  elog(ERROR, "cache lookup failed for opclass %u",
427  classObjectId[i]);
428  opclassTup = (Form_pg_opclass) GETSTRUCT(tuple);
429  if (OidIsValid(opclassTup->opckeytype))
430  keyType = opclassTup->opckeytype;
431 
432  /*
433  * If keytype is specified as ANYELEMENT, and opcintype is
434  * ANYARRAY, then the attribute type must be an array (else it'd
435  * not have matched this opclass); use its element type.
436  *
437  * We could also allow ANYCOMPATIBLE/ANYCOMPATIBLEARRAY here, but
438  * there seems no need to do so; there's no reason to declare an
439  * opclass as taking ANYCOMPATIBLEARRAY rather than ANYARRAY.
440  */
441  if (keyType == ANYELEMENTOID && opclassTup->opcintype == ANYARRAYOID)
442  {
443  keyType = get_base_element_type(to->atttypid);
444  if (!OidIsValid(keyType))
445  elog(ERROR, "could not get element type of array type %u",
446  to->atttypid);
447  }
448 
449  ReleaseSysCache(tuple);
450  }
451 
452  /*
453  * If a key type different from the heap value is specified, update
454  * the type-related fields in the index tupdesc.
455  */
456  if (OidIsValid(keyType) && keyType != to->atttypid)
457  {
458  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
459  if (!HeapTupleIsValid(tuple))
460  elog(ERROR, "cache lookup failed for type %u", keyType);
461  typeTup = (Form_pg_type) GETSTRUCT(tuple);
462 
463  to->atttypid = keyType;
464  to->atttypmod = -1;
465  to->attlen = typeTup->typlen;
466  to->attbyval = typeTup->typbyval;
467  to->attalign = typeTup->typalign;
468  to->attstorage = typeTup->typstorage;
469 
470  ReleaseSysCache(tuple);
471  }
472  }
473 
474  pfree(amroutine);
475 
476  return indexTupDesc;
477 }
478 
479 /* ----------------------------------------------------------------
480  * InitializeAttributeOids
481  * ----------------------------------------------------------------
482  */
483 static void
485  int numatts,
486  Oid indexoid)
487 {
488  TupleDesc tupleDescriptor;
489  int i;
490 
491  tupleDescriptor = RelationGetDescr(indexRelation);
492 
493  for (i = 0; i < numatts; i += 1)
494  TupleDescAttr(tupleDescriptor, i)->attrelid = indexoid;
495 }
496 
497 /* ----------------------------------------------------------------
498  * AppendAttributeTuples
499  * ----------------------------------------------------------------
500  */
501 static void
502 AppendAttributeTuples(Relation indexRelation, Datum *attopts)
503 {
504  Relation pg_attribute;
505  CatalogIndexState indstate;
506  TupleDesc indexTupDesc;
507 
508  /*
509  * open the attribute relation and its indexes
510  */
511  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
512 
513  indstate = CatalogOpenIndexes(pg_attribute);
514 
515  /*
516  * insert data from new index's tupdesc into pg_attribute
517  */
518  indexTupDesc = RelationGetDescr(indexRelation);
519 
520  InsertPgAttributeTuples(pg_attribute, indexTupDesc, InvalidOid, attopts, indstate);
521 
522  CatalogCloseIndexes(indstate);
523 
524  table_close(pg_attribute, RowExclusiveLock);
525 }
526 
527 /* ----------------------------------------------------------------
528  * UpdateIndexRelation
529  *
530  * Construct and insert a new entry in the pg_index catalog
531  * ----------------------------------------------------------------
532  */
533 static void
535  Oid heapoid,
536  Oid parentIndexId,
537  IndexInfo *indexInfo,
538  Oid *collationOids,
539  Oid *classOids,
540  int16 *coloptions,
541  bool primary,
542  bool isexclusion,
543  bool immediate,
544  bool isvalid,
545  bool isready)
546 {
547  int2vector *indkey;
548  oidvector *indcollation;
549  oidvector *indclass;
550  int2vector *indoption;
551  Datum exprsDatum;
552  Datum predDatum;
553  Datum values[Natts_pg_index];
554  bool nulls[Natts_pg_index];
555  Relation pg_index;
556  HeapTuple tuple;
557  int i;
558 
559  /*
560  * Copy the index key, opclass, and indoption info into arrays (should we
561  * make the caller pass them like this to start with?)
562  */
563  indkey = buildint2vector(NULL, indexInfo->ii_NumIndexAttrs);
564  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
565  indkey->values[i] = indexInfo->ii_IndexAttrNumbers[i];
566  indcollation = buildoidvector(collationOids, indexInfo->ii_NumIndexKeyAttrs);
567  indclass = buildoidvector(classOids, indexInfo->ii_NumIndexKeyAttrs);
568  indoption = buildint2vector(coloptions, indexInfo->ii_NumIndexKeyAttrs);
569 
570  /*
571  * Convert the index expressions (if any) to a text datum
572  */
573  if (indexInfo->ii_Expressions != NIL)
574  {
575  char *exprsString;
576 
577  exprsString = nodeToString(indexInfo->ii_Expressions);
578  exprsDatum = CStringGetTextDatum(exprsString);
579  pfree(exprsString);
580  }
581  else
582  exprsDatum = (Datum) 0;
583 
584  /*
585  * Convert the index predicate (if any) to a text datum. Note we convert
586  * implicit-AND format to normal explicit-AND for storage.
587  */
588  if (indexInfo->ii_Predicate != NIL)
589  {
590  char *predString;
591 
592  predString = nodeToString(make_ands_explicit(indexInfo->ii_Predicate));
593  predDatum = CStringGetTextDatum(predString);
594  pfree(predString);
595  }
596  else
597  predDatum = (Datum) 0;
598 
599 
600  /*
601  * open the system catalog index relation
602  */
603  pg_index = table_open(IndexRelationId, RowExclusiveLock);
604 
605  /*
606  * Build a pg_index tuple
607  */
608  MemSet(nulls, false, sizeof(nulls));
609 
610  values[Anum_pg_index_indexrelid - 1] = ObjectIdGetDatum(indexoid);
611  values[Anum_pg_index_indrelid - 1] = ObjectIdGetDatum(heapoid);
612  values[Anum_pg_index_indnatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexAttrs);
613  values[Anum_pg_index_indnkeyatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexKeyAttrs);
614  values[Anum_pg_index_indisunique - 1] = BoolGetDatum(indexInfo->ii_Unique);
615  values[Anum_pg_index_indisprimary - 1] = BoolGetDatum(primary);
616  values[Anum_pg_index_indisexclusion - 1] = BoolGetDatum(isexclusion);
617  values[Anum_pg_index_indimmediate - 1] = BoolGetDatum(immediate);
618  values[Anum_pg_index_indisclustered - 1] = BoolGetDatum(false);
619  values[Anum_pg_index_indisvalid - 1] = BoolGetDatum(isvalid);
620  values[Anum_pg_index_indcheckxmin - 1] = BoolGetDatum(false);
621  values[Anum_pg_index_indisready - 1] = BoolGetDatum(isready);
622  values[Anum_pg_index_indislive - 1] = BoolGetDatum(true);
623  values[Anum_pg_index_indisreplident - 1] = BoolGetDatum(false);
624  values[Anum_pg_index_indkey - 1] = PointerGetDatum(indkey);
625  values[Anum_pg_index_indcollation - 1] = PointerGetDatum(indcollation);
626  values[Anum_pg_index_indclass - 1] = PointerGetDatum(indclass);
627  values[Anum_pg_index_indoption - 1] = PointerGetDatum(indoption);
628  values[Anum_pg_index_indexprs - 1] = exprsDatum;
629  if (exprsDatum == (Datum) 0)
630  nulls[Anum_pg_index_indexprs - 1] = true;
631  values[Anum_pg_index_indpred - 1] = predDatum;
632  if (predDatum == (Datum) 0)
633  nulls[Anum_pg_index_indpred - 1] = true;
634 
635  tuple = heap_form_tuple(RelationGetDescr(pg_index), values, nulls);
636 
637  /*
638  * insert the tuple into the pg_index catalog
639  */
640  CatalogTupleInsert(pg_index, tuple);
641 
642  /*
643  * close the relation and free the tuple
644  */
645  table_close(pg_index, RowExclusiveLock);
646  heap_freetuple(tuple);
647 }
648 
649 
650 /*
651  * index_create
652  *
653  * heapRelation: table to build index on (suitably locked by caller)
654  * indexRelationName: what it say
655  * indexRelationId: normally, pass InvalidOid to let this routine
656  * generate an OID for the index. During bootstrap this may be
657  * nonzero to specify a preselected OID.
658  * parentIndexRelid: if creating an index partition, the OID of the
659  * parent index; otherwise InvalidOid.
660  * parentConstraintId: if creating a constraint on a partition, the OID
661  * of the constraint in the parent; otherwise InvalidOid.
662  * relFileNode: normally, pass InvalidOid to get new storage. May be
663  * nonzero to attach an existing valid build.
664  * indexInfo: same info executor uses to insert into the index
665  * indexColNames: column names to use for index (List of char *)
666  * accessMethodObjectId: OID of index AM to use
667  * tableSpaceId: OID of tablespace to use
668  * collationObjectId: array of collation OIDs, one per index column
669  * classObjectId: array of index opclass OIDs, one per index column
670  * coloptions: array of per-index-column indoption settings
671  * reloptions: AM-specific options
672  * flags: bitmask that can include any combination of these bits:
673  * INDEX_CREATE_IS_PRIMARY
674  * the index is a primary key
675  * INDEX_CREATE_ADD_CONSTRAINT:
676  * invoke index_constraint_create also
677  * INDEX_CREATE_SKIP_BUILD:
678  * skip the index_build() step for the moment; caller must do it
679  * later (typically via reindex_index())
680  * INDEX_CREATE_CONCURRENT:
681  * do not lock the table against writers. The index will be
682  * marked "invalid" and the caller must take additional steps
683  * to fix it up.
684  * INDEX_CREATE_IF_NOT_EXISTS:
685  * do not throw an error if a relation with the same name
686  * already exists.
687  * INDEX_CREATE_PARTITIONED:
688  * create a partitioned index (table must be partitioned)
689  * constr_flags: flags passed to index_constraint_create
690  * (only if INDEX_CREATE_ADD_CONSTRAINT is set)
691  * allow_system_table_mods: allow table to be a system catalog
692  * is_internal: if true, post creation hook for new index
693  * constraintId: if not NULL, receives OID of created constraint
694  *
695  * Returns the OID of the created index.
696  */
697 Oid
698 index_create(Relation heapRelation,
699  const char *indexRelationName,
700  Oid indexRelationId,
701  Oid parentIndexRelid,
702  Oid parentConstraintId,
703  Oid relFileNode,
704  IndexInfo *indexInfo,
705  List *indexColNames,
706  Oid accessMethodObjectId,
707  Oid tableSpaceId,
708  Oid *collationObjectId,
709  Oid *classObjectId,
710  int16 *coloptions,
711  Datum reloptions,
712  bits16 flags,
713  bits16 constr_flags,
714  bool allow_system_table_mods,
715  bool is_internal,
716  Oid *constraintId)
717 {
718  Oid heapRelationId = RelationGetRelid(heapRelation);
719  Relation pg_class;
720  Relation indexRelation;
721  TupleDesc indexTupDesc;
722  bool shared_relation;
723  bool mapped_relation;
724  bool is_exclusion;
725  Oid namespaceId;
726  int i;
727  char relpersistence;
728  bool isprimary = (flags & INDEX_CREATE_IS_PRIMARY) != 0;
729  bool invalid = (flags & INDEX_CREATE_INVALID) != 0;
730  bool concurrent = (flags & INDEX_CREATE_CONCURRENT) != 0;
731  bool partitioned = (flags & INDEX_CREATE_PARTITIONED) != 0;
732  char relkind;
733  TransactionId relfrozenxid;
734  MultiXactId relminmxid;
735 
736  /* constraint flags can only be set when a constraint is requested */
737  Assert((constr_flags == 0) ||
738  ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0));
739  /* partitioned indexes must never be "built" by themselves */
740  Assert(!partitioned || (flags & INDEX_CREATE_SKIP_BUILD));
741 
742  relkind = partitioned ? RELKIND_PARTITIONED_INDEX : RELKIND_INDEX;
743  is_exclusion = (indexInfo->ii_ExclusionOps != NULL);
744 
745  pg_class = table_open(RelationRelationId, RowExclusiveLock);
746 
747  /*
748  * The index will be in the same namespace as its parent table, and is
749  * shared across databases if and only if the parent is. Likewise, it
750  * will use the relfilenode map if and only if the parent does; and it
751  * inherits the parent's relpersistence.
752  */
753  namespaceId = RelationGetNamespace(heapRelation);
754  shared_relation = heapRelation->rd_rel->relisshared;
755  mapped_relation = RelationIsMapped(heapRelation);
756  relpersistence = heapRelation->rd_rel->relpersistence;
757 
758  /*
759  * check parameters
760  */
761  if (indexInfo->ii_NumIndexAttrs < 1)
762  elog(ERROR, "must index at least one column");
763 
764  if (!allow_system_table_mods &&
765  IsSystemRelation(heapRelation) &&
767  ereport(ERROR,
768  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
769  errmsg("user-defined indexes on system catalog tables are not supported")));
770 
771  /*
772  * Btree text_pattern_ops uses text_eq as the equality operator, which is
773  * fine as long as the collation is deterministic; text_eq then reduces to
774  * bitwise equality and so it is semantically compatible with the other
775  * operators and functions in that opclass. But with a nondeterministic
776  * collation, text_eq could yield results that are incompatible with the
777  * actual behavior of the index (which is determined by the opclass's
778  * comparison function). We prevent such problems by refusing creation of
779  * an index with that opclass and a nondeterministic collation.
780  *
781  * The same applies to varchar_pattern_ops and bpchar_pattern_ops. If we
782  * find more cases, we might decide to create a real mechanism for marking
783  * opclasses as incompatible with nondeterminism; but for now, this small
784  * hack suffices.
785  *
786  * Another solution is to use a special operator, not text_eq, as the
787  * equality opclass member; but that is undesirable because it would
788  * prevent index usage in many queries that work fine today.
789  */
790  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
791  {
792  Oid collation = collationObjectId[i];
793  Oid opclass = classObjectId[i];
794 
795  if (collation)
796  {
797  if ((opclass == TEXT_BTREE_PATTERN_OPS_OID ||
798  opclass == VARCHAR_BTREE_PATTERN_OPS_OID ||
799  opclass == BPCHAR_BTREE_PATTERN_OPS_OID) &&
800  !get_collation_isdeterministic(collation))
801  {
802  HeapTuple classtup;
803 
804  classtup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
805  if (!HeapTupleIsValid(classtup))
806  elog(ERROR, "cache lookup failed for operator class %u", opclass);
807  ereport(ERROR,
808  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
809  errmsg("nondeterministic collations are not supported for operator class \"%s\"",
810  NameStr(((Form_pg_opclass) GETSTRUCT(classtup))->opcname))));
811  ReleaseSysCache(classtup);
812  }
813  }
814  }
815 
816  /*
817  * Concurrent index build on a system catalog is unsafe because we tend to
818  * release locks before committing in catalogs.
819  */
820  if (concurrent &&
821  IsCatalogRelation(heapRelation))
822  ereport(ERROR,
823  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
824  errmsg("concurrent index creation on system catalog tables is not supported")));
825 
826  /*
827  * This case is currently not supported. There's no way to ask for it in
828  * the grammar with CREATE INDEX, but it can happen with REINDEX.
829  */
830  if (concurrent && is_exclusion)
831  ereport(ERROR,
832  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
833  errmsg("concurrent index creation for exclusion constraints is not supported")));
834 
835  /*
836  * We cannot allow indexing a shared relation after initdb (because
837  * there's no way to make the entry in other databases' pg_class).
838  */
839  if (shared_relation && !IsBootstrapProcessingMode())
840  ereport(ERROR,
841  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
842  errmsg("shared indexes cannot be created after initdb")));
843 
844  /*
845  * Shared relations must be in pg_global, too (last-ditch check)
846  */
847  if (shared_relation && tableSpaceId != GLOBALTABLESPACE_OID)
848  elog(ERROR, "shared relations must be placed in pg_global tablespace");
849 
850  /*
851  * Check for duplicate name (both as to the index, and as to the
852  * associated constraint if any). Such cases would fail on the relevant
853  * catalogs' unique indexes anyway, but we prefer to give a friendlier
854  * error message.
855  */
856  if (get_relname_relid(indexRelationName, namespaceId))
857  {
858  if ((flags & INDEX_CREATE_IF_NOT_EXISTS) != 0)
859  {
860  ereport(NOTICE,
861  (errcode(ERRCODE_DUPLICATE_TABLE),
862  errmsg("relation \"%s\" already exists, skipping",
863  indexRelationName)));
864  table_close(pg_class, RowExclusiveLock);
865  return InvalidOid;
866  }
867 
868  ereport(ERROR,
869  (errcode(ERRCODE_DUPLICATE_TABLE),
870  errmsg("relation \"%s\" already exists",
871  indexRelationName)));
872  }
873 
874  if ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0 &&
876  indexRelationName))
877  {
878  /*
879  * INDEX_CREATE_IF_NOT_EXISTS does not apply here, since the
880  * conflicting constraint is not an index.
881  */
882  ereport(ERROR,
884  errmsg("constraint \"%s\" for relation \"%s\" already exists",
885  indexRelationName, RelationGetRelationName(heapRelation))));
886  }
887 
888  /*
889  * construct tuple descriptor for index tuples
890  */
891  indexTupDesc = ConstructTupleDescriptor(heapRelation,
892  indexInfo,
893  indexColNames,
894  accessMethodObjectId,
895  collationObjectId,
896  classObjectId);
897 
898  /*
899  * Allocate an OID for the index, unless we were told what to use.
900  *
901  * The OID will be the relfilenode as well, so make sure it doesn't
902  * collide with either pg_class OIDs or existing physical files.
903  */
904  if (!OidIsValid(indexRelationId))
905  {
906  /* Use binary-upgrade override for pg_class.oid/relfilenode? */
907  if (IsBinaryUpgrade)
908  {
910  ereport(ERROR,
911  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
912  errmsg("pg_class index OID value not set when in binary upgrade mode")));
913 
914  indexRelationId = binary_upgrade_next_index_pg_class_oid;
916  }
917  else
918  {
919  indexRelationId =
920  GetNewRelFileNode(tableSpaceId, pg_class, relpersistence);
921  }
922  }
923 
924  /*
925  * create the index relation's relcache entry and, if necessary, the
926  * physical disk file. (If we fail further down, it's the smgr's
927  * responsibility to remove the disk file again, if any.)
928  */
929  indexRelation = heap_create(indexRelationName,
930  namespaceId,
931  tableSpaceId,
932  indexRelationId,
933  relFileNode,
934  accessMethodObjectId,
935  indexTupDesc,
936  relkind,
937  relpersistence,
938  shared_relation,
939  mapped_relation,
940  allow_system_table_mods,
941  &relfrozenxid,
942  &relminmxid);
943 
944  Assert(relfrozenxid == InvalidTransactionId);
945  Assert(relminmxid == InvalidMultiXactId);
946  Assert(indexRelationId == RelationGetRelid(indexRelation));
947 
948  /*
949  * Obtain exclusive lock on it. Although no other transactions can see it
950  * until we commit, this prevents deadlock-risk complaints from lock
951  * manager in cases such as CLUSTER.
952  */
953  LockRelation(indexRelation, AccessExclusiveLock);
954 
955  /*
956  * Fill in fields of the index's pg_class entry that are not set correctly
957  * by heap_create.
958  *
959  * XXX should have a cleaner way to create cataloged indexes
960  */
961  indexRelation->rd_rel->relowner = heapRelation->rd_rel->relowner;
962  indexRelation->rd_rel->relam = accessMethodObjectId;
963  indexRelation->rd_rel->relispartition = OidIsValid(parentIndexRelid);
964 
965  /*
966  * store index's pg_class entry
967  */
968  InsertPgClassTuple(pg_class, indexRelation,
969  RelationGetRelid(indexRelation),
970  (Datum) 0,
971  reloptions);
972 
973  /* done with pg_class */
974  table_close(pg_class, RowExclusiveLock);
975 
976  /*
977  * now update the object id's of all the attribute tuple forms in the
978  * index relation's tuple descriptor
979  */
980  InitializeAttributeOids(indexRelation,
981  indexInfo->ii_NumIndexAttrs,
982  indexRelationId);
983 
984  /*
985  * append ATTRIBUTE tuples for the index
986  */
987  AppendAttributeTuples(indexRelation, indexInfo->ii_OpclassOptions);
988 
989  /* ----------------
990  * update pg_index
991  * (append INDEX tuple)
992  *
993  * Note that this stows away a representation of "predicate".
994  * (Or, could define a rule to maintain the predicate) --Nels, Feb '92
995  * ----------------
996  */
997  UpdateIndexRelation(indexRelationId, heapRelationId, parentIndexRelid,
998  indexInfo,
999  collationObjectId, classObjectId, coloptions,
1000  isprimary, is_exclusion,
1001  (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) == 0,
1002  !concurrent && !invalid,
1003  !concurrent);
1004 
1005  /*
1006  * Register relcache invalidation on the indexes' heap relation, to
1007  * maintain consistency of its index list
1008  */
1009  CacheInvalidateRelcache(heapRelation);
1010 
1011  /* update pg_inherits and the parent's relhassubclass, if needed */
1012  if (OidIsValid(parentIndexRelid))
1013  {
1014  StoreSingleInheritance(indexRelationId, parentIndexRelid, 1);
1015  SetRelationHasSubclass(parentIndexRelid, true);
1016  }
1017 
1018  /*
1019  * Register constraint and dependencies for the index.
1020  *
1021  * If the index is from a CONSTRAINT clause, construct a pg_constraint
1022  * entry. The index will be linked to the constraint, which in turn is
1023  * linked to the table. If it's not a CONSTRAINT, we need to make a
1024  * dependency directly on the table.
1025  *
1026  * We don't need a dependency on the namespace, because there'll be an
1027  * indirect dependency via our parent table.
1028  *
1029  * During bootstrap we can't register any dependencies, and we don't try
1030  * to make a constraint either.
1031  */
1033  {
1034  ObjectAddress myself,
1035  referenced;
1036  ObjectAddresses *addrs;
1037  List *colls = NIL,
1038  *colls_no_version = NIL;
1039 
1040  ObjectAddressSet(myself, RelationRelationId, indexRelationId);
1041 
1042  if ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0)
1043  {
1044  char constraintType;
1045  ObjectAddress localaddr;
1046 
1047  if (isprimary)
1048  constraintType = CONSTRAINT_PRIMARY;
1049  else if (indexInfo->ii_Unique)
1050  constraintType = CONSTRAINT_UNIQUE;
1051  else if (is_exclusion)
1052  constraintType = CONSTRAINT_EXCLUSION;
1053  else
1054  {
1055  elog(ERROR, "constraint must be PRIMARY, UNIQUE or EXCLUDE");
1056  constraintType = 0; /* keep compiler quiet */
1057  }
1058 
1059  localaddr = index_constraint_create(heapRelation,
1060  indexRelationId,
1061  parentConstraintId,
1062  indexInfo,
1063  indexRelationName,
1064  constraintType,
1065  constr_flags,
1066  allow_system_table_mods,
1067  is_internal);
1068  if (constraintId)
1069  *constraintId = localaddr.objectId;
1070  }
1071  else
1072  {
1073  bool have_simple_col = false;
1074 
1075  addrs = new_object_addresses();
1076 
1077  /* Create auto dependencies on simply-referenced columns */
1078  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1079  {
1080  if (indexInfo->ii_IndexAttrNumbers[i] != 0)
1081  {
1082  ObjectAddressSubSet(referenced, RelationRelationId,
1083  heapRelationId,
1084  indexInfo->ii_IndexAttrNumbers[i]);
1085  add_exact_object_address(&referenced, addrs);
1086  have_simple_col = true;
1087  }
1088  }
1089 
1090  /*
1091  * If there are no simply-referenced columns, give the index an
1092  * auto dependency on the whole table. In most cases, this will
1093  * be redundant, but it might not be if the index expressions and
1094  * predicate contain no Vars or only whole-row Vars.
1095  */
1096  if (!have_simple_col)
1097  {
1098  ObjectAddressSet(referenced, RelationRelationId,
1099  heapRelationId);
1100  add_exact_object_address(&referenced, addrs);
1101  }
1102 
1104  free_object_addresses(addrs);
1105  }
1106 
1107  /*
1108  * If this is an index partition, create partition dependencies on
1109  * both the parent index and the table. (Note: these must be *in
1110  * addition to*, not instead of, all other dependencies. Otherwise
1111  * we'll be short some dependencies after DETACH PARTITION.)
1112  */
1113  if (OidIsValid(parentIndexRelid))
1114  {
1115  ObjectAddressSet(referenced, RelationRelationId, parentIndexRelid);
1116  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
1117 
1118  ObjectAddressSet(referenced, RelationRelationId, heapRelationId);
1119  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
1120  }
1121 
1122  /* Get dependencies on collations for all index keys. */
1123  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1124  {
1125  Oid colloid = collationObjectId[i];
1126 
1127  if (OidIsValid(colloid))
1128  {
1129  Oid opclass = classObjectId[i];
1130 
1131  /*
1132  * The *_pattern_ops opclasses are special: they explicitly do
1133  * not depend on collation order so we can save some effort.
1134  *
1135  * XXX With more analysis, we could also skip version tracking
1136  * for some cases like hash indexes with deterministic
1137  * collations, because they will never need to order strings.
1138  */
1139  if (opclass == TEXT_BTREE_PATTERN_OPS_OID ||
1140  opclass == VARCHAR_BTREE_PATTERN_OPS_OID ||
1141  opclass == BPCHAR_BTREE_PATTERN_OPS_OID)
1142  colls_no_version = lappend_oid(colls_no_version, colloid);
1143  else
1144  colls = lappend_oid(colls, colloid);
1145  }
1146  else
1147  {
1148  Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
1149 
1150  Assert(i < indexTupDesc->natts);
1151 
1152  /*
1153  * Even though there is no top-level collation, there may be
1154  * collations affecting ordering inside types, so look there
1155  * too.
1156  */
1157  colls = list_concat(colls, GetTypeCollations(att->atttypid));
1158  }
1159  }
1160 
1161  /*
1162  * If we have anything in both lists, keep just the versioned one to
1163  * avoid some duplication.
1164  */
1165  if (colls_no_version != NIL && colls != NIL)
1166  colls_no_version = list_difference_oid(colls_no_version, colls);
1167 
1168  /* Store the versioned and unversioned collation dependencies. */
1169  if (colls_no_version != NIL)
1170  recordDependencyOnCollations(&myself, colls_no_version, false);
1171  if (colls != NIL)
1172  recordDependencyOnCollations(&myself, colls, true);
1173 
1174  /* Store dependency on operator classes */
1175  addrs = new_object_addresses();
1176  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1177  {
1178  ObjectAddressSet(referenced, OperatorClassRelationId, classObjectId[i]);
1179  add_exact_object_address(&referenced, addrs);
1180  }
1182  free_object_addresses(addrs);
1183 
1184  /* Store dependencies on anything mentioned in index expressions */
1185  if (indexInfo->ii_Expressions)
1186  {
1188  (Node *) indexInfo->ii_Expressions,
1189  heapRelationId,
1191  DEPENDENCY_AUTO, false, true);
1192  }
1193 
1194  /* Store dependencies on anything mentioned in predicate */
1195  if (indexInfo->ii_Predicate)
1196  {
1198  (Node *) indexInfo->ii_Predicate,
1199  heapRelationId,
1201  DEPENDENCY_AUTO, false, true);
1202  }
1203  }
1204  else
1205  {
1206  /* Bootstrap mode - assert we weren't asked for constraint support */
1207  Assert((flags & INDEX_CREATE_ADD_CONSTRAINT) == 0);
1208  }
1209 
1210  /* Post creation hook for new index */
1211  InvokeObjectPostCreateHookArg(RelationRelationId,
1212  indexRelationId, 0, is_internal);
1213 
1214  /*
1215  * Advance the command counter so that we can see the newly-entered
1216  * catalog tuples for the index.
1217  */
1219 
1220  /*
1221  * In bootstrap mode, we have to fill in the index strategy structure with
1222  * information from the catalogs. If we aren't bootstrapping, then the
1223  * relcache entry has already been rebuilt thanks to sinval update during
1224  * CommandCounterIncrement.
1225  */
1227  RelationInitIndexAccessInfo(indexRelation);
1228  else
1229  Assert(indexRelation->rd_indexcxt != NULL);
1230 
1231  indexRelation->rd_index->indnkeyatts = indexInfo->ii_NumIndexKeyAttrs;
1232 
1233  /* Validate opclass-specific options */
1234  if (indexInfo->ii_OpclassOptions)
1235  for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1236  (void) index_opclass_options(indexRelation, i + 1,
1237  indexInfo->ii_OpclassOptions[i],
1238  true);
1239 
1240  /*
1241  * If this is bootstrap (initdb) time, then we don't actually fill in the
1242  * index yet. We'll be creating more indexes and classes later, so we
1243  * delay filling them in until just before we're done with bootstrapping.
1244  * Similarly, if the caller specified to skip the build then filling the
1245  * index is delayed till later (ALTER TABLE can save work in some cases
1246  * with this). Otherwise, we call the AM routine that constructs the
1247  * index.
1248  */
1250  {
1251  index_register(heapRelationId, indexRelationId, indexInfo);
1252  }
1253  else if ((flags & INDEX_CREATE_SKIP_BUILD) != 0)
1254  {
1255  /*
1256  * Caller is responsible for filling the index later on. However,
1257  * we'd better make sure that the heap relation is correctly marked as
1258  * having an index.
1259  */
1260  index_update_stats(heapRelation,
1261  true,
1262  -1.0);
1263  /* Make the above update visible */
1265  }
1266  else
1267  {
1268  index_build(heapRelation, indexRelation, indexInfo, false, true);
1269  }
1270 
1271  /*
1272  * Close the index; but we keep the lock that we acquired above until end
1273  * of transaction. Closing the heap is caller's responsibility.
1274  */
1275  index_close(indexRelation, NoLock);
1276 
1277  return indexRelationId;
1278 }
1279 
1281 {
1285 
1286 /*
1287  * Raise a warning if the recorded and current collation version don't match.
1288  * This is a callback for visitDependenciesOf().
1289  */
1290 static bool
1292  const char *version,
1293  char **new_version,
1294  void *data)
1295 {
1296  do_collation_version_check_context *context = data;
1297  char *current_version;
1298 
1299  /* We only care about dependencies on collations with a version. */
1300  if (!version || otherObject->classId != CollationRelationId)
1301  return false;
1302 
1303  /* Ask the provider for the current version. Give up if unsupported. */
1304  current_version = get_collation_version_for_oid(otherObject->objectId,
1305  false);
1306  if (!current_version)
1307  return false;
1308 
1309  /*
1310  * We don't expect too many duplicates, but it's possible, and we don't
1311  * want to generate duplicate warnings.
1312  */
1313  if (list_member_oid(context->warned_colls, otherObject->objectId))
1314  return false;
1315 
1316  /* Do they match? */
1317  if (strcmp(current_version, version) != 0)
1318  {
1319  /*
1320  * The version has changed, probably due to an OS/library upgrade or
1321  * streaming replication between different OS/library versions.
1322  */
1323  ereport(WARNING,
1324  (errmsg("index \"%s\" depends on collation \"%s\" version \"%s\", but the current version is \"%s\"",
1325  get_rel_name(context->relid),
1326  get_collation_name(otherObject->objectId),
1327  version,
1328  current_version),
1329  errdetail("The index may be corrupted due to changes in sort order."),
1330  errhint("REINDEX to avoid the risk of corruption.")));
1331 
1332  /* Remember not to complain about this collation again. */
1333  context->warned_colls = lappend_oid(context->warned_colls,
1334  otherObject->objectId);
1335  }
1336 
1337  return false;
1338 }
1339 
1340 /* index_check_collation_versions
1341  * Check the collation version for all dependencies on the given index.
1342  */
1343 void
1345 {
1347  ObjectAddress object;
1348 
1349  /*
1350  * The callback needs the relid for error messages, and some scratch space
1351  * to avoid duplicate warnings.
1352  */
1353  context.relid = relid;
1354  context.warned_colls = NIL;
1355 
1356  object.classId = RelationRelationId;
1357  object.objectId = relid;
1358  object.objectSubId = 0;
1359 
1360  visitDependenciesOf(&object, &do_collation_version_check, &context);
1361 
1362  list_free(context.warned_colls);
1363 }
1364 
1365 /*
1366  * Update the version for collations. A callback for visitDependenciesOf().
1367  */
1368 static bool
1370  const char *version,
1371  char **new_version,
1372  void *data)
1373 {
1374  Oid *coll = data;
1375 
1376  /* We only care about dependencies on collations with versions. */
1377  if (!version || otherObject->classId != CollationRelationId)
1378  return false;
1379 
1380  /* If we're only trying to update one collation, skip others. */
1381  if (OidIsValid(*coll) && otherObject->objectId != *coll)
1382  return false;
1383 
1384  *new_version = get_collation_version_for_oid(otherObject->objectId, false);
1385 
1386  return true;
1387 }
1388 
1389 /*
1390  * Record the current versions of one or all collations that an index depends
1391  * on. InvalidOid means all.
1392  */
1393 void
1395 {
1396  ObjectAddress object;
1397 
1398  object.classId = RelationRelationId;
1399  object.objectId = relid;
1400  object.objectSubId = 0;
1402 }
1403 
1404 /*
1405  * index_concurrently_create_copy
1406  *
1407  * Create concurrently an index based on the definition of the one provided by
1408  * caller. The index is inserted into catalogs and needs to be built later
1409  * on. This is called during concurrent reindex processing.
1410  *
1411  * "tablespaceOid" is the tablespace to use for this index.
1412  */
1413 Oid
1415  Oid tablespaceOid, const char *newName)
1416 {
1417  Relation indexRelation;
1418  IndexInfo *oldInfo,
1419  *newInfo;
1420  Oid newIndexId = InvalidOid;
1421  HeapTuple indexTuple,
1422  classTuple;
1423  Datum indclassDatum,
1424  colOptionDatum,
1425  optionDatum;
1426  oidvector *indclass;
1427  int2vector *indcoloptions;
1428  bool isnull;
1429  List *indexColNames = NIL;
1430  List *indexExprs = NIL;
1431  List *indexPreds = NIL;
1432 
1433  indexRelation = index_open(oldIndexId, RowExclusiveLock);
1434 
1435  /* The new index needs some information from the old index */
1436  oldInfo = BuildIndexInfo(indexRelation);
1437 
1438  /*
1439  * Concurrent build of an index with exclusion constraints is not
1440  * supported.
1441  */
1442  if (oldInfo->ii_ExclusionOps != NULL)
1443  ereport(ERROR,
1444  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1445  errmsg("concurrent index creation for exclusion constraints is not supported")));
1446 
1447  /* Get the array of class and column options IDs from index info */
1448  indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId));
1449  if (!HeapTupleIsValid(indexTuple))
1450  elog(ERROR, "cache lookup failed for index %u", oldIndexId);
1451  indclassDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1452  Anum_pg_index_indclass, &isnull);
1453  Assert(!isnull);
1454  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1455 
1456  colOptionDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1457  Anum_pg_index_indoption, &isnull);
1458  Assert(!isnull);
1459  indcoloptions = (int2vector *) DatumGetPointer(colOptionDatum);
1460 
1461  /* Fetch options of index if any */
1462  classTuple = SearchSysCache1(RELOID, oldIndexId);
1463  if (!HeapTupleIsValid(classTuple))
1464  elog(ERROR, "cache lookup failed for relation %u", oldIndexId);
1465  optionDatum = SysCacheGetAttr(RELOID, classTuple,
1466  Anum_pg_class_reloptions, &isnull);
1467 
1468  /*
1469  * Fetch the list of expressions and predicates directly from the
1470  * catalogs. This cannot rely on the information from IndexInfo of the
1471  * old index as these have been flattened for the planner.
1472  */
1473  if (oldInfo->ii_Expressions != NIL)
1474  {
1475  Datum exprDatum;
1476  char *exprString;
1477 
1478  exprDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1479  Anum_pg_index_indexprs, &isnull);
1480  Assert(!isnull);
1481  exprString = TextDatumGetCString(exprDatum);
1482  indexExprs = (List *) stringToNode(exprString);
1483  pfree(exprString);
1484  }
1485  if (oldInfo->ii_Predicate != NIL)
1486  {
1487  Datum predDatum;
1488  char *predString;
1489 
1490  predDatum = SysCacheGetAttr(INDEXRELID, indexTuple,
1491  Anum_pg_index_indpred, &isnull);
1492  Assert(!isnull);
1493  predString = TextDatumGetCString(predDatum);
1494  indexPreds = (List *) stringToNode(predString);
1495 
1496  /* Also convert to implicit-AND format */
1497  indexPreds = make_ands_implicit((Expr *) indexPreds);
1498  pfree(predString);
1499  }
1500 
1501  /*
1502  * Build the index information for the new index. Note that rebuild of
1503  * indexes with exclusion constraints is not supported, hence there is no
1504  * need to fill all the ii_Exclusion* fields.
1505  */
1506  newInfo = makeIndexInfo(oldInfo->ii_NumIndexAttrs,
1507  oldInfo->ii_NumIndexKeyAttrs,
1508  oldInfo->ii_Am,
1509  indexExprs,
1510  indexPreds,
1511  oldInfo->ii_Unique,
1512  false, /* not ready for inserts */
1513  true);
1514 
1515  /*
1516  * Extract the list of column names and the column numbers for the new
1517  * index information. All this information will be used for the index
1518  * creation.
1519  */
1520  for (int i = 0; i < oldInfo->ii_NumIndexAttrs; i++)
1521  {
1522  TupleDesc indexTupDesc = RelationGetDescr(indexRelation);
1523  Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
1524 
1525  indexColNames = lappend(indexColNames, NameStr(att->attname));
1526  newInfo->ii_IndexAttrNumbers[i] = oldInfo->ii_IndexAttrNumbers[i];
1527  }
1528 
1529  /*
1530  * Now create the new index.
1531  *
1532  * For a partition index, we adjust the partition dependency later, to
1533  * ensure a consistent state at all times. That is why parentIndexRelid
1534  * is not set here.
1535  */
1536  newIndexId = index_create(heapRelation,
1537  newName,
1538  InvalidOid, /* indexRelationId */
1539  InvalidOid, /* parentIndexRelid */
1540  InvalidOid, /* parentConstraintId */
1541  InvalidOid, /* relFileNode */
1542  newInfo,
1543  indexColNames,
1544  indexRelation->rd_rel->relam,
1545  tablespaceOid,
1546  indexRelation->rd_indcollation,
1547  indclass->values,
1548  indcoloptions->values,
1549  optionDatum,
1551  0,
1552  true, /* allow table to be a system catalog? */
1553  false, /* is_internal? */
1554  NULL);
1555 
1556  /* Close the relations used and clean up */
1557  index_close(indexRelation, NoLock);
1558  ReleaseSysCache(indexTuple);
1559  ReleaseSysCache(classTuple);
1560 
1561  return newIndexId;
1562 }
1563 
1564 /*
1565  * index_concurrently_build
1566  *
1567  * Build index for a concurrent operation. Low-level locks are taken when
1568  * this operation is performed to prevent only schema changes, but they need
1569  * to be kept until the end of the transaction performing this operation.
1570  * 'indexOid' refers to an index relation OID already created as part of
1571  * previous processing, and 'heapOid' refers to its parent heap relation.
1572  */
1573 void
1575  Oid indexRelationId)
1576 {
1577  Relation heapRel;
1578  Relation indexRelation;
1579  IndexInfo *indexInfo;
1580 
1581  /* This had better make sure that a snapshot is active */
1583 
1584  /* Open and lock the parent heap relation */
1585  heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
1586 
1587  /* And the target index relation */
1588  indexRelation = index_open(indexRelationId, RowExclusiveLock);
1589 
1590  /*
1591  * We have to re-build the IndexInfo struct, since it was lost in the
1592  * commit of the transaction where this concurrent index was created at
1593  * the catalog level.
1594  */
1595  indexInfo = BuildIndexInfo(indexRelation);
1596  Assert(!indexInfo->ii_ReadyForInserts);
1597  indexInfo->ii_Concurrent = true;
1598  indexInfo->ii_BrokenHotChain = false;
1599 
1600  /* Now build the index */
1601  index_build(heapRel, indexRelation, indexInfo, false, true);
1602 
1603  /* Close both the relations, but keep the locks */
1604  table_close(heapRel, NoLock);
1605  index_close(indexRelation, NoLock);
1606 
1607  /*
1608  * Update the pg_index row to mark the index as ready for inserts. Once we
1609  * commit this transaction, any new transactions that open the table must
1610  * insert new entries into the index for insertions and non-HOT updates.
1611  */
1613 }
1614 
1615 /*
1616  * index_concurrently_swap
1617  *
1618  * Swap name, dependencies, and constraints of the old index over to the new
1619  * index, while marking the old index as invalid and the new as valid.
1620  */
1621 void
1622 index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
1623 {
1624  Relation pg_class,
1625  pg_index,
1626  pg_constraint,
1627  pg_trigger;
1628  Relation oldClassRel,
1629  newClassRel;
1630  HeapTuple oldClassTuple,
1631  newClassTuple;
1632  Form_pg_class oldClassForm,
1633  newClassForm;
1634  HeapTuple oldIndexTuple,
1635  newIndexTuple;
1636  Form_pg_index oldIndexForm,
1637  newIndexForm;
1638  bool isPartition;
1639  Oid indexConstraintOid;
1640  List *constraintOids = NIL;
1641  ListCell *lc;
1642 
1643  /*
1644  * Take a necessary lock on the old and new index before swapping them.
1645  */
1646  oldClassRel = relation_open(oldIndexId, ShareUpdateExclusiveLock);
1647  newClassRel = relation_open(newIndexId, ShareUpdateExclusiveLock);
1648 
1649  /* Now swap names and dependencies of those indexes */
1650  pg_class = table_open(RelationRelationId, RowExclusiveLock);
1651 
1652  oldClassTuple = SearchSysCacheCopy1(RELOID,
1653  ObjectIdGetDatum(oldIndexId));
1654  if (!HeapTupleIsValid(oldClassTuple))
1655  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1656  newClassTuple = SearchSysCacheCopy1(RELOID,
1657  ObjectIdGetDatum(newIndexId));
1658  if (!HeapTupleIsValid(newClassTuple))
1659  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1660 
1661  oldClassForm = (Form_pg_class) GETSTRUCT(oldClassTuple);
1662  newClassForm = (Form_pg_class) GETSTRUCT(newClassTuple);
1663 
1664  /* Swap the names */
1665  namestrcpy(&newClassForm->relname, NameStr(oldClassForm->relname));
1666  namestrcpy(&oldClassForm->relname, oldName);
1667 
1668  /* Swap the partition flags to track inheritance properly */
1669  isPartition = newClassForm->relispartition;
1670  newClassForm->relispartition = oldClassForm->relispartition;
1671  oldClassForm->relispartition = isPartition;
1672 
1673  CatalogTupleUpdate(pg_class, &oldClassTuple->t_self, oldClassTuple);
1674  CatalogTupleUpdate(pg_class, &newClassTuple->t_self, newClassTuple);
1675 
1676  heap_freetuple(oldClassTuple);
1677  heap_freetuple(newClassTuple);
1678 
1679  /* Now swap index info */
1680  pg_index = table_open(IndexRelationId, RowExclusiveLock);
1681 
1682  oldIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1683  ObjectIdGetDatum(oldIndexId));
1684  if (!HeapTupleIsValid(oldIndexTuple))
1685  elog(ERROR, "could not find tuple for relation %u", oldIndexId);
1686  newIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1687  ObjectIdGetDatum(newIndexId));
1688  if (!HeapTupleIsValid(newIndexTuple))
1689  elog(ERROR, "could not find tuple for relation %u", newIndexId);
1690 
1691  oldIndexForm = (Form_pg_index) GETSTRUCT(oldIndexTuple);
1692  newIndexForm = (Form_pg_index) GETSTRUCT(newIndexTuple);
1693 
1694  /*
1695  * Copy constraint flags from the old index. This is safe because the old
1696  * index guaranteed uniqueness.
1697  */
1698  newIndexForm->indisprimary = oldIndexForm->indisprimary;
1699  oldIndexForm->indisprimary = false;
1700  newIndexForm->indisexclusion = oldIndexForm->indisexclusion;
1701  oldIndexForm->indisexclusion = false;
1702  newIndexForm->indimmediate = oldIndexForm->indimmediate;
1703  oldIndexForm->indimmediate = true;
1704 
1705  /* Preserve indisreplident in the new index */
1706  newIndexForm->indisreplident = oldIndexForm->indisreplident;
1707 
1708  /* Preserve indisclustered in the new index */
1709  newIndexForm->indisclustered = oldIndexForm->indisclustered;
1710 
1711  /*
1712  * Mark the new index as valid, and the old index as invalid similarly to
1713  * what index_set_state_flags() does.
1714  */
1715  newIndexForm->indisvalid = true;
1716  oldIndexForm->indisvalid = false;
1717  oldIndexForm->indisclustered = false;
1718  oldIndexForm->indisreplident = false;
1719 
1720  CatalogTupleUpdate(pg_index, &oldIndexTuple->t_self, oldIndexTuple);
1721  CatalogTupleUpdate(pg_index, &newIndexTuple->t_self, newIndexTuple);
1722 
1723  heap_freetuple(oldIndexTuple);
1724  heap_freetuple(newIndexTuple);
1725 
1726  /*
1727  * Move constraints and triggers over to the new index
1728  */
1729 
1730  constraintOids = get_index_ref_constraints(oldIndexId);
1731 
1732  indexConstraintOid = get_index_constraint(oldIndexId);
1733 
1734  if (OidIsValid(indexConstraintOid))
1735  constraintOids = lappend_oid(constraintOids, indexConstraintOid);
1736 
1737  pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
1738  pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
1739 
1740  foreach(lc, constraintOids)
1741  {
1742  HeapTuple constraintTuple,
1743  triggerTuple;
1744  Form_pg_constraint conForm;
1745  ScanKeyData key[1];
1746  SysScanDesc scan;
1747  Oid constraintOid = lfirst_oid(lc);
1748 
1749  /* Move the constraint from the old to the new index */
1750  constraintTuple = SearchSysCacheCopy1(CONSTROID,
1751  ObjectIdGetDatum(constraintOid));
1752  if (!HeapTupleIsValid(constraintTuple))
1753  elog(ERROR, "could not find tuple for constraint %u", constraintOid);
1754 
1755  conForm = ((Form_pg_constraint) GETSTRUCT(constraintTuple));
1756 
1757  if (conForm->conindid == oldIndexId)
1758  {
1759  conForm->conindid = newIndexId;
1760 
1761  CatalogTupleUpdate(pg_constraint, &constraintTuple->t_self, constraintTuple);
1762  }
1763 
1764  heap_freetuple(constraintTuple);
1765 
1766  /* Search for trigger records */
1767  ScanKeyInit(&key[0],
1768  Anum_pg_trigger_tgconstraint,
1769  BTEqualStrategyNumber, F_OIDEQ,
1770  ObjectIdGetDatum(constraintOid));
1771 
1772  scan = systable_beginscan(pg_trigger, TriggerConstraintIndexId, true,
1773  NULL, 1, key);
1774 
1775  while (HeapTupleIsValid((triggerTuple = systable_getnext(scan))))
1776  {
1777  Form_pg_trigger tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1778 
1779  if (tgForm->tgconstrindid != oldIndexId)
1780  continue;
1781 
1782  /* Make a modifiable copy */
1783  triggerTuple = heap_copytuple(triggerTuple);
1784  tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1785 
1786  tgForm->tgconstrindid = newIndexId;
1787 
1788  CatalogTupleUpdate(pg_trigger, &triggerTuple->t_self, triggerTuple);
1789 
1790  heap_freetuple(triggerTuple);
1791  }
1792 
1793  systable_endscan(scan);
1794  }
1795 
1796  /*
1797  * Move comment if any
1798  */
1799  {
1800  Relation description;
1801  ScanKeyData skey[3];
1802  SysScanDesc sd;
1803  HeapTuple tuple;
1804  Datum values[Natts_pg_description] = {0};
1805  bool nulls[Natts_pg_description] = {0};
1806  bool replaces[Natts_pg_description] = {0};
1807 
1808  values[Anum_pg_description_objoid - 1] = ObjectIdGetDatum(newIndexId);
1809  replaces[Anum_pg_description_objoid - 1] = true;
1810 
1811  ScanKeyInit(&skey[0],
1812  Anum_pg_description_objoid,
1813  BTEqualStrategyNumber, F_OIDEQ,
1814  ObjectIdGetDatum(oldIndexId));
1815  ScanKeyInit(&skey[1],
1816  Anum_pg_description_classoid,
1817  BTEqualStrategyNumber, F_OIDEQ,
1818  ObjectIdGetDatum(RelationRelationId));
1819  ScanKeyInit(&skey[2],
1820  Anum_pg_description_objsubid,
1821  BTEqualStrategyNumber, F_INT4EQ,
1822  Int32GetDatum(0));
1823 
1824  description = table_open(DescriptionRelationId, RowExclusiveLock);
1825 
1826  sd = systable_beginscan(description, DescriptionObjIndexId, true,
1827  NULL, 3, skey);
1828 
1829  while ((tuple = systable_getnext(sd)) != NULL)
1830  {
1831  tuple = heap_modify_tuple(tuple, RelationGetDescr(description),
1832  values, nulls, replaces);
1833  CatalogTupleUpdate(description, &tuple->t_self, tuple);
1834 
1835  break; /* Assume there can be only one match */
1836  }
1837 
1838  systable_endscan(sd);
1839  table_close(description, NoLock);
1840  }
1841 
1842  /*
1843  * Swap inheritance relationship with parent index
1844  */
1845  if (get_rel_relispartition(oldIndexId))
1846  {
1847  List *ancestors = get_partition_ancestors(oldIndexId);
1848  Oid parentIndexRelid = linitial_oid(ancestors);
1849 
1850  DeleteInheritsTuple(oldIndexId, parentIndexRelid, false, NULL);
1851  StoreSingleInheritance(newIndexId, parentIndexRelid, 1);
1852 
1853  list_free(ancestors);
1854  }
1855 
1856  /*
1857  * Swap all dependencies of and on the old index to the new one, and
1858  * vice-versa. Note that a call to CommandCounterIncrement() would cause
1859  * duplicate entries in pg_depend, so this should not be done.
1860  */
1861  changeDependenciesOf(RelationRelationId, newIndexId, oldIndexId);
1862  changeDependenciesOn(RelationRelationId, newIndexId, oldIndexId);
1863 
1864  changeDependenciesOf(RelationRelationId, oldIndexId, newIndexId);
1865  changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId);
1866 
1867  /* Now we have the old index's collation versions, so fix that. */
1870 
1871  /*
1872  * Copy over statistics from old to new index
1873  */
1874  {
1875  PgStat_StatTabEntry *tabentry;
1876 
1877  tabentry = pgstat_fetch_stat_tabentry(oldIndexId);
1878  if (tabentry)
1879  {
1880  if (newClassRel->pgstat_info)
1881  {
1882  newClassRel->pgstat_info->t_counts.t_numscans = tabentry->numscans;
1883  newClassRel->pgstat_info->t_counts.t_tuples_returned = tabentry->tuples_returned;
1884  newClassRel->pgstat_info->t_counts.t_tuples_fetched = tabentry->tuples_fetched;
1885  newClassRel->pgstat_info->t_counts.t_blocks_fetched = tabentry->blocks_fetched;
1886  newClassRel->pgstat_info->t_counts.t_blocks_hit = tabentry->blocks_hit;
1887 
1888  /*
1889  * The data will be sent by the next pgstat_report_stat()
1890  * call.
1891  */
1892  }
1893  }
1894  }
1895 
1896  /* Copy data of pg_statistic from the old index to the new one */
1897  CopyStatistics(oldIndexId, newIndexId);
1898 
1899  /* Copy pg_attribute.attstattarget for each index attribute */
1900  {
1901  HeapTuple attrTuple;
1902  Relation pg_attribute;
1903  SysScanDesc scan;
1904  ScanKeyData key[1];
1905 
1906  pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
1907  ScanKeyInit(&key[0],
1908  Anum_pg_attribute_attrelid,
1909  BTEqualStrategyNumber, F_OIDEQ,
1910  ObjectIdGetDatum(newIndexId));
1911  scan = systable_beginscan(pg_attribute, AttributeRelidNumIndexId,
1912  true, NULL, 1, key);
1913 
1914  while (HeapTupleIsValid((attrTuple = systable_getnext(scan))))
1915  {
1916  Form_pg_attribute att = (Form_pg_attribute) GETSTRUCT(attrTuple);
1917  Datum repl_val[Natts_pg_attribute];
1918  bool repl_null[Natts_pg_attribute];
1919  bool repl_repl[Natts_pg_attribute];
1920  int attstattarget;
1921  HeapTuple newTuple;
1922 
1923  /* Ignore dropped columns */
1924  if (att->attisdropped)
1925  continue;
1926 
1927  /*
1928  * Get attstattarget from the old index and refresh the new value.
1929  */
1930  attstattarget = get_attstattarget(oldIndexId, att->attnum);
1931 
1932  /* no need for a refresh if both match */
1933  if (attstattarget == att->attstattarget)
1934  continue;
1935 
1936  memset(repl_val, 0, sizeof(repl_val));
1937  memset(repl_null, false, sizeof(repl_null));
1938  memset(repl_repl, false, sizeof(repl_repl));
1939 
1940  repl_repl[Anum_pg_attribute_attstattarget - 1] = true;
1941  repl_val[Anum_pg_attribute_attstattarget - 1] = Int32GetDatum(attstattarget);
1942 
1943  newTuple = heap_modify_tuple(attrTuple,
1944  RelationGetDescr(pg_attribute),
1945  repl_val, repl_null, repl_repl);
1946  CatalogTupleUpdate(pg_attribute, &newTuple->t_self, newTuple);
1947 
1948  heap_freetuple(newTuple);
1949  }
1950 
1951  systable_endscan(scan);
1952  table_close(pg_attribute, RowExclusiveLock);
1953  }
1954 
1955  /* Close relations */
1956  table_close(pg_class, RowExclusiveLock);
1957  table_close(pg_index, RowExclusiveLock);
1958  table_close(pg_constraint, RowExclusiveLock);
1959  table_close(pg_trigger, RowExclusiveLock);
1960 
1961  /* The lock taken previously is not released until the end of transaction */
1962  relation_close(oldClassRel, NoLock);
1963  relation_close(newClassRel, NoLock);
1964 }
1965 
1966 /*
1967  * index_concurrently_set_dead
1968  *
1969  * Perform the last invalidation stage of DROP INDEX CONCURRENTLY or REINDEX
1970  * CONCURRENTLY before actually dropping the index. After calling this
1971  * function, the index is seen by all the backends as dead. Low-level locks
1972  * taken here are kept until the end of the transaction calling this function.
1973  */
1974 void
1976 {
1977  Relation userHeapRelation;
1978  Relation userIndexRelation;
1979 
1980  /*
1981  * No more predicate locks will be acquired on this index, and we're about
1982  * to stop doing inserts into the index which could show conflicts with
1983  * existing predicate locks, so now is the time to move them to the heap
1984  * relation.
1985  */
1986  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1987  userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1988  TransferPredicateLocksToHeapRelation(userIndexRelation);
1989 
1990  /*
1991  * Now we are sure that nobody uses the index for queries; they just might
1992  * have it open for updating it. So now we can unset indisready and
1993  * indislive, then wait till nobody could be using it at all anymore.
1994  */
1996 
1997  /*
1998  * Invalidate the relcache for the table, so that after this commit all
1999  * sessions will refresh the table's index list. Forgetting just the
2000  * index's relcache entry is not enough.
2001  */
2002  CacheInvalidateRelcache(userHeapRelation);
2003 
2004  /*
2005  * Close the relations again, though still holding session lock.
2006  */
2007  table_close(userHeapRelation, NoLock);
2008  index_close(userIndexRelation, NoLock);
2009 }
2010 
2011 /*
2012  * index_constraint_create
2013  *
2014  * Set up a constraint associated with an index. Return the new constraint's
2015  * address.
2016  *
2017  * heapRelation: table owning the index (must be suitably locked by caller)
2018  * indexRelationId: OID of the index
2019  * parentConstraintId: if constraint is on a partition, the OID of the
2020  * constraint in the parent.
2021  * indexInfo: same info executor uses to insert into the index
2022  * constraintName: what it say (generally, should match name of index)
2023  * constraintType: one of CONSTRAINT_PRIMARY, CONSTRAINT_UNIQUE, or
2024  * CONSTRAINT_EXCLUSION
2025  * flags: bitmask that can include any combination of these bits:
2026  * INDEX_CONSTR_CREATE_MARK_AS_PRIMARY: index is a PRIMARY KEY
2027  * INDEX_CONSTR_CREATE_DEFERRABLE: constraint is DEFERRABLE
2028  * INDEX_CONSTR_CREATE_INIT_DEFERRED: constraint is INITIALLY DEFERRED
2029  * INDEX_CONSTR_CREATE_UPDATE_INDEX: update the pg_index row
2030  * INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS: remove existing dependencies
2031  * of index on table's columns
2032  * allow_system_table_mods: allow table to be a system catalog
2033  * is_internal: index is constructed due to internal process
2034  */
2037  Oid indexRelationId,
2038  Oid parentConstraintId,
2039  IndexInfo *indexInfo,
2040  const char *constraintName,
2041  char constraintType,
2042  bits16 constr_flags,
2043  bool allow_system_table_mods,
2044  bool is_internal)
2045 {
2046  Oid namespaceId = RelationGetNamespace(heapRelation);
2047  ObjectAddress myself,
2048  idxaddr;
2049  Oid conOid;
2050  bool deferrable;
2051  bool initdeferred;
2052  bool mark_as_primary;
2053  bool islocal;
2054  bool noinherit;
2055  int inhcount;
2056 
2057  deferrable = (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) != 0;
2058  initdeferred = (constr_flags & INDEX_CONSTR_CREATE_INIT_DEFERRED) != 0;
2059  mark_as_primary = (constr_flags & INDEX_CONSTR_CREATE_MARK_AS_PRIMARY) != 0;
2060 
2061  /* constraint creation support doesn't work while bootstrapping */
2063 
2064  /* enforce system-table restriction */
2065  if (!allow_system_table_mods &&
2066  IsSystemRelation(heapRelation) &&
2068  ereport(ERROR,
2069  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2070  errmsg("user-defined indexes on system catalog tables are not supported")));
2071 
2072  /* primary/unique constraints shouldn't have any expressions */
2073  if (indexInfo->ii_Expressions &&
2074  constraintType != CONSTRAINT_EXCLUSION)
2075  elog(ERROR, "constraints cannot have index expressions");
2076 
2077  /*
2078  * If we're manufacturing a constraint for a pre-existing index, we need
2079  * to get rid of the existing auto dependencies for the index (the ones
2080  * that index_create() would have made instead of calling this function).
2081  *
2082  * Note: this code would not necessarily do the right thing if the index
2083  * has any expressions or predicate, but we'd never be turning such an
2084  * index into a UNIQUE or PRIMARY KEY constraint.
2085  */
2086  if (constr_flags & INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS)
2087  deleteDependencyRecordsForClass(RelationRelationId, indexRelationId,
2088  RelationRelationId, DEPENDENCY_AUTO);
2089 
2090  if (OidIsValid(parentConstraintId))
2091  {
2092  islocal = false;
2093  inhcount = 1;
2094  noinherit = false;
2095  }
2096  else
2097  {
2098  islocal = true;
2099  inhcount = 0;
2100  noinherit = true;
2101  }
2102 
2103  /*
2104  * Construct a pg_constraint entry.
2105  */
2106  conOid = CreateConstraintEntry(constraintName,
2107  namespaceId,
2108  constraintType,
2109  deferrable,
2110  initdeferred,
2111  true,
2112  parentConstraintId,
2113  RelationGetRelid(heapRelation),
2114  indexInfo->ii_IndexAttrNumbers,
2115  indexInfo->ii_NumIndexKeyAttrs,
2116  indexInfo->ii_NumIndexAttrs,
2117  InvalidOid, /* no domain */
2118  indexRelationId, /* index OID */
2119  InvalidOid, /* no foreign key */
2120  NULL,
2121  NULL,
2122  NULL,
2123  NULL,
2124  0,
2125  ' ',
2126  ' ',
2127  ' ',
2128  indexInfo->ii_ExclusionOps,
2129  NULL, /* no check constraint */
2130  NULL,
2131  islocal,
2132  inhcount,
2133  noinherit,
2134  is_internal);
2135 
2136  /*
2137  * Register the index as internally dependent on the constraint.
2138  *
2139  * Note that the constraint has a dependency on the table, so we don't
2140  * need (or want) any direct dependency from the index to the table.
2141  */
2142  ObjectAddressSet(myself, ConstraintRelationId, conOid);
2143  ObjectAddressSet(idxaddr, RelationRelationId, indexRelationId);
2144  recordDependencyOn(&idxaddr, &myself, DEPENDENCY_INTERNAL);
2145 
2146  /*
2147  * Also, if this is a constraint on a partition, give it partition-type
2148  * dependencies on the parent constraint as well as the table.
2149  */
2150  if (OidIsValid(parentConstraintId))
2151  {
2152  ObjectAddress referenced;
2153 
2154  ObjectAddressSet(referenced, ConstraintRelationId, parentConstraintId);
2155  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
2156  ObjectAddressSet(referenced, RelationRelationId,
2157  RelationGetRelid(heapRelation));
2158  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
2159  }
2160 
2161  /*
2162  * If the constraint is deferrable, create the deferred uniqueness
2163  * checking trigger. (The trigger will be given an internal dependency on
2164  * the constraint by CreateTrigger.)
2165  */
2166  if (deferrable)
2167  {
2169 
2170  trigger->replace = false;
2171  trigger->isconstraint = true;
2172  trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
2173  "PK_ConstraintTrigger" :
2174  "Unique_ConstraintTrigger";
2175  trigger->relation = NULL;
2176  trigger->funcname = SystemFuncName("unique_key_recheck");
2177  trigger->args = NIL;
2178  trigger->row = true;
2179  trigger->timing = TRIGGER_TYPE_AFTER;
2180  trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;
2181  trigger->columns = NIL;
2182  trigger->whenClause = NULL;
2183  trigger->transitionRels = NIL;
2184  trigger->deferrable = true;
2185  trigger->initdeferred = initdeferred;
2186  trigger->constrrel = NULL;
2187 
2188  (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
2189  InvalidOid, conOid, indexRelationId, InvalidOid,
2190  InvalidOid, NULL, true, false);
2191  }
2192 
2193  /*
2194  * If needed, mark the index as primary and/or deferred in pg_index.
2195  *
2196  * Note: When making an existing index into a constraint, caller must have
2197  * a table lock that prevents concurrent table updates; otherwise, there
2198  * is a risk that concurrent readers of the table will miss seeing this
2199  * index at all.
2200  */
2201  if ((constr_flags & INDEX_CONSTR_CREATE_UPDATE_INDEX) &&
2202  (mark_as_primary || deferrable))
2203  {
2204  Relation pg_index;
2205  HeapTuple indexTuple;
2206  Form_pg_index indexForm;
2207  bool dirty = false;
2208 
2209  pg_index = table_open(IndexRelationId, RowExclusiveLock);
2210 
2211  indexTuple = SearchSysCacheCopy1(INDEXRELID,
2212  ObjectIdGetDatum(indexRelationId));
2213  if (!HeapTupleIsValid(indexTuple))
2214  elog(ERROR, "cache lookup failed for index %u", indexRelationId);
2215  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
2216 
2217  if (mark_as_primary && !indexForm->indisprimary)
2218  {
2219  indexForm->indisprimary = true;
2220  dirty = true;
2221  }
2222 
2223  if (deferrable && indexForm->indimmediate)
2224  {
2225  indexForm->indimmediate = false;
2226  dirty = true;
2227  }
2228 
2229  if (dirty)
2230  {
2231  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
2232 
2233  InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
2234  InvalidOid, is_internal);
2235  }
2236 
2237  heap_freetuple(indexTuple);
2238  table_close(pg_index, RowExclusiveLock);
2239  }
2240 
2241  return myself;
2242 }
2243 
2244 /*
2245  * index_drop
2246  *
2247  * NOTE: this routine should now only be called through performDeletion(),
2248  * else associated dependencies won't be cleaned up.
2249  *
2250  * If concurrent is true, do a DROP INDEX CONCURRENTLY. If concurrent is
2251  * false but concurrent_lock_mode is true, then do a normal DROP INDEX but
2252  * take a lock for CONCURRENTLY processing. That is used as part of REINDEX
2253  * CONCURRENTLY.
2254  */
2255 void
2256 index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
2257 {
2258  Oid heapId;
2259  Relation userHeapRelation;
2260  Relation userIndexRelation;
2261  Relation indexRelation;
2262  HeapTuple tuple;
2263  bool hasexprs;
2264  LockRelId heaprelid,
2265  indexrelid;
2266  LOCKTAG heaplocktag;
2267  LOCKMODE lockmode;
2268 
2269  /*
2270  * A temporary relation uses a non-concurrent DROP. Other backends can't
2271  * access a temporary relation, so there's no harm in grabbing a stronger
2272  * lock (see comments in RemoveRelations), and a non-concurrent DROP is
2273  * more efficient.
2274  */
2275  Assert(get_rel_persistence(indexId) != RELPERSISTENCE_TEMP ||
2276  (!concurrent && !concurrent_lock_mode));
2277 
2278  /*
2279  * To drop an index safely, we must grab exclusive lock on its parent
2280  * table. Exclusive lock on the index alone is insufficient because
2281  * another backend might be about to execute a query on the parent table.
2282  * If it relies on a previously cached list of index OIDs, then it could
2283  * attempt to access the just-dropped index. We must therefore take a
2284  * table lock strong enough to prevent all queries on the table from
2285  * proceeding until we commit and send out a shared-cache-inval notice
2286  * that will make them update their index lists.
2287  *
2288  * In the concurrent case we avoid this requirement by disabling index use
2289  * in multiple steps and waiting out any transactions that might be using
2290  * the index, so we don't need exclusive lock on the parent table. Instead
2291  * we take ShareUpdateExclusiveLock, to ensure that two sessions aren't
2292  * doing CREATE/DROP INDEX CONCURRENTLY on the same index. (We will get
2293  * AccessExclusiveLock on the index below, once we're sure nobody else is
2294  * using it.)
2295  */
2296  heapId = IndexGetRelation(indexId, false);
2297  lockmode = (concurrent || concurrent_lock_mode) ? ShareUpdateExclusiveLock : AccessExclusiveLock;
2298  userHeapRelation = table_open(heapId, lockmode);
2299  userIndexRelation = index_open(indexId, lockmode);
2300 
2301  /*
2302  * We might still have open queries using it in our own session, which the
2303  * above locking won't prevent, so test explicitly.
2304  */
2305  CheckTableNotInUse(userIndexRelation, "DROP INDEX");
2306 
2307  /*
2308  * Drop Index Concurrently is more or less the reverse process of Create
2309  * Index Concurrently.
2310  *
2311  * First we unset indisvalid so queries starting afterwards don't use the
2312  * index to answer queries anymore. We have to keep indisready = true so
2313  * transactions that are still scanning the index can continue to see
2314  * valid index contents. For instance, if they are using READ COMMITTED
2315  * mode, and another transaction makes changes and commits, they need to
2316  * see those new tuples in the index.
2317  *
2318  * After all transactions that could possibly have used the index for
2319  * queries end, we can unset indisready and indislive, then wait till
2320  * nobody could be touching it anymore. (Note: we need indislive because
2321  * this state must be distinct from the initial state during CREATE INDEX
2322  * CONCURRENTLY, which has indislive true while indisready and indisvalid
2323  * are false. That's because in that state, transactions must examine the
2324  * index for HOT-safety decisions, while in this state we don't want them
2325  * to open it at all.)
2326  *
2327  * Since all predicate locks on the index are about to be made invalid, we
2328  * must promote them to predicate locks on the heap. In the
2329  * non-concurrent case we can just do that now. In the concurrent case
2330  * it's a bit trickier. The predicate locks must be moved when there are
2331  * no index scans in progress on the index and no more can subsequently
2332  * start, so that no new predicate locks can be made on the index. Also,
2333  * they must be moved before heap inserts stop maintaining the index, else
2334  * the conflict with the predicate lock on the index gap could be missed
2335  * before the lock on the heap relation is in place to detect a conflict
2336  * based on the heap tuple insert.
2337  */
2338  if (concurrent)
2339  {
2340  /*
2341  * We must commit our transaction in order to make the first pg_index
2342  * state update visible to other sessions. If the DROP machinery has
2343  * already performed any other actions (removal of other objects,
2344  * pg_depend entries, etc), the commit would make those actions
2345  * permanent, which would leave us with inconsistent catalog state if
2346  * we fail partway through the following sequence. Since DROP INDEX
2347  * CONCURRENTLY is restricted to dropping just one index that has no
2348  * dependencies, we should get here before anything's been done ---
2349  * but let's check that to be sure. We can verify that the current
2350  * transaction has not executed any transactional updates by checking
2351  * that no XID has been assigned.
2352  */
2354  ereport(ERROR,
2355  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2356  errmsg("DROP INDEX CONCURRENTLY must be first action in transaction")));
2357 
2358  /*
2359  * Mark index invalid by updating its pg_index entry
2360  */
2362 
2363  /*
2364  * Invalidate the relcache for the table, so that after this commit
2365  * all sessions will refresh any cached plans that might reference the
2366  * index.
2367  */
2368  CacheInvalidateRelcache(userHeapRelation);
2369 
2370  /* save lockrelid and locktag for below, then close but keep locks */
2371  heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
2372  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
2373  indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
2374 
2375  table_close(userHeapRelation, NoLock);
2376  index_close(userIndexRelation, NoLock);
2377 
2378  /*
2379  * We must commit our current transaction so that the indisvalid
2380  * update becomes visible to other transactions; then start another.
2381  * Note that any previously-built data structures are lost in the
2382  * commit. The only data we keep past here are the relation IDs.
2383  *
2384  * Before committing, get a session-level lock on the table, to ensure
2385  * that neither it nor the index can be dropped before we finish. This
2386  * cannot block, even if someone else is waiting for access, because
2387  * we already have the same lock within our transaction.
2388  */
2391 
2395 
2396  /*
2397  * Now we must wait until no running transaction could be using the
2398  * index for a query. Use AccessExclusiveLock here to check for
2399  * running transactions that hold locks of any kind on the table. Note
2400  * we do not need to worry about xacts that open the table for reading
2401  * after this point; they will see the index as invalid when they open
2402  * the relation.
2403  *
2404  * Note: the reason we use actual lock acquisition here, rather than
2405  * just checking the ProcArray and sleeping, is that deadlock is
2406  * possible if one of the transactions in question is blocked trying
2407  * to acquire an exclusive lock on our table. The lock code will
2408  * detect deadlock and error out properly.
2409  *
2410  * Note: we report progress through WaitForLockers() unconditionally
2411  * here, even though it will only be used when we're called by REINDEX
2412  * CONCURRENTLY and not when called by DROP INDEX CONCURRENTLY.
2413  */
2414  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2415 
2416  /* Finish invalidation of index and mark it as dead */
2417  index_concurrently_set_dead(heapId, indexId);
2418 
2419  /*
2420  * Again, commit the transaction to make the pg_index update visible
2421  * to other sessions.
2422  */
2425 
2426  /*
2427  * Wait till every transaction that saw the old index state has
2428  * finished. See above about progress reporting.
2429  */
2430  WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2431 
2432  /*
2433  * Re-open relations to allow us to complete our actions.
2434  *
2435  * At this point, nothing should be accessing the index, but lets
2436  * leave nothing to chance and grab AccessExclusiveLock on the index
2437  * before the physical deletion.
2438  */
2439  userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
2440  userIndexRelation = index_open(indexId, AccessExclusiveLock);
2441  }
2442  else
2443  {
2444  /* Not concurrent, so just transfer predicate locks and we're good */
2445  TransferPredicateLocksToHeapRelation(userIndexRelation);
2446  }
2447 
2448  /*
2449  * Schedule physical removal of the files (if any)
2450  */
2451  if (userIndexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
2452  RelationDropStorage(userIndexRelation);
2453 
2454  /*
2455  * Close and flush the index's relcache entry, to ensure relcache doesn't
2456  * try to rebuild it while we're deleting catalog entries. We keep the
2457  * lock though.
2458  */
2459  index_close(userIndexRelation, NoLock);
2460 
2461  RelationForgetRelation(indexId);
2462 
2463  /*
2464  * fix INDEX relation, and check for expressional index
2465  */
2466  indexRelation = table_open(IndexRelationId, RowExclusiveLock);
2467 
2468  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
2469  if (!HeapTupleIsValid(tuple))
2470  elog(ERROR, "cache lookup failed for index %u", indexId);
2471 
2472  hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs,
2473  RelationGetDescr(indexRelation));
2474 
2475  CatalogTupleDelete(indexRelation, &tuple->t_self);
2476 
2477  ReleaseSysCache(tuple);
2478  table_close(indexRelation, RowExclusiveLock);
2479 
2480  /*
2481  * if it has any expression columns, we might have stored statistics about
2482  * them.
2483  */
2484  if (hasexprs)
2485  RemoveStatistics(indexId, 0);
2486 
2487  /*
2488  * fix ATTRIBUTE relation
2489  */
2490  DeleteAttributeTuples(indexId);
2491 
2492  /*
2493  * fix RELATION relation
2494  */
2495  DeleteRelationTuple(indexId);
2496 
2497  /*
2498  * fix INHERITS relation
2499  */
2500  DeleteInheritsTuple(indexId, InvalidOid, false, NULL);
2501 
2502  /*
2503  * We are presently too lazy to attempt to compute the new correct value
2504  * of relhasindex (the next VACUUM will fix it if necessary). So there is
2505  * no need to update the pg_class tuple for the owning relation. But we
2506  * must send out a shared-cache-inval notice on the owning relation to
2507  * ensure other backends update their relcache lists of indexes. (In the
2508  * concurrent case, this is redundant but harmless.)
2509  */
2510  CacheInvalidateRelcache(userHeapRelation);
2511 
2512  /*
2513  * Close owning rel, but keep lock
2514  */
2515  table_close(userHeapRelation, NoLock);
2516 
2517  /*
2518  * Release the session locks before we go.
2519  */
2520  if (concurrent)
2521  {
2524  }
2525 }
2526 
2527 /* ----------------------------------------------------------------
2528  * index_build support
2529  * ----------------------------------------------------------------
2530  */
2531 
2532 /* ----------------
2533  * BuildIndexInfo
2534  * Construct an IndexInfo record for an open index
2535  *
2536  * IndexInfo stores the information about the index that's needed by
2537  * FormIndexDatum, which is used for both index_build() and later insertion
2538  * of individual index tuples. Normally we build an IndexInfo for an index
2539  * just once per command, and then use it for (potentially) many tuples.
2540  * ----------------
2541  */
2542 IndexInfo *
2544 {
2545  IndexInfo *ii;
2546  Form_pg_index indexStruct = index->rd_index;
2547  int i;
2548  int numAtts;
2549 
2550  /* check the number of keys, and copy attr numbers into the IndexInfo */
2551  numAtts = indexStruct->indnatts;
2552  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2553  elog(ERROR, "invalid indnatts %d for index %u",
2554  numAtts, RelationGetRelid(index));
2555 
2556  /*
2557  * Create the node, fetching any expressions needed for expressional
2558  * indexes and index predicate if any.
2559  */
2560  ii = makeIndexInfo(indexStruct->indnatts,
2561  indexStruct->indnkeyatts,
2562  index->rd_rel->relam,
2565  indexStruct->indisunique,
2566  indexStruct->indisready,
2567  false);
2568 
2569  /* fill in attribute numbers */
2570  for (i = 0; i < numAtts; i++)
2571  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2572 
2573  /* fetch exclusion constraint info if any */
2574  if (indexStruct->indisexclusion)
2575  {
2577  &ii->ii_ExclusionOps,
2578  &ii->ii_ExclusionProcs,
2579  &ii->ii_ExclusionStrats);
2580  }
2581 
2583 
2584  return ii;
2585 }
2586 
2587 /* ----------------
2588  * BuildDummyIndexInfo
2589  * Construct a dummy IndexInfo record for an open index
2590  *
2591  * This differs from the real BuildIndexInfo in that it will never run any
2592  * user-defined code that might exist in index expressions or predicates.
2593  * Instead of the real index expressions, we return null constants that have
2594  * the right types/typmods/collations. Predicates and exclusion clauses are
2595  * just ignored. This is sufficient for the purpose of truncating an index,
2596  * since we will not need to actually evaluate the expressions or predicates;
2597  * the only thing that's likely to be done with the data is construction of
2598  * a tupdesc describing the index's rowtype.
2599  * ----------------
2600  */
2601 IndexInfo *
2603 {
2604  IndexInfo *ii;
2605  Form_pg_index indexStruct = index->rd_index;
2606  int i;
2607  int numAtts;
2608 
2609  /* check the number of keys, and copy attr numbers into the IndexInfo */
2610  numAtts = indexStruct->indnatts;
2611  if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2612  elog(ERROR, "invalid indnatts %d for index %u",
2613  numAtts, RelationGetRelid(index));
2614 
2615  /*
2616  * Create the node, using dummy index expressions, and pretending there is
2617  * no predicate.
2618  */
2619  ii = makeIndexInfo(indexStruct->indnatts,
2620  indexStruct->indnkeyatts,
2621  index->rd_rel->relam,
2623  NIL,
2624  indexStruct->indisunique,
2625  indexStruct->indisready,
2626  false);
2627 
2628  /* fill in attribute numbers */
2629  for (i = 0; i < numAtts; i++)
2630  ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2631 
2632  /* We ignore the exclusion constraint if any */
2633 
2634  return ii;
2635 }
2636 
2637 /*
2638  * CompareIndexInfo
2639  * Return whether the properties of two indexes (in different tables)
2640  * indicate that they have the "same" definitions.
2641  *
2642  * Note: passing collations and opfamilies separately is a kludge. Adding
2643  * them to IndexInfo may result in better coding here and elsewhere.
2644  *
2645  * Use build_attrmap_by_name(index2, index1) to build the attmap.
2646  */
2647 bool
2649  Oid *collations1, Oid *collations2,
2650  Oid *opfamilies1, Oid *opfamilies2,
2651  AttrMap *attmap)
2652 {
2653  int i;
2654 
2655  if (info1->ii_Unique != info2->ii_Unique)
2656  return false;
2657 
2658  /* indexes are only equivalent if they have the same access method */
2659  if (info1->ii_Am != info2->ii_Am)
2660  return false;
2661 
2662  /* and same number of attributes */
2663  if (info1->ii_NumIndexAttrs != info2->ii_NumIndexAttrs)
2664  return false;
2665 
2666  /* and same number of key attributes */
2667  if (info1->ii_NumIndexKeyAttrs != info2->ii_NumIndexKeyAttrs)
2668  return false;
2669 
2670  /*
2671  * and columns match through the attribute map (actual attribute numbers
2672  * might differ!) Note that this implies that index columns that are
2673  * expressions appear in the same positions. We will next compare the
2674  * expressions themselves.
2675  */
2676  for (i = 0; i < info1->ii_NumIndexAttrs; i++)
2677  {
2678  if (attmap->maplen < info2->ii_IndexAttrNumbers[i])
2679  elog(ERROR, "incorrect attribute map");
2680 
2681  /* ignore expressions at this stage */
2682  if ((info1->ii_IndexAttrNumbers[i] != InvalidAttrNumber) &&
2683  (attmap->attnums[info2->ii_IndexAttrNumbers[i] - 1] !=
2684  info1->ii_IndexAttrNumbers[i]))
2685  return false;
2686 
2687  /* collation and opfamily is not valid for including columns */
2688  if (i >= info1->ii_NumIndexKeyAttrs)
2689  continue;
2690 
2691  if (collations1[i] != collations2[i])
2692  return false;
2693  if (opfamilies1[i] != opfamilies2[i])
2694  return false;
2695  }
2696 
2697  /*
2698  * For expression indexes: either both are expression indexes, or neither
2699  * is; if they are, make sure the expressions match.
2700  */
2701  if ((info1->ii_Expressions != NIL) != (info2->ii_Expressions != NIL))
2702  return false;
2703  if (info1->ii_Expressions != NIL)
2704  {
2705  bool found_whole_row;
2706  Node *mapped;
2707 
2708  mapped = map_variable_attnos((Node *) info2->ii_Expressions,
2709  1, 0, attmap,
2710  InvalidOid, &found_whole_row);
2711  if (found_whole_row)
2712  {
2713  /*
2714  * we could throw an error here, but seems out of scope for this
2715  * routine.
2716  */
2717  return false;
2718  }
2719 
2720  if (!equal(info1->ii_Expressions, mapped))
2721  return false;
2722  }
2723 
2724  /* Partial index predicates must be identical, if they exist */
2725  if ((info1->ii_Predicate == NULL) != (info2->ii_Predicate == NULL))
2726  return false;
2727  if (info1->ii_Predicate != NULL)
2728  {
2729  bool found_whole_row;
2730  Node *mapped;
2731 
2732  mapped = map_variable_attnos((Node *) info2->ii_Predicate,
2733  1, 0, attmap,
2734  InvalidOid, &found_whole_row);
2735  if (found_whole_row)
2736  {
2737  /*
2738  * we could throw an error here, but seems out of scope for this
2739  * routine.
2740  */
2741  return false;
2742  }
2743  if (!equal(info1->ii_Predicate, mapped))
2744  return false;
2745  }
2746 
2747  /* No support currently for comparing exclusion indexes. */
2748  if (info1->ii_ExclusionOps != NULL || info2->ii_ExclusionOps != NULL)
2749  return false;
2750 
2751  return true;
2752 }
2753 
2754 /* ----------------
2755  * BuildSpeculativeIndexInfo
2756  * Add extra state to IndexInfo record
2757  *
2758  * For unique indexes, we usually don't want to add info to the IndexInfo for
2759  * checking uniqueness, since the B-Tree AM handles that directly. However,
2760  * in the case of speculative insertion, additional support is required.
2761  *
2762  * Do this processing here rather than in BuildIndexInfo() to not incur the
2763  * overhead in the common non-speculative cases.
2764  * ----------------
2765  */
2766 void
2768 {
2769  int indnkeyatts;
2770  int i;
2771 
2772  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
2773 
2774  /*
2775  * fetch info for checking unique indexes
2776  */
2777  Assert(ii->ii_Unique);
2778 
2779  if (index->rd_rel->relam != BTREE_AM_OID)
2780  elog(ERROR, "unexpected non-btree speculative unique index");
2781 
2782  ii->ii_UniqueOps = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2783  ii->ii_UniqueProcs = (Oid *) palloc(sizeof(Oid) * indnkeyatts);
2784  ii->ii_UniqueStrats = (uint16 *) palloc(sizeof(uint16) * indnkeyatts);
2785 
2786  /*
2787  * We have to look up the operator's strategy number. This provides a
2788  * cross-check that the operator does match the index.
2789  */
2790  /* We need the func OIDs and strategy numbers too */
2791  for (i = 0; i < indnkeyatts; i++)
2792  {
2794  ii->ii_UniqueOps[i] =
2795  get_opfamily_member(index->rd_opfamily[i],
2796  index->rd_opcintype[i],
2797  index->rd_opcintype[i],
2798  ii->ii_UniqueStrats[i]);
2799  if (!OidIsValid(ii->ii_UniqueOps[i]))
2800  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2801  ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2802  index->rd_opcintype[i], index->rd_opfamily[i]);
2803  ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2804  }
2805 }
2806 
2807 /* ----------------
2808  * FormIndexDatum
2809  * Construct values[] and isnull[] arrays for a new index tuple.
2810  *
2811  * indexInfo Info about the index
2812  * slot Heap tuple for which we must prepare an index entry
2813  * estate executor state for evaluating any index expressions
2814  * values Array of index Datums (output area)
2815  * isnull Array of is-null indicators (output area)
2816  *
2817  * When there are no index expressions, estate may be NULL. Otherwise it
2818  * must be supplied, *and* the ecxt_scantuple slot of its per-tuple expr
2819  * context must point to the heap tuple passed in.
2820  *
2821  * Notice we don't actually call index_form_tuple() here; we just prepare
2822  * its input arrays values[] and isnull[]. This is because the index AM
2823  * may wish to alter the data before storage.
2824  * ----------------
2825  */
2826 void
2828  TupleTableSlot *slot,
2829  EState *estate,
2830  Datum *values,
2831  bool *isnull)
2832 {
2833  ListCell *indexpr_item;
2834  int i;
2835 
2836  if (indexInfo->ii_Expressions != NIL &&
2837  indexInfo->ii_ExpressionsState == NIL)
2838  {
2839  /* First time through, set up expression evaluation state */
2840  indexInfo->ii_ExpressionsState =
2841  ExecPrepareExprList(indexInfo->ii_Expressions, estate);
2842  /* Check caller has set up context correctly */
2843  Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
2844  }
2845  indexpr_item = list_head(indexInfo->ii_ExpressionsState);
2846 
2847  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
2848  {
2849  int keycol = indexInfo->ii_IndexAttrNumbers[i];
2850  Datum iDatum;
2851  bool isNull;
2852 
2853  if (keycol < 0)
2854  iDatum = slot_getsysattr(slot, keycol, &isNull);
2855  else if (keycol != 0)
2856  {
2857  /*
2858  * Plain index column; get the value we need directly from the
2859  * heap tuple.
2860  */
2861  iDatum = slot_getattr(slot, keycol, &isNull);
2862  }
2863  else
2864  {
2865  /*
2866  * Index expression --- need to evaluate it.
2867  */
2868  if (indexpr_item == NULL)
2869  elog(ERROR, "wrong number of index expressions");
2870  iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
2871  GetPerTupleExprContext(estate),
2872  &isNull);
2873  indexpr_item = lnext(indexInfo->ii_ExpressionsState, indexpr_item);
2874  }
2875  values[i] = iDatum;
2876  isnull[i] = isNull;
2877  }
2878 
2879  if (indexpr_item != NULL)
2880  elog(ERROR, "wrong number of index expressions");
2881 }
2882 
2883 
2884 /*
2885  * index_update_stats --- update pg_class entry after CREATE INDEX or REINDEX
2886  *
2887  * This routine updates the pg_class row of either an index or its parent
2888  * relation after CREATE INDEX or REINDEX. Its rather bizarre API is designed
2889  * to ensure we can do all the necessary work in just one update.
2890  *
2891  * hasindex: set relhasindex to this value
2892  * reltuples: if >= 0, set reltuples to this value; else no change
2893  *
2894  * If reltuples >= 0, relpages and relallvisible are also updated (using
2895  * RelationGetNumberOfBlocks() and visibilitymap_count()).
2896  *
2897  * NOTE: an important side-effect of this operation is that an SI invalidation
2898  * message is sent out to all backends --- including me --- causing relcache
2899  * entries to be flushed or updated with the new data. This must happen even
2900  * if we find that no change is needed in the pg_class row. When updating
2901  * a heap entry, this ensures that other backends find out about the new
2902  * index. When updating an index, it's important because some index AMs
2903  * expect a relcache flush to occur after REINDEX.
2904  */
2905 static void
2907  bool hasindex,
2908  double reltuples)
2909 {
2910  Oid relid = RelationGetRelid(rel);
2911  Relation pg_class;
2912  HeapTuple tuple;
2913  Form_pg_class rd_rel;
2914  bool dirty;
2915 
2916  /*
2917  * We always update the pg_class row using a non-transactional,
2918  * overwrite-in-place update. There are several reasons for this:
2919  *
2920  * 1. In bootstrap mode, we have no choice --- UPDATE wouldn't work.
2921  *
2922  * 2. We could be reindexing pg_class itself, in which case we can't move
2923  * its pg_class row because CatalogTupleInsert/CatalogTupleUpdate might
2924  * not know about all the indexes yet (see reindex_relation).
2925  *
2926  * 3. Because we execute CREATE INDEX with just share lock on the parent
2927  * rel (to allow concurrent index creations), an ordinary update could
2928  * suffer a tuple-concurrently-updated failure against another CREATE
2929  * INDEX committing at about the same time. We can avoid that by having
2930  * them both do nontransactional updates (we assume they will both be
2931  * trying to change the pg_class row to the same thing, so it doesn't
2932  * matter which goes first).
2933  *
2934  * It is safe to use a non-transactional update even though our
2935  * transaction could still fail before committing. Setting relhasindex
2936  * true is safe even if there are no indexes (VACUUM will eventually fix
2937  * it). And of course the new relpages and reltuples counts are correct
2938  * regardless. However, we don't want to change relpages (or
2939  * relallvisible) if the caller isn't providing an updated reltuples
2940  * count, because that would bollix the reltuples/relpages ratio which is
2941  * what's really important.
2942  */
2943 
2944  pg_class = table_open(RelationRelationId, RowExclusiveLock);
2945 
2946  /*
2947  * Make a copy of the tuple to update. Normally we use the syscache, but
2948  * we can't rely on that during bootstrap or while reindexing pg_class
2949  * itself.
2950  */
2951  if (IsBootstrapProcessingMode() ||
2952  ReindexIsProcessingHeap(RelationRelationId))
2953  {
2954  /* don't assume syscache will work */
2955  TableScanDesc pg_class_scan;
2956  ScanKeyData key[1];
2957 
2958  ScanKeyInit(&key[0],
2959  Anum_pg_class_oid,
2960  BTEqualStrategyNumber, F_OIDEQ,
2961  ObjectIdGetDatum(relid));
2962 
2963  pg_class_scan = table_beginscan_catalog(pg_class, 1, key);
2964  tuple = heap_getnext(pg_class_scan, ForwardScanDirection);
2965  tuple = heap_copytuple(tuple);
2966  table_endscan(pg_class_scan);
2967  }
2968  else
2969  {
2970  /* normal case, use syscache */
2971  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2972  }
2973 
2974  if (!HeapTupleIsValid(tuple))
2975  elog(ERROR, "could not find tuple for relation %u", relid);
2976  rd_rel = (Form_pg_class) GETSTRUCT(tuple);
2977 
2978  /* Should this be a more comprehensive test? */
2979  Assert(rd_rel->relkind != RELKIND_PARTITIONED_INDEX);
2980 
2981  /*
2982  * As a special hack, if we are dealing with an empty table and the
2983  * existing reltuples is -1, we leave that alone. This ensures that
2984  * creating an index as part of CREATE TABLE doesn't cause the table to
2985  * prematurely look like it's been vacuumed.
2986  */
2987  if (reltuples == 0 && rd_rel->reltuples < 0)
2988  reltuples = -1;
2989 
2990  /* Apply required updates, if any, to copied tuple */
2991 
2992  dirty = false;
2993  if (rd_rel->relhasindex != hasindex)
2994  {
2995  rd_rel->relhasindex = hasindex;
2996  dirty = true;
2997  }
2998 
2999  if (reltuples >= 0)
3000  {
3001  BlockNumber relpages = RelationGetNumberOfBlocks(rel);
3002  BlockNumber relallvisible;
3003 
3004  if (rd_rel->relkind != RELKIND_INDEX)
3005  visibilitymap_count(rel, &relallvisible, NULL);
3006  else /* don't bother for indexes */
3007  relallvisible = 0;
3008 
3009  if (rd_rel->relpages != (int32) relpages)
3010  {
3011  rd_rel->relpages = (int32) relpages;
3012  dirty = true;
3013  }
3014  if (rd_rel->reltuples != (float4) reltuples)
3015  {
3016  rd_rel->reltuples = (float4) reltuples;
3017  dirty = true;
3018  }
3019  if (rd_rel->relallvisible != (int32) relallvisible)
3020  {
3021  rd_rel->relallvisible = (int32) relallvisible;
3022  dirty = true;
3023  }
3024  }
3025 
3026  /*
3027  * If anything changed, write out the tuple
3028  */
3029  if (dirty)
3030  {
3031  heap_inplace_update(pg_class, tuple);
3032  /* the above sends a cache inval message */
3033  }
3034  else
3035  {
3036  /* no need to change tuple, but force relcache inval anyway */
3038  }
3039 
3040  heap_freetuple(tuple);
3041 
3042  table_close(pg_class, RowExclusiveLock);
3043 }
3044 
3045 
3046 /*
3047  * index_build - invoke access-method-specific index build procedure
3048  *
3049  * On entry, the index's catalog entries are valid, and its physical disk
3050  * file has been created but is empty. We call the AM-specific build
3051  * procedure to fill in the index contents. We then update the pg_class
3052  * entries of the index and heap relation as needed, using statistics
3053  * returned by ambuild as well as data passed by the caller.
3054  *
3055  * isreindex indicates we are recreating a previously-existing index.
3056  * parallel indicates if parallelism may be useful.
3057  *
3058  * Note: before Postgres 8.2, the passed-in heap and index Relations
3059  * were automatically closed by this routine. This is no longer the case.
3060  * The caller opened 'em, and the caller should close 'em.
3061  */
3062 void
3063 index_build(Relation heapRelation,
3064  Relation indexRelation,
3065  IndexInfo *indexInfo,
3066  bool isreindex,
3067  bool parallel)
3068 {
3069  IndexBuildResult *stats;
3070  Oid save_userid;
3071  int save_sec_context;
3072  int save_nestlevel;
3073 
3074  /*
3075  * sanity checks
3076  */
3077  Assert(RelationIsValid(indexRelation));
3078  Assert(PointerIsValid(indexRelation->rd_indam));
3079  Assert(PointerIsValid(indexRelation->rd_indam->ambuild));
3080  Assert(PointerIsValid(indexRelation->rd_indam->ambuildempty));
3081 
3082  /*
3083  * Determine worker process details for parallel CREATE INDEX. Currently,
3084  * only btree has support for parallel builds.
3085  *
3086  * Note that planner considers parallel safety for us.
3087  */
3088  if (parallel && IsNormalProcessingMode() &&
3089  indexRelation->rd_rel->relam == BTREE_AM_OID)
3090  indexInfo->ii_ParallelWorkers =
3092  RelationGetRelid(indexRelation));
3093 
3094  if (indexInfo->ii_ParallelWorkers == 0)
3095  ereport(DEBUG1,
3096  (errmsg_internal("building index \"%s\" on table \"%s\" serially",
3097  RelationGetRelationName(indexRelation),
3098  RelationGetRelationName(heapRelation))));
3099  else
3100  ereport(DEBUG1,
3101  (errmsg_internal("building index \"%s\" on table \"%s\" with request for %d parallel workers",
3102  RelationGetRelationName(indexRelation),
3103  RelationGetRelationName(heapRelation),
3104  indexInfo->ii_ParallelWorkers)));
3105 
3106  /*
3107  * Switch to the table owner's userid, so that any index functions are run
3108  * as that user. Also lock down security-restricted operations and
3109  * arrange to make GUC variable changes local to this command.
3110  */
3111  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3112  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3113  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3114  save_nestlevel = NewGUCNestLevel();
3115 
3116  /* Set up initial progress report status */
3117  {
3118  const int progress_index[] = {
3125  };
3126  const int64 progress_vals[] = {
3129  0, 0, 0, 0
3130  };
3131 
3132  pgstat_progress_update_multi_param(6, progress_index, progress_vals);
3133  }
3134 
3135  /*
3136  * Call the access method's build procedure
3137  */
3138  stats = indexRelation->rd_indam->ambuild(heapRelation, indexRelation,
3139  indexInfo);
3140  Assert(PointerIsValid(stats));
3141 
3142  /*
3143  * If this is an unlogged index, we may need to write out an init fork for
3144  * it -- but we must first check whether one already exists. If, for
3145  * example, an unlogged relation is truncated in the transaction that
3146  * created it, or truncated twice in a subsequent transaction, the
3147  * relfilenode won't change, and nothing needs to be done here.
3148  */
3149  if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
3150  !smgrexists(indexRelation->rd_smgr, INIT_FORKNUM))
3151  {
3152  RelationOpenSmgr(indexRelation);
3153  smgrcreate(indexRelation->rd_smgr, INIT_FORKNUM, false);
3154  indexRelation->rd_indam->ambuildempty(indexRelation);
3155  }
3156 
3157  /*
3158  * If we found any potentially broken HOT chains, mark the index as not
3159  * being usable until the current transaction is below the event horizon.
3160  * See src/backend/access/heap/README.HOT for discussion. Also set this
3161  * if early pruning/vacuuming is enabled for the heap relation. While it
3162  * might become safe to use the index earlier based on actual cleanup
3163  * activity and other active transactions, the test for that would be much
3164  * more complex and would require some form of blocking, so keep it simple
3165  * and fast by just using the current transaction.
3166  *
3167  * However, when reindexing an existing index, we should do nothing here.
3168  * Any HOT chains that are broken with respect to the index must predate
3169  * the index's original creation, so there is no need to change the
3170  * index's usability horizon. Moreover, we *must not* try to change the
3171  * index's pg_index entry while reindexing pg_index itself, and this
3172  * optimization nicely prevents that. The more complex rules needed for a
3173  * reindex are handled separately after this function returns.
3174  *
3175  * We also need not set indcheckxmin during a concurrent index build,
3176  * because we won't set indisvalid true until all transactions that care
3177  * about the broken HOT chains or early pruning/vacuuming are gone.
3178  *
3179  * Therefore, this code path can only be taken during non-concurrent
3180  * CREATE INDEX. Thus the fact that heap_update will set the pg_index
3181  * tuple's xmin doesn't matter, because that tuple was created in the
3182  * current transaction anyway. That also means we don't need to worry
3183  * about any concurrent readers of the tuple; no other transaction can see
3184  * it yet.
3185  */
3186  if ((indexInfo->ii_BrokenHotChain || EarlyPruningEnabled(heapRelation)) &&
3187  !isreindex &&
3188  !indexInfo->ii_Concurrent)
3189  {
3190  Oid indexId = RelationGetRelid(indexRelation);
3191  Relation pg_index;
3192  HeapTuple indexTuple;
3193  Form_pg_index indexForm;
3194 
3195  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3196 
3197  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3198  ObjectIdGetDatum(indexId));
3199  if (!HeapTupleIsValid(indexTuple))
3200  elog(ERROR, "cache lookup failed for index %u", indexId);
3201  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3202 
3203  /* If it's a new index, indcheckxmin shouldn't be set ... */
3204  Assert(!indexForm->indcheckxmin);
3205 
3206  indexForm->indcheckxmin = true;
3207  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3208 
3209  heap_freetuple(indexTuple);
3210  table_close(pg_index, RowExclusiveLock);
3211  }
3212 
3213  /*
3214  * Update heap and index pg_class rows
3215  */
3216  index_update_stats(heapRelation,
3217  true,
3218  stats->heap_tuples);
3219 
3220  index_update_stats(indexRelation,
3221  false,
3222  stats->index_tuples);
3223 
3224  /* Make the updated catalog row versions visible */
3226 
3227  /*
3228  * If it's for an exclusion constraint, make a second pass over the heap
3229  * to verify that the constraint is satisfied. We must not do this until
3230  * the index is fully valid. (Broken HOT chains shouldn't matter, though;
3231  * see comments for IndexCheckExclusion.)
3232  */
3233  if (indexInfo->ii_ExclusionOps != NULL)
3234  IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
3235 
3236  /* Roll back any GUC changes executed by index functions */
3237  AtEOXact_GUC(false, save_nestlevel);
3238 
3239  /* Restore userid and security context */
3240  SetUserIdAndSecContext(save_userid, save_sec_context);
3241 }
3242 
3243 /*
3244  * IndexCheckExclusion - verify that a new exclusion constraint is satisfied
3245  *
3246  * When creating an exclusion constraint, we first build the index normally
3247  * and then rescan the heap to check for conflicts. We assume that we only
3248  * need to validate tuples that are live according to an up-to-date snapshot,
3249  * and that these were correctly indexed even in the presence of broken HOT
3250  * chains. This should be OK since we are holding at least ShareLock on the
3251  * table, meaning there can be no uncommitted updates from other transactions.
3252  * (Note: that wouldn't necessarily work for system catalogs, since many
3253  * operations release write lock early on the system catalogs.)
3254  */
3255 static void
3257  Relation indexRelation,
3258  IndexInfo *indexInfo)
3259 {
3260  TableScanDesc scan;
3262  bool isnull[INDEX_MAX_KEYS];
3263  ExprState *predicate;
3264  TupleTableSlot *slot;
3265  EState *estate;
3266  ExprContext *econtext;
3267  Snapshot snapshot;
3268 
3269  /*
3270  * If we are reindexing the target index, mark it as no longer being
3271  * reindexed, to forestall an Assert in index_beginscan when we try to use
3272  * the index for probes. This is OK because the index is now fully valid.
3273  */
3276 
3277  /*
3278  * Need an EState for evaluation of index expressions and partial-index
3279  * predicates. Also a slot to hold the current tuple.
3280  */
3281  estate = CreateExecutorState();
3282  econtext = GetPerTupleExprContext(estate);
3283  slot = table_slot_create(heapRelation, NULL);
3284 
3285  /* Arrange for econtext's scan tuple to be the tuple under test */
3286  econtext->ecxt_scantuple = slot;
3287 
3288  /* Set up execution state for predicate, if any. */
3289  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
3290 
3291  /*
3292  * Scan all live tuples in the base relation.
3293  */
3294  snapshot = RegisterSnapshot(GetLatestSnapshot());
3295  scan = table_beginscan_strat(heapRelation, /* relation */
3296  snapshot, /* snapshot */
3297  0, /* number of keys */
3298  NULL, /* scan key */
3299  true, /* buffer access strategy OK */
3300  true); /* syncscan OK */
3301 
3302  while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
3303  {
3305 
3306  /*
3307  * In a partial index, ignore tuples that don't satisfy the predicate.
3308  */
3309  if (predicate != NULL)
3310  {
3311  if (!ExecQual(predicate, econtext))
3312  continue;
3313  }
3314 
3315  /*
3316  * Extract index column values, including computing expressions.
3317  */
3318  FormIndexDatum(indexInfo,
3319  slot,
3320  estate,
3321  values,
3322  isnull);
3323 
3324  /*
3325  * Check that this tuple has no conflicts.
3326  */
3327  check_exclusion_constraint(heapRelation,
3328  indexRelation, indexInfo,
3329  &(slot->tts_tid), values, isnull,
3330  estate, true);
3331 
3333  }
3334 
3335  table_endscan(scan);
3336  UnregisterSnapshot(snapshot);
3337 
3339 
3340  FreeExecutorState(estate);
3341 
3342  /* These may have been pointing to the now-gone estate */
3343  indexInfo->ii_ExpressionsState = NIL;
3344  indexInfo->ii_PredicateState = NULL;
3345 }
3346 
3347 
3348 /*
3349  * validate_index - support code for concurrent index builds
3350  *
3351  * We do a concurrent index build by first inserting the catalog entry for the
3352  * index via index_create(), marking it not indisready and not indisvalid.
3353  * Then we commit our transaction and start a new one, then we wait for all
3354  * transactions that could have been modifying the table to terminate. Now
3355  * we know that any subsequently-started transactions will see the index and
3356  * honor its constraints on HOT updates; so while existing HOT-chains might
3357  * be broken with respect to the index, no currently live tuple will have an
3358  * incompatible HOT update done to it. We now build the index normally via
3359  * index_build(), while holding a weak lock that allows concurrent
3360  * insert/update/delete. Also, we index only tuples that are valid
3361  * as of the start of the scan (see table_index_build_scan), whereas a normal
3362  * build takes care to include recently-dead tuples. This is OK because
3363  * we won't mark the index valid until all transactions that might be able
3364  * to see those tuples are gone. The reason for doing that is to avoid
3365  * bogus unique-index failures due to concurrent UPDATEs (we might see
3366  * different versions of the same row as being valid when we pass over them,
3367  * if we used HeapTupleSatisfiesVacuum). This leaves us with an index that
3368  * does not contain any tuples added to the table while we built the index.
3369  *
3370  * Next, we mark the index "indisready" (but still not "indisvalid") and
3371  * commit the second transaction and start a third. Again we wait for all
3372  * transactions that could have been modifying the table to terminate. Now
3373  * we know that any subsequently-started transactions will see the index and
3374  * insert their new tuples into it. We then take a new reference snapshot
3375  * which is passed to validate_index(). Any tuples that are valid according
3376  * to this snap, but are not in the index, must be added to the index.
3377  * (Any tuples committed live after the snap will be inserted into the
3378  * index by their originating transaction. Any tuples committed dead before
3379  * the snap need not be indexed, because we will wait out all transactions
3380  * that might care about them before we mark the index valid.)
3381  *
3382  * validate_index() works by first gathering all the TIDs currently in the
3383  * index, using a bulkdelete callback that just stores the TIDs and doesn't
3384  * ever say "delete it". (This should be faster than a plain indexscan;
3385  * also, not all index AMs support full-index indexscan.) Then we sort the
3386  * TIDs, and finally scan the table doing a "merge join" against the TID list
3387  * to see which tuples are missing from the index. Thus we will ensure that
3388  * all tuples valid according to the reference snapshot are in the index.
3389  *
3390  * Building a unique index this way is tricky: we might try to insert a
3391  * tuple that is already dead or is in process of being deleted, and we
3392  * mustn't have a uniqueness failure against an updated version of the same
3393  * row. We could try to check the tuple to see if it's already dead and tell
3394  * index_insert() not to do the uniqueness check, but that still leaves us
3395  * with a race condition against an in-progress update. To handle that,
3396  * we expect the index AM to recheck liveness of the to-be-inserted tuple
3397  * before it declares a uniqueness error.
3398  *
3399  * After completing validate_index(), we wait until all transactions that
3400  * were alive at the time of the reference snapshot are gone; this is
3401  * necessary to be sure there are none left with a transaction snapshot
3402  * older than the reference (and hence possibly able to see tuples we did
3403  * not index). Then we mark the index "indisvalid" and commit. Subsequent
3404  * transactions will be able to use it for queries.
3405  *
3406  * Doing two full table scans is a brute-force strategy. We could try to be
3407  * cleverer, eg storing new tuples in a special area of the table (perhaps
3408  * making the table append-only by setting use_fsm). However that would
3409  * add yet more locking issues.
3410  */
3411 void
3412 validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
3413 {
3414  Relation heapRelation,
3415  indexRelation;
3416  IndexInfo *indexInfo;
3417  IndexVacuumInfo ivinfo;
3419  Oid save_userid;
3420  int save_sec_context;
3421  int save_nestlevel;
3422 
3423  {
3424  const int progress_index[] = {
3430  };
3431  const int64 progress_vals[] = {
3433  0, 0, 0, 0
3434  };
3435 
3436  pgstat_progress_update_multi_param(5, progress_index, progress_vals);
3437  }
3438 
3439  /* Open and lock the parent heap relation */
3440  heapRelation = table_open(heapId, ShareUpdateExclusiveLock);
3441  /* And the target index relation */
3442  indexRelation = index_open(indexId, RowExclusiveLock);
3443 
3444  /*
3445  * Fetch info needed for index_insert. (You might think this should be
3446  * passed in from DefineIndex, but its copy is long gone due to having
3447  * been built in a previous transaction.)
3448  */
3449  indexInfo = BuildIndexInfo(indexRelation);
3450 
3451  /* mark build is concurrent just for consistency */
3452  indexInfo->ii_Concurrent = true;
3453 
3454  /*
3455  * Switch to the table owner's userid, so that any index functions are run
3456  * as that user. Also lock down security-restricted operations and
3457  * arrange to make GUC variable changes local to this command.
3458  */
3459  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3460  SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3461  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3462  save_nestlevel = NewGUCNestLevel();
3463 
3464  /*
3465  * Scan the index and gather up all the TIDs into a tuplesort object.
3466  */
3467  ivinfo.index = indexRelation;
3468  ivinfo.analyze_only = false;
3469  ivinfo.report_progress = true;
3470  ivinfo.estimated_count = true;
3471  ivinfo.message_level = DEBUG2;
3472  ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
3473  ivinfo.strategy = NULL;
3474 
3475  /*
3476  * Encode TIDs as int8 values for the sort, rather than directly sorting
3477  * item pointers. This can be significantly faster, primarily because TID
3478  * is a pass-by-reference type on all platforms, whereas int8 is
3479  * pass-by-value on most platforms.
3480  */
3481  state.tuplesort = tuplesort_begin_datum(INT8OID, Int8LessOperator,
3482  InvalidOid, false,
3484  NULL, false);
3485  state.htups = state.itups = state.tups_inserted = 0;
3486 
3487  /* ambulkdelete updates progress metrics */
3488  (void) index_bulk_delete(&ivinfo, NULL,
3489  validate_index_callback, (void *) &state);
3490 
3491  /* Execute the sort */
3492  {
3493  const int progress_index[] = {
3497  };
3498  const int64 progress_vals[] = {
3500  0, 0
3501  };
3502 
3503  pgstat_progress_update_multi_param(3, progress_index, progress_vals);
3504  }
3506 
3507  /*
3508  * Now scan the heap and "merge" it with the index
3509  */
3512  table_index_validate_scan(heapRelation,
3513  indexRelation,
3514  indexInfo,
3515  snapshot,
3516  &state);
3517 
3518  /* Done with tuplesort object */
3519  tuplesort_end(state.tuplesort);
3520 
3521  elog(DEBUG2,
3522  "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
3523  state.htups, state.itups, state.tups_inserted);
3524 
3525  /* Roll back any GUC changes executed by index functions */
3526  AtEOXact_GUC(false, save_nestlevel);
3527 
3528  /* Restore userid and security context */
3529  SetUserIdAndSecContext(save_userid, save_sec_context);
3530 
3531  /* Close rels, but keep locks */
3532  index_close(indexRelation, NoLock);
3533  table_close(heapRelation, NoLock);
3534 }
3535 
3536 /*
3537  * validate_index_callback - bulkdelete callback to collect the index TIDs
3538  */
3539 static bool
3540 validate_index_callback(ItemPointer itemptr, void *opaque)
3541 {
3543  int64 encoded = itemptr_encode(itemptr);
3544 
3545  tuplesort_putdatum(state->tuplesort, Int64GetDatum(encoded), false);
3546  state->itups += 1;
3547  return false; /* never actually delete anything */
3548 }
3549 
3550 /*
3551  * index_set_state_flags - adjust pg_index state flags
3552  *
3553  * This is used during CREATE/DROP INDEX CONCURRENTLY to adjust the pg_index
3554  * flags that denote the index's state.
3555  *
3556  * Note that CatalogTupleUpdate() sends a cache invalidation message for the
3557  * tuple, so other sessions will hear about the update as soon as we commit.
3558  */
3559 void
3561 {
3562  Relation pg_index;
3563  HeapTuple indexTuple;
3564  Form_pg_index indexForm;
3565 
3566  /* Open pg_index and fetch a writable copy of the index's tuple */
3567  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3568 
3569  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3570  ObjectIdGetDatum(indexId));
3571  if (!HeapTupleIsValid(indexTuple))
3572  elog(ERROR, "cache lookup failed for index %u", indexId);
3573  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3574 
3575  /* Perform the requested state change on the copy */
3576  switch (action)
3577  {
3579  /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3580  Assert(indexForm->indislive);
3581  Assert(!indexForm->indisready);
3582  Assert(!indexForm->indisvalid);
3583  indexForm->indisready = true;
3584  break;
3586  /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3587  Assert(indexForm->indislive);
3588  Assert(indexForm->indisready);
3589  Assert(!indexForm->indisvalid);
3590  indexForm->indisvalid = true;
3591  break;
3593 
3594  /*
3595  * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3596  *
3597  * If indisready == true we leave it set so the index still gets
3598  * maintained by active transactions. We only need to ensure that
3599  * indisvalid is false. (We don't assert that either is initially
3600  * true, though, since we want to be able to retry a DROP INDEX
3601  * CONCURRENTLY that failed partway through.)
3602  *
3603  * Note: the CLUSTER logic assumes that indisclustered cannot be
3604  * set on any invalid index, so clear that flag too. Similarly,
3605  * ALTER TABLE assumes that indisreplident cannot be set for
3606  * invalid indexes.
3607  */
3608  indexForm->indisvalid = false;
3609  indexForm->indisclustered = false;
3610  indexForm->indisreplident = false;
3611  break;
3612  case INDEX_DROP_SET_DEAD:
3613 
3614  /*
3615  * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3616  *
3617  * We clear both indisready and indislive, because we not only
3618  * want to stop updates, we want to prevent sessions from touching
3619  * the index at all.
3620  */
3621  Assert(!indexForm->indisvalid);
3622  Assert(!indexForm->indisclustered);
3623  Assert(!indexForm->indisreplident);
3624  indexForm->indisready = false;
3625  indexForm->indislive = false;
3626  break;
3627  }
3628 
3629  /* ... and update it */
3630  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3631 
3632  table_close(pg_index, RowExclusiveLock);
3633 }
3634 
3635 
3636 /*
3637  * IndexGetRelation: given an index's relation OID, get the OID of the
3638  * relation it is an index on. Uses the system cache.
3639  */
3640 Oid
3641 IndexGetRelation(Oid indexId, bool missing_ok)
3642 {
3643  HeapTuple tuple;
3645  Oid result;
3646 
3647  tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
3648  if (!HeapTupleIsValid(tuple))
3649  {
3650  if (missing_ok)
3651  return InvalidOid;
3652  elog(ERROR, "cache lookup failed for index %u", indexId);
3653  }
3654  index = (Form_pg_index) GETSTRUCT(tuple);
3655  Assert(index->indexrelid == indexId);
3656 
3657  result = index->indrelid;
3658  ReleaseSysCache(tuple);
3659  return result;
3660 }
3661 
3662 /*
3663  * reindex_index - This routine is used to recreate a single index
3664  */
3665 void
3666 reindex_index(Oid indexId, bool skip_constraint_checks, char persistence,
3667  ReindexParams *params)
3668 {
3669  Relation iRel,
3670  heapRelation;
3671  Oid heapId;
3672  IndexInfo *indexInfo;
3673  volatile bool skipped_constraint = false;
3674  PGRUsage ru0;
3675  bool progress = ((params->options & REINDEXOPT_REPORT_PROGRESS) != 0);
3676  bool set_tablespace = false;
3677 
3678  pg_rusage_init(&ru0);
3679 
3680  /*
3681  * Open and lock the parent heap relation. ShareLock is sufficient since
3682  * we only need to be sure no schema or data changes are going on.
3683  */
3684  heapId = IndexGetRelation(indexId,
3685  (params->options & REINDEXOPT_MISSING_OK) != 0);
3686  /* if relation is missing, leave */
3687  if (!OidIsValid(heapId))
3688  return;
3689 
3690  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3691  heapRelation = try_table_open(heapId, ShareLock);
3692  else
3693  heapRelation = table_open(heapId, ShareLock);
3694 
3695  /* if relation is gone, leave */
3696  if (!heapRelation)
3697  return;
3698 
3699  if (progress)
3700  {
3701  const int progress_cols[] = {
3704  };
3705  const int64 progress_vals[] = {
3707  indexId
3708  };
3709 
3711  heapId);
3712  pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
3713  }
3714 
3715  /*
3716  * Open the target index relation and get an exclusive lock on it, to
3717  * ensure that no one else is touching this particular index.
3718  */
3719  iRel = index_open(indexId, AccessExclusiveLock);
3720 
3721  if (progress)
3723  iRel->rd_rel->relam);
3724 
3725  /*
3726  * Partitioned indexes should never get processed here, as they have no
3727  * physical storage.
3728  */
3729  if (iRel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
3730  elog(ERROR, "cannot reindex partitioned index \"%s.%s\"",
3732  RelationGetRelationName(iRel));
3733 
3734  /*
3735  * Don't allow reindex on temp tables of other backends ... their local
3736  * buffer manager is not going to cope.
3737  */
3738  if (RELATION_IS_OTHER_TEMP(iRel))
3739  ereport(ERROR,
3740  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3741  errmsg("cannot reindex temporary tables of other sessions")));
3742 
3743  /*
3744  * Don't allow reindex of an invalid index on TOAST table. This is a
3745  * leftover from a failed REINDEX CONCURRENTLY, and if rebuilt it would
3746  * not be possible to drop it anymore.
3747  */
3749  !get_index_isvalid(indexId))
3750  ereport(ERROR,
3751  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3752  errmsg("cannot reindex invalid index on TOAST table")));
3753 
3754  /*
3755  * System relations cannot be moved even if allow_system_table_mods is
3756  * enabled to keep things consistent with the concurrent case where all
3757  * the indexes of a relation are processed in series, including indexes of
3758  * toast relations.
3759  *
3760  * Note that this check is not part of CheckRelationTableSpaceMove() as it
3761  * gets used for ALTER TABLE SET TABLESPACE that could cascade across
3762  * toast relations.
3763  */
3764  if (OidIsValid(params->tablespaceOid) &&
3765  IsSystemRelation(iRel))
3766  ereport(ERROR,
3767  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3768  errmsg("cannot move system relation \"%s\"",
3769  RelationGetRelationName(iRel))));
3770 
3771  /* Check if the tablespace of this index needs to be changed */
3772  if (OidIsValid(params->tablespaceOid) &&
3774  set_tablespace = true;
3775 
3776  /*
3777  * Also check for active uses of the index in the current transaction; we
3778  * don't want to reindex underneath an open indexscan.
3779  */
3780  CheckTableNotInUse(iRel, "REINDEX INDEX");
3781 
3782  /* Set new tablespace, if requested */
3783  if (set_tablespace)
3784  {
3785  /* Update its pg_class row */
3787 
3788  /*
3789  * Schedule unlinking of the old index storage at transaction
3790  * commit.
3791  */
3792  RelationDropStorage(iRel);
3794 
3795  /* Make sure the reltablespace change is visible */
3797  }
3798 
3799  /*
3800  * All predicate locks on the index are about to be made invalid. Promote
3801  * them to relation locks on the heap.
3802  */
3804 
3805  /* Fetch info needed for index_build */
3806  indexInfo = BuildIndexInfo(iRel);
3807 
3808  /* If requested, skip checking uniqueness/exclusion constraints */
3809  if (skip_constraint_checks)
3810  {
3811  if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
3812  skipped_constraint = true;
3813  indexInfo->ii_Unique = false;
3814  indexInfo->ii_ExclusionOps = NULL;
3815  indexInfo->ii_ExclusionProcs = NULL;
3816  indexInfo->ii_ExclusionStrats = NULL;
3817  }
3818 
3819  /* Suppress use of the target index while rebuilding it */
3820  SetReindexProcessing(heapId, indexId);
3821 
3822  /* Create a new physical relation for the index */
3823  RelationSetNewRelfilenode(iRel, persistence);
3824 
3825  /* Initialize the index and rebuild */
3826  /* Note: we do not need to re-establish pkey setting */
3827  index_build(heapRelation, iRel, indexInfo, true, true);
3828 
3829  /* Re-allow use of target index */
3831 
3832  /*
3833  * If the index is marked invalid/not-ready/dead (ie, it's from a failed
3834  * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
3835  * and we didn't skip a uniqueness check, we can now mark it valid. This
3836  * allows REINDEX to be used to clean up in such cases.
3837  *
3838  * We can also reset indcheckxmin, because we have now done a
3839  * non-concurrent index build, *except* in the case where index_build
3840  * found some still-broken HOT chains. If it did, and we don't have to
3841  * change any of the other flags, we just leave indcheckxmin alone (note
3842  * that index_build won't have changed it, because this is a reindex).
3843  * This is okay and desirable because not updating the tuple leaves the
3844  * index's usability horizon (recorded as the tuple's xmin value) the same
3845  * as it was.
3846  *
3847  * But, if the index was invalid/not-ready/dead and there were broken HOT
3848  * chains, we had better force indcheckxmin true, because the normal
3849  * argument that the HOT chains couldn't conflict with the index is
3850  * suspect for an invalid index. (A conflict is definitely possible if
3851  * the index was dead. It probably shouldn't happen otherwise, but let's
3852  * be conservative.) In this case advancing the usability horizon is
3853  * appropriate.
3854  *
3855  * Another reason for avoiding unnecessary updates here is that while
3856  * reindexing pg_index itself, we must not try to update tuples in it.
3857  * pg_index's indexes should always have these flags in their clean state,
3858  * so that won't happen.
3859  *
3860  * If early pruning/vacuuming is enabled for the heap relation, the
3861  * usability horizon must be advanced to the current transaction on every
3862  * build or rebuild. pg_index is OK in this regard because catalog tables
3863  * are not subject to early cleanup.
3864  */
3865  if (!skipped_constraint)
3866  {
3867  Relation pg_index;
3868  HeapTuple indexTuple;
3869  Form_pg_index indexForm;
3870  bool index_bad;
3871  bool early_pruning_enabled = EarlyPruningEnabled(heapRelation);
3872 
3873  pg_index = table_open(IndexRelationId, RowExclusiveLock);
3874 
3875  indexTuple = SearchSysCacheCopy1(INDEXRELID,
3876  ObjectIdGetDatum(indexId));
3877  if (!HeapTupleIsValid(indexTuple))
3878  elog(ERROR, "cache lookup failed for index %u", indexId);
3879  indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3880 
3881  index_bad = (!indexForm->indisvalid ||
3882  !indexForm->indisready ||
3883  !indexForm->indislive);
3884  if (index_bad ||
3885  (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain) ||
3886  early_pruning_enabled)
3887  {
3888  if (!indexInfo->ii_BrokenHotChain && !early_pruning_enabled)
3889  indexForm->indcheckxmin = false;
3890  else if (index_bad || early_pruning_enabled)
3891  indexForm->indcheckxmin = true;
3892  indexForm->indisvalid = true;
3893  indexForm->indisready = true;
3894  indexForm->indislive = true;
3895  CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3896 
3897  /*
3898  * Invalidate the relcache for the table, so that after we commit
3899  * all sessions will refresh the table's index list. This ensures
3900  * that if anyone misses seeing the pg_index row during this
3901  * update, they'll refresh their list before attempting any update
3902  * on the table.
3903  */
3904  CacheInvalidateRelcache(heapRelation);
3905  }
3906 
3907  table_close(pg_index, RowExclusiveLock);
3908  }
3909 
3910  /* Log what we did */
3911  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3912  ereport(INFO,
3913  (errmsg("index \"%s\" was reindexed",
3914  get_rel_name(indexId)),
3915  errdetail_internal("%s",
3916  pg_rusage_show(&ru0))));
3917 
3918  if (progress)
3920 
3921  /* Close rels, but keep locks */
3922  index_close(iRel, NoLock);
3923  table_close(heapRelation, NoLock);
3924 
3925  /* Record the current versions of all depended-on collations. */
3927 }
3928 
3929 /*
3930  * reindex_relation - This routine is used to recreate all indexes
3931  * of a relation (and optionally its toast relation too, if any).
3932  *
3933  * "flags" is a bitmask that can include any combination of these bits:
3934  *
3935  * REINDEX_REL_PROCESS_TOAST: if true, process the toast table too (if any).
3936  *
3937  * REINDEX_REL_SUPPRESS_INDEX_USE: if true, the relation was just completely
3938  * rebuilt by an operation such as VACUUM FULL or CLUSTER, and therefore its
3939  * indexes are inconsistent with it. This makes things tricky if the relation
3940  * is a system catalog that we might consult during the reindexing. To deal
3941  * with that case, we mark all of the indexes as pending rebuild so that they
3942  * won't be trusted until rebuilt. The caller is required to call us *without*
3943  * having made the rebuilt table visible by doing CommandCounterIncrement;
3944  * we'll do CCI after having collected the index list. (This way we can still
3945  * use catalog indexes while collecting the list.)
3946  *
3947  * REINDEX_REL_CHECK_CONSTRAINTS: if true, recheck unique and exclusion
3948  * constraint conditions, else don't. To avoid deadlocks, VACUUM FULL or
3949  * CLUSTER on a system catalog must omit this flag. REINDEX should be used to
3950  * rebuild an index if constraint inconsistency is suspected. For optimal
3951  * performance, other callers should include the flag only after transforming
3952  * the data in a manner that risks a change in constraint validity.
3953  *
3954  * REINDEX_REL_FORCE_INDEXES_UNLOGGED: if true, set the persistence of the
3955  * rebuilt indexes to unlogged.
3956  *
3957  * REINDEX_REL_FORCE_INDEXES_PERMANENT: if true, set the persistence of the
3958  * rebuilt indexes to permanent.
3959  *
3960  * Returns true if any indexes were rebuilt (including toast table's index
3961  * when relevant). Note that a CommandCounterIncrement will occur after each
3962  * index rebuild.
3963  */
3964 bool
3966 {
3967  Relation rel;
3968  Oid toast_relid;
3969  List *indexIds;
3970  char persistence;
3971  bool result;
3972  ListCell *indexId;
3973  int i;
3974 
3975  /*
3976  * Open and lock the relation. ShareLock is sufficient since we only need
3977  * to prevent schema and data changes in it. The lock level used here
3978  * should match ReindexTable().
3979  */
3980  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3981  rel = try_table_open(relid, ShareLock);
3982  else
3983  rel = table_open(relid, ShareLock);
3984 
3985  /* if relation is gone, leave */
3986  if (!rel)
3987  return false;
3988 
3989  /*
3990  * Partitioned tables should never get processed here, as they have no
3991  * physical storage.
3992  */
3993  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3994  elog(ERROR, "cannot reindex partitioned table \"%s.%s\"",
3997 
3998  toast_relid = rel->rd_rel->reltoastrelid;
3999 
4000  /*
4001  * Get the list of index OIDs for this relation. (We trust to the
4002  * relcache to get this with a sequential scan if ignoring system
4003  * indexes.)
4004  */
4005  indexIds = RelationGetIndexList(rel);
4006 
4007  if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
4008  {
4009  /* Suppress use of all the indexes until they are rebuilt */
4010  SetReindexPending(indexIds);
4011 
4012  /*
4013  * Make the new heap contents visible --- now things might be
4014  * inconsistent!
4015  */
4017  }
4018 
4019  /*
4020  * Compute persistence of indexes: same as that of owning rel, unless
4021  * caller specified otherwise.
4022  */
4024  persistence = RELPERSISTENCE_UNLOGGED;
4025  else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
4026  persistence = RELPERSISTENCE_PERMANENT;
4027  else
4028  persistence = rel->rd_rel->relpersistence;
4029 
4030  /* Reindex all the indexes. */
4031  i = 1;
4032  foreach(indexId, indexIds)
4033  {
4034  Oid indexOid = lfirst_oid(indexId);
4035  Oid indexNamespaceId = get_rel_namespace(indexOid);
4036 
4037  /*
4038  * Skip any invalid indexes on a TOAST table. These can only be
4039  * duplicate leftovers from a failed REINDEX CONCURRENTLY, and if
4040  * rebuilt it would not be possible to drop them anymore.
4041  */
4042  if (IsToastNamespace(indexNamespaceId) &&
4043  !get_index_isvalid(indexOid))
4044  {
4045  ereport(WARNING,
4046  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4047  errmsg("cannot reindex invalid index \"%s.%s\" on TOAST table, skipping",
4048  get_namespace_name(indexNamespaceId),
4049  get_rel_name(indexOid))));
4050  continue;
4051  }
4052 
4053  reindex_index(indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
4054  persistence, params);
4055 
4057 
4058  /* Index should no longer be in the pending list */
4059  Assert(!ReindexIsProcessingIndex(indexOid));
4060 
4061  /* Set index rebuild count */
4063  i);
4064  i++;
4065  }
4066 
4067  /*
4068  * Close rel, but continue to hold the lock.
4069  */
4070  table_close(rel, NoLock);
4071 
4072  result = (indexIds != NIL);
4073 
4074  /*
4075  * If the relation has a secondary toast rel, reindex that too while we
4076  * still hold the lock on the main table.
4077  */
4078  if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
4079  {
4080  /*
4081  * Note that this should fail if the toast relation is missing, so
4082  * reset REINDEXOPT_MISSING_OK. Even if a new tablespace is set for
4083  * the parent relation, the indexes on its toast table are not moved.
4084  * This rule is enforced by setting tablespaceOid to InvalidOid.
4085  */
4086  ReindexParams newparams = *params;
4087 
4088  newparams.options &= ~(REINDEXOPT_MISSING_OK);
4089  newparams.tablespaceOid = InvalidOid;
4090  result |= reindex_relation(toast_relid, flags, &newparams);
4091  }
4092 
4093  return result;
4094 }
4095 
4096 
4097 /* ----------------------------------------------------------------
4098  * System index reindexing support
4099  *
4100  * When we are busy reindexing a system index, this code provides support
4101  * for preventing catalog lookups from using that index. We also make use
4102  * of this to catch attempted uses of user indexes during reindexing of
4103  * those indexes. This information is propagated to parallel workers;
4104  * attempting to change it during a parallel operation is not permitted.
4105  * ----------------------------------------------------------------
4106  */
4107 
4111 static int reindexingNestLevel = 0;
4112 
4113 /*
4114  * ReindexIsProcessingHeap
4115  * True if heap specified by OID is currently being reindexed.
4116  */
4117 bool
4119 {
4120  return heapOid == currentlyReindexedHeap;
4121 }
4122 
4123 /*
4124  * ReindexIsCurrentlyProcessingIndex
4125  * True if index specified by OID is currently being reindexed.
4126  */
4127 static bool
4129 {
4130  return indexOid == currentlyReindexedIndex;
4131 }
4132 
4133 /*
4134  * ReindexIsProcessingIndex
4135  * True if index specified by OID is currently being reindexed,
4136  * or should be treated as invalid because it is awaiting reindex.
4137  */
4138 bool
4140 {
4141  return indexOid == currentlyReindexedIndex ||
4142  list_member_oid(pendingReindexedIndexes, indexOid);
4143 }
4144 
4145 /*
4146  * SetReindexProcessing
4147  * Set flag that specified heap/index are being reindexed.
4148  */
4149 static void
4150 SetReindexProcessing(Oid heapOid, Oid indexOid)
4151 {
4152  Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
4153  /* Reindexing is not re-entrant. */
4155  elog(ERROR, "cannot reindex while reindexing");
4156  currentlyReindexedHeap = heapOid;
4157  currentlyReindexedIndex = indexOid;
4158  /* Index is no longer "pending" reindex. */
4159  RemoveReindexPending(indexOid);
4160  /* This may have been set already, but in case it isn't, do so now. */
4162 }
4163 
4164 /*
4165  * ResetReindexProcessing
4166  * Unset reindexing status.
4167  */
4168 static void
4170 {
4173  /* reindexingNestLevel remains set till end of (sub)transaction */
4174 }
4175 
4176 /*
4177  * SetReindexPending
4178  * Mark the given indexes as pending reindex.
4179  *
4180  * NB: we assume that the current memory context stays valid throughout.
4181  */
4182 static void
4184 {
4185  /* Reindexing is not re-entrant. */
4186  if (pendingReindexedIndexes)
4187  elog(ERROR, "cannot reindex while reindexing");
4188  if (IsInParallelMode())
4189  elog(ERROR, "cannot modify reindex state during a parallel operation");
4190  pendingReindexedIndexes = list_copy(indexes);
4192 }
4193 
4194 /*
4195  * RemoveReindexPending
4196  * Remove the given index from the pending list.
4197  */
4198 static void
4200 {
4201  if (IsInParallelMode())
4202  elog(ERROR, "cannot modify reindex state during a parallel operation");
4203  pendingReindexedIndexes = list_delete_oid(pendingReindexedIndexes,
4204  indexOid);
4205 }
4206 
4207 /*
4208  * ResetReindexState
4209  * Clear all reindexing state during (sub)transaction abort.
4210  */
4211 void
4212 ResetReindexState(int nestLevel)
4213 {
4214  /*
4215  * Because reindexing is not re-entrant, we don't need to cope with nested
4216  * reindexing states. We just need to avoid messing up the outer-level
4217  * state in case a subtransaction fails within a REINDEX. So checking the
4218  * current nest level against that of the reindex operation is sufficient.
4219  */
4220  if (reindexingNestLevel >= nestLevel)
4221  {
4224 
4225  /*
4226  * We needn't try to release the contents of pendingReindexedIndexes;
4227  * that list should be in a transaction-lifespan context, so it will
4228  * go away automatically.
4229  */
4230  pendingReindexedIndexes = NIL;
4231 
4232  reindexingNestLevel = 0;
4233  }
4234 }
4235 
4236 /*
4237  * EstimateReindexStateSpace
4238  * Estimate space needed to pass reindex state to parallel workers.
4239  */
4240 Size
4242 {
4243  return offsetof(SerializedReindexState, pendingReindexedIndexes)
4244  + mul_size(sizeof(Oid), list_length(pendingReindexedIndexes));
4245 }
4246 
4247 /*
4248  * SerializeReindexState
4249  * Serialize reindex state for parallel workers.
4250  */
4251 void
4252 SerializeReindexState(Size maxsize, char *start_address)
4253 {
4254  SerializedReindexState *sistate = (SerializedReindexState *) start_address;
4255  int c = 0;
4256  ListCell *lc;
4257 
4260  sistate->numPendingReindexedIndexes = list_length(pendingReindexedIndexes);
4261  foreach(lc, pendingReindexedIndexes)
4262  sistate->pendingReindexedIndexes[c++] = lfirst_oid(lc);
4263 }
4264 
4265 /*
4266  * RestoreReindexState
4267  * Restore reindex state in a parallel worker.
4268  */
4269 void
4270 RestoreReindexState(void *reindexstate)
4271 {
4272  SerializedReindexState *sistate = (SerializedReindexState *) reindexstate;
4273  int c = 0;
4274  MemoryContext oldcontext;
4275 
4278 
4279  Assert(pendingReindexedIndexes == NIL);
4281  for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
4282  pendingReindexedIndexes =
4283  lappend_oid(pendingReindexedIndexes,
4284  sistate->pendingReindexedIndexes[c]);
4285  MemoryContextSwitchTo(oldcontext);
4286 
4287  /* Note the worker has its own transaction nesting level */
4289 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
signed short int16
Definition: c.h:428
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2827
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:957
#define NIL
Definition: pg_list.h:65
Definition: c.h:660
struct IndexAmRoutine * rd_indam
Definition: rel.h:189
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3641
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5219
void ResetReindexState(int nestLevel)
Definition: index.c:4212
uint16 * ii_UniqueStrats
Definition: execnodes.h:170
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:103
List * SystemFuncName(char *name)
LockRelId lockRelId
Definition: rel.h:44
static Oid currentlyReindexedHeap
Definition: index.c:4108
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT
Definition: progress.h:95
bool CompareIndexInfo(IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
Definition: index.c:2648
static void index_update_stats(Relation rel, bool hasindex, double reltuples)
Definition: index.c:2906
bool ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId, const char *conname)
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:2040
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:330
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
Definition: index.c:1414
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define DescriptionObjIndexId
bool DeleteInheritsTuple(Oid inhrelid, Oid inhparent, bool expect_detach_pending, const char *childname)
Definition: pg_inherits.c:499
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition: smgr.c:333
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
Definition: index.c:2256
static void UpdateIndexRelation(Oid indexoid, Oid heapoid, Oid parentIndexId, IndexInfo *indexInfo, Oid *collationOids, Oid *classOids, int16 *coloptions, bool primary, bool isexclusion, bool immediate, bool isvalid, bool isready)
Definition: index.c:534
void tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull)
Definition: tuplesort.c:1805
#define TriggerConstraintIndexId
Definition: pg_trigger.h:85
Oid currentlyReindexedIndex
Definition: index.c:99
List * ii_Predicate
Definition: execnodes.h:163
Tuplesortstate * tuplesort_begin_datum(Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:1247
static bool ReindexIsCurrentlyProcessingIndex(Oid indexOid)
Definition: index.c:4128
PgStat_Counter tuples_returned
Definition: pgstat.h:808
bool IsSystemRelation(Relation relation)
Definition: catalog.c:73
uint32 TransactionId
Definition: c.h:587
#define INDEX_CREATE_IF_NOT_EXISTS
Definition: index.h:65
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:300
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:590
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3105
#define RelationGetDescr(relation)
Definition: rel.h:483
#define INDEX_CREATE_INVALID
Definition: index.h:67
int LOCKMODE
Definition: lockdefs.h:26
PgStat_Counter t_tuples_fetched
Definition: pgstat.h:120
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3560
void namestrcpy(Name name, const char *str)
Definition: name.c:233
uint16 bits16
Definition: c.h:449
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
static void SetReindexProcessing(Oid heapOid, Oid indexOid)
Definition: index.c:4150
static void SetReindexPending(List *indexes)
Definition: index.c:4183
#define PointerGetDatum(X)
Definition: postgres.h:600
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Node * whenClause
Definition: parsenodes.h:2520
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:50
void SerializeReindexState(Size maxsize, char *start_address)
Definition: index.c:4252
char * get_collation_name(Oid colloid)
Definition: lsyscache.c:1060
ExprState * ii_PredicateState
Definition: execnodes.h:164
#define RelationGetForm(relation)
Definition: rel.h:451
void CommitTransactionCommand(void)
Definition: xact.c:2939
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:234
void recordDependencyOnCollations(ObjectAddress *myself, List *collations, bool record_version)
Definition: dependency.c:1647
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2830
List * RelationGetDummyIndexExpressions(Relation relation)
Definition: relcache.c:4844
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *istat, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:691
bool analyze_only
Definition: genam.h:47
int2vector * buildint2vector(const int16 *int2s, int n)
Definition: int.c:114
Oid dbId
Definition: rel.h:39
bool report_progress
Definition: genam.h:48
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
BufferAccessStrategy strategy
Definition: genam.h:52
static void InitializeAttributeOids(Relation indexRelation, int numatts, Oid indexoid)
Definition: index.c:484
Oid binary_upgrade_next_index_pg_class_oid
Definition: index.c:90
int maplen
Definition: attmap.h:37
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Int16GetDatum(X)
Definition: postgres.h:495
Definition: lock.h:166
static List * pendingReindexedIndexes
Definition: index.c:4110
List * list_copy(const List *oldlist)
Definition: list.c:1418
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:350
Definition: nodes.h:539
Oid * ii_ExclusionProcs
Definition: execnodes.h:166
bool get_collation_isdeterministic(Oid colloid)
Definition: lsyscache.c:1079
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int errcode(int sqlerrcode)
Definition: elog.c:698
void * stringToNode(const char *str)
Definition: read.c:89
Relation index
Definition: genam.h:46
#define MemSet(start, val, len)
Definition: c.h:1008
#define INFO
Definition: elog.h:33
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
#define PROGRESS_CREATEIDX_TUPLES_TOTAL
Definition: progress.h:84
uint32 BlockNumber
Definition: block.h:31
void RelationForgetRelation(Oid rid)
Definition: relcache.c:2731
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2621
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2543
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:247
PgStat_Counter numscans
Definition: pgstat.h:806
#define INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS
Definition: index.h:93
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
Definition: index.c:205
PgStat_TableCounts t_counts
Definition: pgstat.h:177
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2566
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1622
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
#define REINDEX_REL_SUPPRESS_INDEX_USE
Definition: index.h:159
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:1032
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2862
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:200
Form_pg_class rd_rel
Definition: rel.h:110
void CopyStatistics(Oid fromrelid, Oid torelid)
Definition: heap.c:3172
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:395
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:69
Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER]
Definition: index.c:101
Oid amkeytype
Definition: amapi.h:250
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
Definition: index.c:698
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
Definition: objectaccess.h:178
PgStat_Counter t_tuples_returned
Definition: pgstat.h:119
Oid * ii_UniqueOps
Definition: execnodes.h:168
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
bool IsBinaryUpgrade
Definition: globals.c:113
double itups
Definition: index.h:51
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:907
void pgstat_progress_end_command(void)
signed int int32
Definition: c.h:429
Definition: attmap.h:34
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
static void ResetReindexProcessing(void)
Definition: index.c:4169
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4898
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
Definition: type.h:89
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:91
char * get_collation_version_for_oid(Oid oid, bool missing_ok)
Definition: pg_locale.c:1707
static void AppendAttributeTuples(Relation indexRelation, Datum *attopts)
Definition: index.c:502
void RelationSetNewRelfilenode(Relation relation, char persistence)
Definition: relcache.c:3576
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3253
void InsertPgClassTuple(Relation pg_class_desc, Relation new_rel_desc, Oid new_rel_oid, Datum relacl, Datum reloptions)
Definition: heap.c:922
#define RelationOpenSmgr(relation)
Definition: rel.h:514
RangeVar * constrrel
Definition: parsenodes.h:2526
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:532
List * ii_ExpressionsState
Definition: execnodes.h:162
Form_pg_index rd_index
Definition: rel.h:175
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
unsigned short uint16
Definition: c.h:440
void pfree(void *pointer)
Definition: mcxt.c:1169
bool IsInParallelMode(void)
Definition: xact.c:1012
Oid * rd_indcollation
Definition: rel.h:200
#define EarlyPruningEnabled(rel)
Definition: snapmgr.h:44
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:383
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
Definition: rel.h:36
ambuild_function ambuild
Definition: amapi.h:259
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:370
IndexAmRoutine * GetIndexAmRoutineByAmId(Oid amoid, bool noerror)
Definition: amapi.c:56
#define RelationIsValid(relation)
Definition: rel.h:430
#define REINDEXOPT_VERBOSE
Definition: index.h:41
bool ReindexIsProcessingHeap(Oid heapOid)
Definition: index.c:4118
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
void recordDependencyOnSingleRelExpr(const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool reverse_self, bool record_version)
Definition: dependency.c:1734
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1856
#define DEBUG2
Definition: elog.h:24
Tuplesortstate * tuplesort
Definition: index.h:49
#define AttrNumberGetAttrOffset(attNum)
Definition: attnum.h:51
Oid tablespaceOid
Definition: index.h:36
PgStat_StatTabEntry * pgstat_fetch_stat_tabentry(Oid relid)
Definition: pgstat.c:2728
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:183
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
char * c
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:113
#define IsNormalProcessingMode()
Definition: miscadmin.h:396
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
#define AttributeRelidNumIndexId
Definition: pg_attribute.h:208
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition: tablecmds.c:3294
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4785
Oid * ii_UniqueProcs
Definition: execnodes.h:169
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:668
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:583
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6235
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:80
int errdetail(const char *fmt,...)
Definition: elog.c:1042
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
IndexStateFlagsAction
Definition: index.h:24
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:491
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:720
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
List * list_delete_oid(List *list, Oid datum)
Definition: list.c:849
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
PgStat_Counter tuples_fetched
Definition: pgstat.h:809
bool ii_BrokenHotChain
Definition: execnodes.h:175
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:798
Oid * rd_opfamily
Definition: rel.h:190
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:969
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
static int64 itemptr_encode(ItemPointer itemptr)
Definition: index.h:188
static TupleDesc ConstructTupleDescriptor(Relation heapRelation, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid *collationObjectId, Oid *classObjectId)
Definition: index.c:271
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:476
void InsertPgAttributeTuples(Relation pg_attribute_rel, TupleDesc tupdesc, Oid new_rel_oid, Datum *attoptions, CatalogIndexState indstate)
Definition: heap.c:740
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:425
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:743
void visitDependenciesOf(const ObjectAddress *object, VisitDependenciesOfCB callback, void *userdata)
Definition: dependency.c:443
List * transitionRels
Definition: parsenodes.h:2522
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3943
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:455
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1700
static void IndexCheckExclusion(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo)
Definition: index.c:3256
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:195
Size EstimateReindexStateSpace(void)
Definition: index.c:4241
void index_register(Oid heap, Oid ind, IndexInfo *indexInfo)
Definition: bootstrap.c:1089
bool ii_ReadyForInserts
Definition: execnodes.h:173
PgStat_Counter t_blocks_hit
Definition: pgstat.h:133
MemoryContext TopMemoryContext
Definition: mcxt.c:48
int numPendingReindexedIndexes
Definition: index.c:100
static bool do_collation_version_check(const ObjectAddress *otherObject, const char *version, char **new_version, void *data)
Definition: index.c:1291
bytea * index_opclass_options(Relation indrel, AttrNumber attnum, Datum attoptions, bool validate)
Definition: indexam.c:939
EState * CreateExecutorState(void)
Definition: execUtils.c:90
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition: predicate.c:3146
bool get_rel_relispartition(Oid relid)
Definition: lsyscache.c:1998
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:766
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
List * lappend(List *list, void *datum)
Definition: list.c:336
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3666
static Oid currentlyReindexedIndex
Definition: index.c:4109
List * list_difference_oid(const List *list1, const List *list2)
Definition: list.c:1167
#define PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE
Definition: progress.h:104
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5427
#define WARNING
Definition: elog.h:40
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3412
#define RelationIsMapped(relation)
Definition: rel.h:506
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
float float4
Definition: c.h:564
int progress
Definition: pgbench.c:270
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
void RelationAssumeNewRelfilenode(Relation relation)
Definition: relcache.c:3727
Definition: c.h:649
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
#define TextDatumGetCString(d)
Definition: builtins.h:83
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
int get_attstattarget(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:883
void RelationDropStorage(Relation rel)
Definition: storage.c:195
uintptr_t Datum
Definition: postgres.h:411
void CommandCounterIncrement(void)
Definition: xact.c:1021
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Expr * make_ands_explicit(List *andclauses)
Definition: makefuncs.c:708
int ii_NumIndexAttrs
Definition: execnodes.h:158
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
static bool relationHasPrimaryKey(Relation rel)
Definition: index.c:151
#define PROGRESS_CREATEIDX_COMMAND_REINDEX
Definition: progress.h:110
PgStat_Counter blocks_hit
Definition: pgstat.h:823
#define InvalidMultiXactId
Definition: multixact.h:24
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:213
#define InvokeObjectPostCreateHookArg(classId, objectId, subId, is_internal)
Definition: objectaccess.h:153
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:313
PgStat_Counter t_numscans
Definition: pgstat.h:117
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:61
#define BoolGetDatum(X)
Definition: postgres.h:446
static void RemoveReindexPending(Oid indexOid)
Definition: index.c:4199
long changeDependenciesOf(Oid classId, Oid oldObjectId, Oid newObjectId)
Definition: pg_depend.c:529
#define InvalidOid
Definition: postgres_ext.h:36
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
FormData_pg_attribute
Definition: pg_attribute.h:187
#define INDEX_CREATE_CONCURRENT
Definition: index.h:64
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
int16 attnum
Definition: pg_attribute.h:83
#define ereport(elevel,...)
Definition: elog.h:157
void DeleteRelationTuple(Oid relid)
Definition: heap.c:1555
int maintenance_work_mem
Definition: globals.c:126
#define NOTICE
Definition: elog.h:37
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
int message_level
Definition: genam.h:50
TransactionId MultiXactId
Definition: c.h:597
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
double num_heap_tuples
Definition: genam.h:51
bool ii_Unique
Definition: execnodes.h:172
#define makeNode(_type_)
Definition: nodes.h:587
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void index_check_collation_versions(Oid relid)
Definition: index.c:1344
FormData_pg_constraint * Form_pg_constraint
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isreindex, bool parallel)
Definition: index.c:3063
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define REINDEX_REL_FORCE_INDEXES_UNLOGGED
Definition: index.h:161
List * ii_Expressions
Definition: execnodes.h:161
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:804
oidvector * buildoidvector(const Oid *oids, int n)
Definition: oid.c:167
#define lfirst(lc)
Definition: pg_list.h:169
void pgstat_progress_update_param(int index, int64 val)
Definition: regguts.h:317
double tups_inserted
Definition: index.h:51
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:600
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN
Definition: progress.h:96
void StartTransactionCommand(void)
Definition: xact.c:2838
bits32 options
Definition: index.h:35
AttrNumber * attnums
Definition: attmap.h:36
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition: indexing.c:43
Relation heap_create(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid relfilenode, Oid accessmtd, TupleDesc tupDesc, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, bool allow_system_table_mods, TransactionId *relfrozenxid, MultiXactId *relminmxid)
Definition: heap.c:295
#define linitial_oid(l)
Definition: pg_list.h:176
#define INDEX_MAX_KEYS
int ii_ParallelWorkers
Definition: execnodes.h:176
size_t Size
Definition: c.h:540
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
struct PgStat_TableStatus * pgstat_info
Definition: rel.h:237
int plan_create_index_workers(Oid tableOid, Oid indexOid)
Definition: planner.c:5851
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3532
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static int list_length(const List *l)
Definition: pg_list.h:149
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:160
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1138
Oid GetNewRelFileNode(Oid reltablespace, Relation pg_class, char relpersistence)
Definition: catalog.c:427
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
List * get_index_ref_constraints(Oid indexId)
Definition: pg_depend.c:1025
void DeleteAttributeTuples(Oid relid)
Definition: heap.c:1584
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:657
static int reindexingNestLevel
Definition: index.c:4111
#define INDEX_CONSTR_CREATE_UPDATE_INDEX
Definition: index.h:92
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4551
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
bool ii_Concurrent
Definition: execnodes.h:174
static bool do_collation_version_update(const ObjectAddress *otherObject, const char *version, char **new_version, void *data)
Definition: index.c:1369
#define InvalidAttrNumber
Definition: attnum.h:23
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define DatumGetPointer(X)
Definition: postgres.h:593
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
double htups
Definition: index.h:51
void RemoveStatistics(Oid relid, AttrNumber attnum)
Definition: heap.c:3217
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2049
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3965
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
static Datum values[MAXATTR]
Definition: bootstrap.c:166
void RelationInitIndexAccessInfo(Relation relation)
Definition: relcache.c:1358
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:394
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:63
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2779
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define InvalidCompressionMethod
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
#define INDEX_CREATE_PARTITIONED
Definition: index.h:66
#define Int32GetDatum(X)
Definition: postgres.h:523
int NewGUCNestLevel(void)
Definition: guc.c:6221
List * GetTypeCollations(Oid typeoid)
Definition: pg_type.c:527
Oid * ii_ExclusionOps
Definition: execnodes.h:165
void RestoreReindexState(void *reindexstate)
Definition: index.c:4270
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:6048
IndexInfo * BuildDummyIndexInfo(Relation index)
Definition: index.c:2602
static void table_index_validate_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, Snapshot snapshot, struct ValidateIndexState *state)
Definition: tableam.h:1809
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
ambuildempty_function ambuildempty
Definition: amapi.h:260
MemoryContext rd_indexcxt
Definition: rel.h:187
#define ShareLock
Definition: lockdefs.h:41
int i
void LockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:217
RangeVar * relation
Definition: parsenodes.h:2511
Oid currentlyReindexedHeap
Definition: index.c:98
#define PROGRESS_CLUSTER_INDEX_REBUILD_COUNT
Definition: progress.h:62
#define NameStr(name)
Definition: c.h:681
ObjectAddress CreateTrigger(CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition)
Definition: trigger.c:150
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define CStringGetTextDatum(s)
Definition: builtins.h:82
char * nodeToString(const void *obj)
Definition: outfuncs.c:4526
#define REINDEX_REL_FORCE_INDEXES_PERMANENT
Definition: index.h:162
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition: indexing.c:61
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:158
void BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii)
Definition: index.c:2767
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
#define PROGRESS_CREATEIDX_SUBPHASE
Definition: progress.h:83
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1314
void check_exclusion_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex)
Definition: execIndexing.c:887
Oid * rd_opcintype
Definition: rel.h:191
void index_update_collation_versions(Oid relid, Oid coll)
Definition: index.c:1394
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:402
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
uint16 * ii_ExclusionStrats
Definition: execnodes.h:167
void CheckAttributeType(const char *attname, Oid atttypid, Oid attcollation, List *containing_rowtypes, int flags)
Definition: heap.c:591
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1464
#define INDEX_CREATE_ADD_CONSTRAINT
Definition: index.h:62
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1975
bool ReindexIsProcessingIndex(Oid indexOid)
Definition: index.c:4139
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1574
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
static bool validate_index_callback(ItemPointer itemptr, void *opaque)
Definition: index.c:3540
PgStat_Counter blocks_fetched
Definition: pgstat.h:822
Definition: pg_list.h:50
long changeDependenciesOn(Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:585
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define PointerIsValid(pointer)
Definition: c.h:698
ItemPointerData tts_tid
Definition: tuptable.h:130
List * get_partition_ancestors(Oid relid)
Definition: partition.c:133
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:457
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:90
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
struct do_collation_version_check_context do_collation_version_check_context
Datum * ii_OpclassOptions
Definition: execnodes.h:171
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define offsetof(type, field)
Definition: c.h:727
void SetRelationTableSpace(Relation rel, Oid newTableSpaceId, Oid newRelFileNode)
Definition: tablecmds.c:3351
PgStat_Counter t_blocks_fetched
Definition: pgstat.h:132
#define lfirst_oid(lc)
Definition: pg_list.h:171
double index_tuples
Definition: genam.h:33
#define INDEX_CONSTR_CREATE_MARK_AS_PRIMARY
Definition: index.h:89
double heap_tuples
Definition: genam.h:32
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81
Oid relId
Definition: rel.h:38
bool estimated_count
Definition: genam.h:49
ObjectAddress index_constraint_create(Relation heapRelation, Oid indexRelationId, Oid parentConstraintId, IndexInfo *indexInfo, const char *constraintName, char constraintType, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
Definition: index.c:2036
Oid ii_Am
Definition: execnodes.h:177
#define RelationGetNamespace(relation)
Definition: rel.h:498