PostgreSQL Source Code git master
indexcmds.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/gist.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_database.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_type.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/progress.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_coerce.h"
#include "parser/parse_oper.h"
#include "parser/parse_utilcmd.h"
#include "partitioning/partdesc.h"
#include "pgstat.h"
#include "rewrite/rewriteManip.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/injection_point.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/pg_rusage.h"
#include "utils/regproc.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for indexcmds.c:

Go to the source code of this file.

Data Structures

struct  ReindexIndexCallbackState
 
struct  ReindexErrorInfo
 

Typedefs

typedef struct ReindexErrorInfo ReindexErrorInfo
 

Functions

static bool CompareOpclassOptions (const Datum *opts1, const Datum *opts2, int natts)
 
static void CheckPredicate (Expr *predicate)
 
static void ComputeIndexAttrs (ParseState *pstate, IndexInfo *indexInfo, Oid *typeOids, Oid *collationOids, Oid *opclassOids, Datum *opclassOptions, int16 *colOptions, const List *attList, const List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint, bool iswithoutoverlaps, Oid ddl_userid, int ddl_sec_context, int *ddl_save_nestlevel)
 
static char * ChooseIndexName (const char *tabname, Oid namespaceId, const List *colnames, const List *exclusionOpNames, bool primary, bool isconstraint)
 
static char * ChooseIndexNameAddition (const List *colnames)
 
static ListChooseIndexColumnNames (const List *indexElems)
 
static void ReindexIndex (const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
 
static void RangeVarCallbackForReindexIndex (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
static Oid ReindexTable (const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleTables (const ReindexStmt *stmt, const ReindexParams *params)
 
static void reindex_error_callback (void *arg)
 
static void ReindexPartitions (const ReindexStmt *stmt, Oid relid, const ReindexParams *params, bool isTopLevel)
 
static void ReindexMultipleInternal (const ReindexStmt *stmt, const List *relids, const ReindexParams *params)
 
static bool ReindexRelationConcurrently (const ReindexStmt *stmt, Oid relationOid, const ReindexParams *params)
 
static void update_relispartition (Oid relationId, bool newval)
 
static void set_indexsafe_procflags (void)
 
bool CheckIndexCompatible (Oid oldId, const char *accessMethodName, const List *attributeList, const List *exclusionOpNames, bool isWithoutOverlaps)
 
void WaitForOlderSnapshots (TransactionId limitXmin, bool progress)
 
ObjectAddress DefineIndex (ParseState *pstate, Oid tableId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, int total_parts, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
 
Oid ResolveOpClass (const List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
 
Oid GetDefaultOpClass (Oid type_id, Oid am_id)
 
void GetOperatorFromCompareType (Oid opclass, Oid rhstype, CompareType cmptype, Oid *opid, StrategyNumber *strat)
 
char * makeObjectName (const char *name1, const char *name2, const char *label)
 
char * ChooseRelationName (const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
 
void ExecReindex (ParseState *pstate, const ReindexStmt *stmt, bool isTopLevel)
 
void IndexSetParentIndex (Relation partitionIdx, Oid parentOid)
 

Typedef Documentation

◆ ReindexErrorInfo

Function Documentation

◆ CheckIndexCompatible()

bool CheckIndexCompatible ( Oid  oldId,
const char *  accessMethodName,
const List attributeList,
const List exclusionOpNames,
bool  isWithoutOverlaps 
)

Definition at line 178 of file indexcmds.c.

183{
184 bool isconstraint;
185 Oid *typeIds;
186 Oid *collationIds;
187 Oid *opclassIds;
188 Datum *opclassOptions;
189 Oid accessMethodId;
190 Oid relationId;
191 HeapTuple tuple;
192 Form_pg_index indexForm;
193 Form_pg_am accessMethodForm;
194 const IndexAmRoutine *amRoutine;
195 bool amcanorder;
196 bool amsummarizing;
197 int16 *coloptions;
198 IndexInfo *indexInfo;
199 int numberOfAttributes;
200 int old_natts;
201 bool ret = true;
202 oidvector *old_indclass;
203 oidvector *old_indcollation;
204 Relation irel;
205 int i;
206 Datum d;
207
208 /* Caller should already have the relation locked in some way. */
209 relationId = IndexGetRelation(oldId, false);
210
211 /*
212 * We can pretend isconstraint = false unconditionally. It only serves to
213 * decide the text of an error message that should never happen for us.
214 */
215 isconstraint = false;
216
217 numberOfAttributes = list_length(attributeList);
218 Assert(numberOfAttributes > 0);
219 Assert(numberOfAttributes <= INDEX_MAX_KEYS);
220
221 /* look up the access method */
222 tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
223 if (!HeapTupleIsValid(tuple))
225 (errcode(ERRCODE_UNDEFINED_OBJECT),
226 errmsg("access method \"%s\" does not exist",
227 accessMethodName)));
228 accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
229 accessMethodId = accessMethodForm->oid;
230 amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
231 ReleaseSysCache(tuple);
232
233 amcanorder = amRoutine->amcanorder;
234 amsummarizing = amRoutine->amsummarizing;
235
236 /*
237 * Compute the operator classes, collations, and exclusion operators for
238 * the new index, so we can test whether it's compatible with the existing
239 * one. Note that ComputeIndexAttrs might fail here, but that's OK:
240 * DefineIndex would have failed later. Our attributeList contains only
241 * key attributes, thus we're filling ii_NumIndexAttrs and
242 * ii_NumIndexKeyAttrs with same value.
243 */
244 indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
245 accessMethodId, NIL, NIL, false, false,
246 false, false, amsummarizing, isWithoutOverlaps);
247 typeIds = palloc_array(Oid, numberOfAttributes);
248 collationIds = palloc_array(Oid, numberOfAttributes);
249 opclassIds = palloc_array(Oid, numberOfAttributes);
250 opclassOptions = palloc_array(Datum, numberOfAttributes);
251 coloptions = palloc_array(int16, numberOfAttributes);
252 ComputeIndexAttrs(NULL, indexInfo,
253 typeIds, collationIds, opclassIds, opclassOptions,
254 coloptions, attributeList,
255 exclusionOpNames, relationId,
256 accessMethodName, accessMethodId,
257 amcanorder, isconstraint, isWithoutOverlaps, InvalidOid,
258 0, NULL);
259
260 /* Get the soon-obsolete pg_index tuple. */
261 tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldId));
262 if (!HeapTupleIsValid(tuple))
263 elog(ERROR, "cache lookup failed for index %u", oldId);
264 indexForm = (Form_pg_index) GETSTRUCT(tuple);
265
266 /*
267 * We don't assess expressions or predicates; assume incompatibility.
268 * Also, if the index is invalid for any reason, treat it as incompatible.
269 */
270 if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) &&
271 heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) &&
272 indexForm->indisvalid))
273 {
274 ReleaseSysCache(tuple);
275 return false;
276 }
277
278 /* Any change in operator class or collation breaks compatibility. */
279 old_natts = indexForm->indnkeyatts;
280 Assert(old_natts == numberOfAttributes);
281
282 d = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indcollation);
283 old_indcollation = (oidvector *) DatumGetPointer(d);
284
285 d = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indclass);
286 old_indclass = (oidvector *) DatumGetPointer(d);
287
288 ret = (memcmp(old_indclass->values, opclassIds, old_natts * sizeof(Oid)) == 0 &&
289 memcmp(old_indcollation->values, collationIds, old_natts * sizeof(Oid)) == 0);
290
291 ReleaseSysCache(tuple);
292
293 if (!ret)
294 return false;
295
296 /* For polymorphic opcintype, column type changes break compatibility. */
297 irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
298 for (i = 0; i < old_natts; i++)
299 {
300 if (IsPolymorphicType(get_opclass_input_type(opclassIds[i])) &&
301 TupleDescAttr(irel->rd_att, i)->atttypid != typeIds[i])
302 {
303 ret = false;
304 break;
305 }
306 }
307
308 /* Any change in opclass options break compatibility. */
309 if (ret)
310 {
311 Datum *oldOpclassOptions = palloc_array(Datum, old_natts);
312
313 for (i = 0; i < old_natts; i++)
314 oldOpclassOptions[i] = get_attoptions(oldId, i + 1);
315
316 ret = CompareOpclassOptions(oldOpclassOptions, opclassOptions, old_natts);
317
318 pfree(oldOpclassOptions);
319 }
320
321 /* Any change in exclusion operator selections breaks compatibility. */
322 if (ret && indexInfo->ii_ExclusionOps != NULL)
323 {
324 Oid *old_operators,
325 *old_procs;
326 uint16 *old_strats;
327
328 RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
329 ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
330 old_natts * sizeof(Oid)) == 0;
331
332 /* Require an exact input type match for polymorphic operators. */
333 if (ret)
334 {
335 for (i = 0; i < old_natts && ret; i++)
336 {
337 Oid left,
338 right;
339
340 op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
341 if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
342 TupleDescAttr(irel->rd_att, i)->atttypid != typeIds[i])
343 {
344 ret = false;
345 break;
346 }
347 }
348 }
349 }
350
351 index_close(irel, NoLock);
352 return ret;
353}
const IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
int16_t int16
Definition: c.h:547
uint16_t uint16
Definition: c.h:551
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:150
#define palloc_array(type, count)
Definition: fe_memutils.h:76
Assert(PointerIsAligned(start, uint64))
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:456
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3581
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
static bool CompareOpclassOptions(const Datum *opts1, const Datum *opts2, int natts)
Definition: indexcmds.c:362
static void ComputeIndexAttrs(ParseState *pstate, IndexInfo *indexInfo, Oid *typeOids, Oid *collationOids, Oid *opclassOids, Datum *opclassOptions, int16 *colOptions, const List *attList, const List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint, bool iswithoutoverlaps, Oid ddl_userid, int ddl_sec_context, int *ddl_save_nestlevel)
Definition: indexcmds.c:1875
int i
Definition: isn.c:77
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1314
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:1046
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1508
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool nulls_not_distinct, bool isready, bool concurrent, bool summarizing, bool withoutoverlaps)
Definition: makefuncs.c:834
void pfree(void *pointer)
Definition: mcxt.c:1616
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
#define INDEX_MAX_KEYS
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
uint64_t Datum
Definition: postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5648
bool amsummarizing
Definition: amapi.h:282
bool amcanorder
Definition: amapi.h:246
Oid * ii_ExclusionOps
Definition: execnodes.h:188
TupleDesc rd_att
Definition: rel.h:112
Definition: c.h:745
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:752
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:625
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

References AccessShareLock, IndexAmRoutine::amcanorder, IndexAmRoutine::amsummarizing, Assert(), CompareOpclassOptions(), ComputeIndexAttrs(), DatumGetPointer(), elog, ereport, errcode(), errmsg(), ERROR, get_attoptions(), get_opclass_input_type(), GetIndexAmRoutine(), GETSTRUCT(), heap_attisnull(), HeapTupleIsValid, i, IndexInfo::ii_ExclusionOps, index_close(), INDEX_MAX_KEYS, index_open(), IndexGetRelation(), InvalidOid, list_length(), makeIndexInfo(), NIL, NoLock, ObjectIdGetDatum(), op_input_types(), palloc_array, pfree(), PointerGetDatum(), RelationData::rd_att, RelationGetExclusionInfo(), ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttrNotNull(), TupleDescAttr(), and oidvector::values.

Referenced by TryReuseIndex().

◆ CheckPredicate()

static void CheckPredicate ( Expr predicate)
static

Definition at line 1848 of file indexcmds.c.

1849{
1850 /*
1851 * transformExpr() should have already rejected subqueries, aggregates,
1852 * and window functions, based on the EXPR_KIND_ for a predicate.
1853 */
1854
1855 /*
1856 * A predicate using mutable functions is probably wrong, for the same
1857 * reasons that we don't allow an index expression to use one.
1858 */
1860 ereport(ERROR,
1861 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1862 errmsg("functions in index predicate must be marked IMMUTABLE")));
1863}
bool contain_mutable_functions_after_planning(Expr *expr)
Definition: clauses.c:502

References contain_mutable_functions_after_planning(), ereport, errcode(), errmsg(), and ERROR.

Referenced by DefineIndex().

◆ ChooseIndexColumnNames()

static List * ChooseIndexColumnNames ( const List indexElems)
static

Definition at line 2785 of file indexcmds.c.

2786{
2787 List *result = NIL;
2788 ListCell *lc;
2789
2790 foreach(lc, indexElems)
2791 {
2792 IndexElem *ielem = (IndexElem *) lfirst(lc);
2793 const char *origname;
2794 const char *curname;
2795 int i;
2796 char buf[NAMEDATALEN];
2797
2798 /* Get the preliminary name from the IndexElem */
2799 if (ielem->indexcolname)
2800 origname = ielem->indexcolname; /* caller-specified name */
2801 else if (ielem->name)
2802 origname = ielem->name; /* simple column reference */
2803 else
2804 origname = "expr"; /* default name for expression */
2805
2806 /* If it conflicts with any previous column, tweak it */
2807 curname = origname;
2808 for (i = 1;; i++)
2809 {
2810 ListCell *lc2;
2811 char nbuf[32];
2812 int nlen;
2813
2814 foreach(lc2, result)
2815 {
2816 if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2817 break;
2818 }
2819 if (lc2 == NULL)
2820 break; /* found nonconflicting name */
2821
2822 sprintf(nbuf, "%d", i);
2823
2824 /* Ensure generated names are shorter than NAMEDATALEN */
2825 nlen = pg_mbcliplen(origname, strlen(origname),
2826 NAMEDATALEN - 1 - strlen(nbuf));
2827 memcpy(buf, origname, nlen);
2828 strcpy(buf + nlen, nbuf);
2829 curname = buf;
2830 }
2831
2832 /* And attach to the result list */
2833 result = lappend(result, pstrdup(curname));
2834 }
2835 return result;
2836}
List * lappend(List *list, void *datum)
Definition: list.c:339
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1086
char * pstrdup(const char *in)
Definition: mcxt.c:1781
#define NAMEDATALEN
#define lfirst(lc)
Definition: pg_list.h:172
static char buf[DEFAULT_XLOG_SEG_SIZE]
Definition: pg_test_fsync.c:71
#define sprintf
Definition: port.h:262
char * indexcolname
Definition: parsenodes.h:813
char * name
Definition: parsenodes.h:811
Definition: pg_list.h:54

References buf, i, IndexElem::indexcolname, lappend(), lfirst, IndexElem::name, NAMEDATALEN, NIL, pg_mbcliplen(), pstrdup(), and sprintf.

Referenced by DefineIndex().

◆ ChooseIndexName()

static char * ChooseIndexName ( const char *  tabname,
Oid  namespaceId,
const List colnames,
const List exclusionOpNames,
bool  primary,
bool  isconstraint 
)
static

Definition at line 2696 of file indexcmds.c.

2699{
2700 char *indexname;
2701
2702 if (primary)
2703 {
2704 /* the primary key's name does not depend on the specific column(s) */
2705 indexname = ChooseRelationName(tabname,
2706 NULL,
2707 "pkey",
2708 namespaceId,
2709 true);
2710 }
2711 else if (exclusionOpNames != NIL)
2712 {
2713 indexname = ChooseRelationName(tabname,
2714 ChooseIndexNameAddition(colnames),
2715 "excl",
2716 namespaceId,
2717 true);
2718 }
2719 else if (isconstraint)
2720 {
2721 indexname = ChooseRelationName(tabname,
2722 ChooseIndexNameAddition(colnames),
2723 "key",
2724 namespaceId,
2725 true);
2726 }
2727 else
2728 {
2729 indexname = ChooseRelationName(tabname,
2730 ChooseIndexNameAddition(colnames),
2731 "idx",
2732 namespaceId,
2733 false);
2734 }
2735
2736 return indexname;
2737}
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2628
static char * ChooseIndexNameAddition(const List *colnames)
Definition: indexcmds.c:2751

References ChooseIndexNameAddition(), ChooseRelationName(), and NIL.

Referenced by DefineIndex().

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( const List colnames)
static

Definition at line 2751 of file indexcmds.c.

2752{
2753 char buf[NAMEDATALEN * 2];
2754 int buflen = 0;
2755 ListCell *lc;
2756
2757 buf[0] = '\0';
2758 foreach(lc, colnames)
2759 {
2760 const char *name = (const char *) lfirst(lc);
2761
2762 if (buflen > 0)
2763 buf[buflen++] = '_'; /* insert _ between names */
2764
2765 /*
2766 * At this point we have buflen <= NAMEDATALEN. name should be less
2767 * than NAMEDATALEN already, but use strlcpy for paranoia.
2768 */
2769 strlcpy(buf + buflen, name, NAMEDATALEN);
2770 buflen += strlen(buf + buflen);
2771 if (buflen >= NAMEDATALEN)
2772 break;
2773 }
2774 return pstrdup(buf);
2775}
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * name

References buf, lfirst, name, NAMEDATALEN, pstrdup(), and strlcpy().

Referenced by ChooseIndexName().

◆ ChooseRelationName()

char * ChooseRelationName ( const char *  name1,
const char *  name2,
const char *  label,
Oid  namespaceid,
bool  isconstraint 
)

Definition at line 2628 of file indexcmds.c.

2631{
2632 int pass = 0;
2633 char *relname = NULL;
2634 char modlabel[NAMEDATALEN];
2635 SnapshotData SnapshotDirty;
2636 Relation pgclassrel;
2637
2638 /* prepare to search pg_class with a dirty snapshot */
2639 InitDirtySnapshot(SnapshotDirty);
2640 pgclassrel = table_open(RelationRelationId, AccessShareLock);
2641
2642 /* try the unmodified label first */
2643 strlcpy(modlabel, label, sizeof(modlabel));
2644
2645 for (;;)
2646 {
2647 ScanKeyData key[2];
2648 SysScanDesc scan;
2649 bool collides;
2650
2651 relname = makeObjectName(name1, name2, modlabel);
2652
2653 /* is there any conflicting relation name? */
2654 ScanKeyInit(&key[0],
2655 Anum_pg_class_relname,
2656 BTEqualStrategyNumber, F_NAMEEQ,
2658 ScanKeyInit(&key[1],
2659 Anum_pg_class_relnamespace,
2660 BTEqualStrategyNumber, F_OIDEQ,
2661 ObjectIdGetDatum(namespaceid));
2662
2663 scan = systable_beginscan(pgclassrel, ClassNameNspIndexId,
2664 true /* indexOK */ ,
2665 &SnapshotDirty,
2666 2, key);
2667
2668 collides = HeapTupleIsValid(systable_getnext(scan));
2669
2670 systable_endscan(scan);
2671
2672 /* break out of loop if no conflict */
2673 if (!collides)
2674 {
2675 if (!isconstraint ||
2676 !ConstraintNameExists(relname, namespaceid))
2677 break;
2678 }
2679
2680 /* found a conflict, so try a new name component */
2681 pfree(relname);
2682 snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2683 }
2684
2685 table_close(pgclassrel, AccessShareLock);
2686
2687 return relname;
2688}
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:514
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:388
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2540
static char * label
NameData relname
Definition: pg_class.h:38
bool ConstraintNameExists(const char *conname, Oid namespaceid)
#define snprintf
Definition: port.h:260
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:360
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:42
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References AccessShareLock, BTEqualStrategyNumber, ConstraintNameExists(), CStringGetDatum(), HeapTupleIsValid, InitDirtySnapshot, sort-test::key, label, makeObjectName(), NAMEDATALEN, ObjectIdGetDatum(), pfree(), relname, ScanKeyInit(), snprintf, strlcpy(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by ChooseIndexName(), generateSerialExtraStmts(), and ReindexRelationConcurrently().

◆ CompareOpclassOptions()

static bool CompareOpclassOptions ( const Datum opts1,
const Datum opts2,
int  natts 
)
static

Definition at line 362 of file indexcmds.c.

363{
364 int i;
365 FmgrInfo fm;
366
367 if (!opts1 && !opts2)
368 return true;
369
370 fmgr_info(F_ARRAY_EQ, &fm);
371 for (i = 0; i < natts; i++)
372 {
373 Datum opt1 = opts1 ? opts1[i] : (Datum) 0;
374 Datum opt2 = opts2 ? opts2[i] : (Datum) 0;
375
376 if (opt1 == (Datum) 0)
377 {
378 if (opt2 == (Datum) 0)
379 continue;
380 else
381 return false;
382 }
383 else if (opt2 == (Datum) 0)
384 return false;
385
386 /*
387 * Compare non-NULL text[] datums. Use C collation to enforce binary
388 * equivalence of texts, because we don't know anything about the
389 * semantics of opclass options.
390 */
391 if (!DatumGetBool(FunctionCall2Coll(&fm, C_COLLATION_OID, opt1, opt2)))
392 return false;
393 }
394
395 return true;
396}
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1150
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:128
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
Definition: fmgr.h:57

References DatumGetBool(), fmgr_info(), FunctionCall2Coll(), and i.

Referenced by CheckIndexCompatible().

◆ ComputeIndexAttrs()

static void ComputeIndexAttrs ( ParseState pstate,
IndexInfo indexInfo,
Oid typeOids,
Oid collationOids,
Oid opclassOids,
Datum opclassOptions,
int16 colOptions,
const List attList,
const List exclusionOpNames,
Oid  relId,
const char *  accessMethodName,
Oid  accessMethodId,
bool  amcanorder,
bool  isconstraint,
bool  iswithoutoverlaps,
Oid  ddl_userid,
int  ddl_sec_context,
int *  ddl_save_nestlevel 
)
static

Definition at line 1875 of file indexcmds.c.

1893{
1894 ListCell *nextExclOp;
1895 ListCell *lc;
1896 int attn;
1897 int nkeycols = indexInfo->ii_NumIndexKeyAttrs;
1898 Oid save_userid;
1899 int save_sec_context;
1900
1901 /* Allocate space for exclusion operator info, if needed */
1902 if (exclusionOpNames)
1903 {
1904 Assert(list_length(exclusionOpNames) == nkeycols);
1905 indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols);
1906 indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols);
1907 indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols);
1908 nextExclOp = list_head(exclusionOpNames);
1909 }
1910 else
1911 nextExclOp = NULL;
1912
1913 /*
1914 * If this is a WITHOUT OVERLAPS constraint, we need space for exclusion
1915 * ops, but we don't need to parse anything, so we can let nextExclOp be
1916 * NULL. Note that for partitions/inheriting/LIKE, exclusionOpNames will
1917 * be set, so we already allocated above.
1918 */
1919 if (iswithoutoverlaps)
1920 {
1921 if (exclusionOpNames == NIL)
1922 {
1923 indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols);
1924 indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols);
1925 indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols);
1926 }
1927 nextExclOp = NULL;
1928 }
1929
1930 if (OidIsValid(ddl_userid))
1931 GetUserIdAndSecContext(&save_userid, &save_sec_context);
1932
1933 /*
1934 * process attributeList
1935 */
1936 attn = 0;
1937 foreach(lc, attList)
1938 {
1939 IndexElem *attribute = (IndexElem *) lfirst(lc);
1940 Oid atttype;
1941 Oid attcollation;
1942
1943 /*
1944 * Process the column-or-expression to be indexed.
1945 */
1946 if (attribute->name != NULL)
1947 {
1948 /* Simple index attribute */
1949 HeapTuple atttuple;
1950 Form_pg_attribute attform;
1951
1952 Assert(attribute->expr == NULL);
1953 atttuple = SearchSysCacheAttName(relId, attribute->name);
1954 if (!HeapTupleIsValid(atttuple))
1955 {
1956 /* difference in error message spellings is historical */
1957 if (isconstraint)
1958 ereport(ERROR,
1959 (errcode(ERRCODE_UNDEFINED_COLUMN),
1960 errmsg("column \"%s\" named in key does not exist",
1961 attribute->name),
1962 parser_errposition(pstate, attribute->location)));
1963 else
1964 ereport(ERROR,
1965 (errcode(ERRCODE_UNDEFINED_COLUMN),
1966 errmsg("column \"%s\" does not exist",
1967 attribute->name),
1968 parser_errposition(pstate, attribute->location)));
1969 }
1970 attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1971 indexInfo->ii_IndexAttrNumbers[attn] = attform->attnum;
1972 atttype = attform->atttypid;
1973 attcollation = attform->attcollation;
1974 ReleaseSysCache(atttuple);
1975 }
1976 else
1977 {
1978 /* Index expression */
1979 Node *expr = attribute->expr;
1980
1981 Assert(expr != NULL);
1982
1983 if (attn >= nkeycols)
1984 ereport(ERROR,
1985 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1986 errmsg("expressions are not supported in included columns"),
1987 parser_errposition(pstate, attribute->location)));
1988 atttype = exprType(expr);
1989 attcollation = exprCollation(expr);
1990
1991 /*
1992 * Strip any top-level COLLATE clause. This ensures that we treat
1993 * "x COLLATE y" and "(x COLLATE y)" alike.
1994 */
1995 while (IsA(expr, CollateExpr))
1996 expr = (Node *) ((CollateExpr *) expr)->arg;
1997
1998 if (IsA(expr, Var) &&
1999 ((Var *) expr)->varattno != InvalidAttrNumber)
2000 {
2001 /*
2002 * User wrote "(column)" or "(column COLLATE something)".
2003 * Treat it like simple attribute anyway.
2004 */
2005 indexInfo->ii_IndexAttrNumbers[attn] = ((Var *) expr)->varattno;
2006 }
2007 else
2008 {
2009 indexInfo->ii_IndexAttrNumbers[attn] = 0; /* marks expression */
2010 indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
2011 expr);
2012
2013 /*
2014 * transformExpr() should have already rejected subqueries,
2015 * aggregates, and window functions, based on the EXPR_KIND_
2016 * for an index expression.
2017 */
2018
2019 /*
2020 * An expression using mutable functions is probably wrong,
2021 * since if you aren't going to get the same result for the
2022 * same data every time, it's not clear what the index entries
2023 * mean at all.
2024 */
2026 ereport(ERROR,
2027 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2028 errmsg("functions in index expression must be marked IMMUTABLE"),
2029 parser_errposition(pstate, attribute->location)));
2030 }
2031 }
2032
2033 typeOids[attn] = atttype;
2034
2035 /*
2036 * Included columns have no collation, no opclass and no ordering
2037 * options.
2038 */
2039 if (attn >= nkeycols)
2040 {
2041 if (attribute->collation)
2042 ereport(ERROR,
2043 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2044 errmsg("including column does not support a collation"),
2045 parser_errposition(pstate, attribute->location)));
2046 if (attribute->opclass)
2047 ereport(ERROR,
2048 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2049 errmsg("including column does not support an operator class"),
2050 parser_errposition(pstate, attribute->location)));
2051 if (attribute->ordering != SORTBY_DEFAULT)
2052 ereport(ERROR,
2053 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2054 errmsg("including column does not support ASC/DESC options"),
2055 parser_errposition(pstate, attribute->location)));
2056 if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
2057 ereport(ERROR,
2058 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2059 errmsg("including column does not support NULLS FIRST/LAST options"),
2060 parser_errposition(pstate, attribute->location)));
2061
2062 opclassOids[attn] = InvalidOid;
2063 opclassOptions[attn] = (Datum) 0;
2064 colOptions[attn] = 0;
2065 collationOids[attn] = InvalidOid;
2066 attn++;
2067
2068 continue;
2069 }
2070
2071 /*
2072 * Apply collation override if any. Use of ddl_userid is necessary
2073 * due to ACL checks therein, and it's safe because collations don't
2074 * contain opaque expressions (or non-opaque expressions).
2075 */
2076 if (attribute->collation)
2077 {
2078 if (OidIsValid(ddl_userid))
2079 {
2080 AtEOXact_GUC(false, *ddl_save_nestlevel);
2081 SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
2082 }
2083 attcollation = get_collation_oid(attribute->collation, false);
2084 if (OidIsValid(ddl_userid))
2085 {
2086 SetUserIdAndSecContext(save_userid, save_sec_context);
2087 *ddl_save_nestlevel = NewGUCNestLevel();
2089 }
2090 }
2091
2092 /*
2093 * Check we have a collation iff it's a collatable type. The only
2094 * expected failures here are (1) COLLATE applied to a noncollatable
2095 * type, or (2) index expression had an unresolved collation. But we
2096 * might as well code this to be a complete consistency check.
2097 */
2098 if (type_is_collatable(atttype))
2099 {
2100 if (!OidIsValid(attcollation))
2101 ereport(ERROR,
2102 (errcode(ERRCODE_INDETERMINATE_COLLATION),
2103 errmsg("could not determine which collation to use for index expression"),
2104 errhint("Use the COLLATE clause to set the collation explicitly."),
2105 parser_errposition(pstate, attribute->location)));
2106 }
2107 else
2108 {
2109 if (OidIsValid(attcollation))
2110 ereport(ERROR,
2111 (errcode(ERRCODE_DATATYPE_MISMATCH),
2112 errmsg("collations are not supported by type %s",
2113 format_type_be(atttype)),
2114 parser_errposition(pstate, attribute->location)));
2115 }
2116
2117 collationOids[attn] = attcollation;
2118
2119 /*
2120 * Identify the opclass to use. Use of ddl_userid is necessary due to
2121 * ACL checks therein. This is safe despite opclasses containing
2122 * opaque expressions (specifically, functions), because only
2123 * superusers can define opclasses.
2124 */
2125 if (OidIsValid(ddl_userid))
2126 {
2127 AtEOXact_GUC(false, *ddl_save_nestlevel);
2128 SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
2129 }
2130 opclassOids[attn] = ResolveOpClass(attribute->opclass,
2131 atttype,
2132 accessMethodName,
2133 accessMethodId);
2134 if (OidIsValid(ddl_userid))
2135 {
2136 SetUserIdAndSecContext(save_userid, save_sec_context);
2137 *ddl_save_nestlevel = NewGUCNestLevel();
2139 }
2140
2141 /*
2142 * Identify the exclusion operator, if any.
2143 */
2144 if (nextExclOp)
2145 {
2146 List *opname = (List *) lfirst(nextExclOp);
2147 Oid opid;
2148 Oid opfamily;
2149 int strat;
2150
2151 /*
2152 * Find the operator --- it must accept the column datatype
2153 * without runtime coercion (but binary compatibility is OK).
2154 * Operators contain opaque expressions (specifically, functions).
2155 * compatible_oper_opid() boils down to oper() and
2156 * IsBinaryCoercible(). PostgreSQL would have security problems
2157 * elsewhere if oper() started calling opaque expressions.
2158 */
2159 if (OidIsValid(ddl_userid))
2160 {
2161 AtEOXact_GUC(false, *ddl_save_nestlevel);
2162 SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
2163 }
2164 opid = compatible_oper_opid(opname, atttype, atttype, false);
2165 if (OidIsValid(ddl_userid))
2166 {
2167 SetUserIdAndSecContext(save_userid, save_sec_context);
2168 *ddl_save_nestlevel = NewGUCNestLevel();
2170 }
2171
2172 /*
2173 * Only allow commutative operators to be used in exclusion
2174 * constraints. If X conflicts with Y, but Y does not conflict
2175 * with X, bad things will happen.
2176 */
2177 if (get_commutator(opid) != opid)
2178 ereport(ERROR,
2179 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2180 errmsg("operator %s is not commutative",
2181 format_operator(opid)),
2182 errdetail("Only commutative operators can be used in exclusion constraints."),
2183 parser_errposition(pstate, attribute->location)));
2184
2185 /*
2186 * Operator must be a member of the right opfamily, too
2187 */
2188 opfamily = get_opclass_family(opclassOids[attn]);
2189 strat = get_op_opfamily_strategy(opid, opfamily);
2190 if (strat == 0)
2191 ereport(ERROR,
2192 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2193 errmsg("operator %s is not a member of operator family \"%s\"",
2194 format_operator(opid),
2195 get_opfamily_name(opfamily, false)),
2196 errdetail("The exclusion operator must be related to the index operator class for the constraint."),
2197 parser_errposition(pstate, attribute->location)));
2198
2199 indexInfo->ii_ExclusionOps[attn] = opid;
2200 indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
2201 indexInfo->ii_ExclusionStrats[attn] = strat;
2202 nextExclOp = lnext(exclusionOpNames, nextExclOp);
2203 }
2204 else if (iswithoutoverlaps)
2205 {
2206 CompareType cmptype;
2207 StrategyNumber strat;
2208 Oid opid;
2209
2210 if (attn == nkeycols - 1)
2211 cmptype = COMPARE_OVERLAP;
2212 else
2213 cmptype = COMPARE_EQ;
2214 GetOperatorFromCompareType(opclassOids[attn], InvalidOid, cmptype, &opid, &strat);
2215 indexInfo->ii_ExclusionOps[attn] = opid;
2216 indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
2217 indexInfo->ii_ExclusionStrats[attn] = strat;
2218 }
2219
2220 /*
2221 * Set up the per-column options (indoption field). For now, this is
2222 * zero for any un-ordered index, while ordered indexes have DESC and
2223 * NULLS FIRST/LAST options.
2224 */
2225 colOptions[attn] = 0;
2226 if (amcanorder)
2227 {
2228 /* default ordering is ASC */
2229 if (attribute->ordering == SORTBY_DESC)
2230 colOptions[attn] |= INDOPTION_DESC;
2231 /* default null ordering is LAST for ASC, FIRST for DESC */
2232 if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
2233 {
2234 if (attribute->ordering == SORTBY_DESC)
2235 colOptions[attn] |= INDOPTION_NULLS_FIRST;
2236 }
2237 else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
2238 colOptions[attn] |= INDOPTION_NULLS_FIRST;
2239 }
2240 else
2241 {
2242 /* index AM does not support ordering */
2243 if (attribute->ordering != SORTBY_DEFAULT)
2244 ereport(ERROR,
2245 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2246 errmsg("access method \"%s\" does not support ASC/DESC options",
2247 accessMethodName),
2248 parser_errposition(pstate, attribute->location)));
2249 if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
2250 ereport(ERROR,
2251 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2252 errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
2253 accessMethodName),
2254 parser_errposition(pstate, attribute->location)));
2255 }
2256
2257 /* Set up the per-column opclass options (attoptions field). */
2258 if (attribute->opclassopts)
2259 {
2260 Assert(attn < nkeycols);
2261
2262 opclassOptions[attn] =
2263 transformRelOptions((Datum) 0, attribute->opclassopts,
2264 NULL, NULL, false, false);
2265 }
2266 else
2267 opclassOptions[attn] = (Datum) 0;
2268
2269 attn++;
2270 }
2271}
#define InvalidAttrNumber
Definition: attnum.h:23
#define OidIsValid(objectId)
Definition: c.h:788
CompareType
Definition: cmptype.h:32
@ COMPARE_OVERLAP
Definition: cmptype.h:40
@ COMPARE_EQ
Definition: cmptype.h:36
int errdetail(const char *fmt,...)
Definition: elog.c:1216
int errhint(const char *fmt,...)
Definition: elog.c:1330
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
int NewGUCNestLevel(void)
Definition: guc.c:2110
void RestrictSearchPath(void)
Definition: guc.c:2121
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2137
Oid ResolveOpClass(const List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
Definition: indexcmds.c:2280
void GetOperatorFromCompareType(Oid opclass, Oid rhstype, CompareType cmptype, Oid *opid, StrategyNumber *strat)
Definition: indexcmds.c:2467
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1292
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1435
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:85
char * get_opfamily_name(Oid opfid, bool missing_ok)
Definition: lsyscache.c:1403
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:3231
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1659
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:612
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:619
Oid get_collation_oid(List *collname, bool missing_ok)
Definition: namespace.c:4041
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:490
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
void * arg
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
char * format_operator(Oid operator_oid)
Definition: regproc.c:801
Datum transformRelOptions(Datum oldOptions, List *defList, const char *nameSpace, const char *const validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1176
uint16 StrategyNumber
Definition: stratnum.h:22
Node * expr
Definition: parsenodes.h:812
SortByDir ordering
Definition: parsenodes.h:817
List * opclassopts
Definition: parsenodes.h:816
ParseLoc location
Definition: parsenodes.h:819
SortByNulls nulls_ordering
Definition: parsenodes.h:818
List * opclass
Definition: parsenodes.h:815
List * collation
Definition: parsenodes.h:814
uint16 * ii_ExclusionStrats
Definition: execnodes.h:192
int ii_NumIndexKeyAttrs
Definition: execnodes.h:169
List * ii_Expressions
Definition: execnodes.h:178
Oid * ii_ExclusionProcs
Definition: execnodes.h:190
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:175
Definition: nodes.h:135
Definition: primnodes.h:262
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:475

References arg, Assert(), AtEOXact_GUC(), IndexElem::collation, COMPARE_EQ, COMPARE_OVERLAP, compatible_oper_opid(), contain_mutable_functions_after_planning(), ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, IndexElem::expr, exprCollation(), exprType(), format_operator(), format_type_be(), get_collation_oid(), get_commutator(), get_op_opfamily_strategy(), get_opclass_family(), get_opcode(), get_opfamily_name(), GetOperatorFromCompareType(), GETSTRUCT(), GetUserIdAndSecContext(), HeapTupleIsValid, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexKeyAttrs, InvalidAttrNumber, InvalidOid, IsA, lappend(), lfirst, list_head(), list_length(), lnext(), IndexElem::location, IndexElem::name, NewGUCNestLevel(), NIL, IndexElem::nulls_ordering, OidIsValid, IndexElem::opclass, IndexElem::opclassopts, IndexElem::ordering, palloc_array, parser_errposition(), ReleaseSysCache(), ResolveOpClass(), RestrictSearchPath(), SearchSysCacheAttName(), SetUserIdAndSecContext(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, transformRelOptions(), and type_is_collatable().

Referenced by CheckIndexCompatible(), and DefineIndex().

◆ DefineIndex()

ObjectAddress DefineIndex ( ParseState pstate,
Oid  tableId,
IndexStmt stmt,
Oid  indexRelationId,
Oid  parentIndexId,
Oid  parentConstraintId,
int  total_parts,
bool  is_alter_table,
bool  check_rights,
bool  check_not_in_use,
bool  skip_build,
bool  quiet 
)

Definition at line 544 of file indexcmds.c.

556{
557 bool concurrent;
558 char *indexRelationName;
559 char *accessMethodName;
560 Oid *typeIds;
561 Oid *collationIds;
562 Oid *opclassIds;
563 Datum *opclassOptions;
564 Oid accessMethodId;
565 Oid namespaceId;
566 Oid tablespaceId;
567 Oid createdConstraintId = InvalidOid;
568 List *indexColNames;
569 List *allIndexParams;
570 Relation rel;
571 HeapTuple tuple;
572 Form_pg_am accessMethodForm;
573 const IndexAmRoutine *amRoutine;
574 bool amcanorder;
575 bool amissummarizing;
576 amoptions_function amoptions;
577 bool exclusion;
578 bool partitioned;
579 bool safe_index;
580 Datum reloptions;
581 int16 *coloptions;
582 IndexInfo *indexInfo;
583 bits16 flags;
584 bits16 constr_flags;
585 int numberOfAttributes;
586 int numberOfKeyAttributes;
587 TransactionId limitXmin;
588 ObjectAddress address;
589 LockRelId heaprelid;
590 LOCKTAG heaplocktag;
591 LOCKMODE lockmode;
592 Snapshot snapshot;
593 Oid root_save_userid;
594 int root_save_sec_context;
595 int root_save_nestlevel;
596
597 root_save_nestlevel = NewGUCNestLevel();
598
600
601 /*
602 * Some callers need us to run with an empty default_tablespace; this is a
603 * necessary hack to be able to reproduce catalog state accurately when
604 * recreating indexes after table-rewriting ALTER TABLE.
605 */
606 if (stmt->reset_default_tblspc)
607 (void) set_config_option("default_tablespace", "",
609 GUC_ACTION_SAVE, true, 0, false);
610
611 /*
612 * Force non-concurrent build on temporary relations, even if CONCURRENTLY
613 * was requested. Other backends can't access a temporary relation, so
614 * there's no harm in grabbing a stronger lock, and a non-concurrent DROP
615 * is more efficient. Do this before any use of the concurrent option is
616 * done.
617 */
618 if (stmt->concurrent && get_rel_persistence(tableId) != RELPERSISTENCE_TEMP)
619 concurrent = true;
620 else
621 concurrent = false;
622
623 /*
624 * Start progress report. If we're building a partition, this was already
625 * done.
626 */
627 if (!OidIsValid(parentIndexId))
628 {
631 concurrent ?
634 }
635
636 /*
637 * No index OID to report yet
638 */
640 InvalidOid);
641
642 /*
643 * count key attributes in index
644 */
645 numberOfKeyAttributes = list_length(stmt->indexParams);
646
647 /*
648 * Calculate the new list of index columns including both key columns and
649 * INCLUDE columns. Later we can determine which of these are key
650 * columns, and which are just part of the INCLUDE list by checking the
651 * list position. A list item in a position less than ii_NumIndexKeyAttrs
652 * is part of the key columns, and anything equal to and over is part of
653 * the INCLUDE columns.
654 */
655 allIndexParams = list_concat_copy(stmt->indexParams,
656 stmt->indexIncludingParams);
657 numberOfAttributes = list_length(allIndexParams);
658
659 if (numberOfKeyAttributes <= 0)
661 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
662 errmsg("must specify at least one column")));
663 if (numberOfAttributes > INDEX_MAX_KEYS)
665 (errcode(ERRCODE_TOO_MANY_COLUMNS),
666 errmsg("cannot use more than %d columns in an index",
668
669 /*
670 * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
671 * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
672 * (but not VACUUM).
673 *
674 * NB: Caller is responsible for making sure that tableId refers to the
675 * relation on which the index should be built; except in bootstrap mode,
676 * this will typically require the caller to have already locked the
677 * relation. To avoid lock upgrade hazards, that lock should be at least
678 * as strong as the one we take here.
679 *
680 * NB: If the lock strength here ever changes, code that is run by
681 * parallel workers under the control of certain particular ambuild
682 * functions will need to be updated, too.
683 */
684 lockmode = concurrent ? ShareUpdateExclusiveLock : ShareLock;
685 rel = table_open(tableId, lockmode);
686
687 /*
688 * Switch to the table owner's userid, so that any index functions are run
689 * as that user. Also lock down security-restricted operations. We
690 * already arranged to make GUC variable changes local to this command.
691 */
692 GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context);
693 SetUserIdAndSecContext(rel->rd_rel->relowner,
694 root_save_sec_context | SECURITY_RESTRICTED_OPERATION);
695
696 namespaceId = RelationGetNamespace(rel);
697
698 /*
699 * It has exclusion constraint behavior if it's an EXCLUDE constraint or a
700 * temporal PRIMARY KEY/UNIQUE constraint
701 */
702 exclusion = stmt->excludeOpNames || stmt->iswithoutoverlaps;
703
704 /* Ensure that it makes sense to index this kind of relation */
705 switch (rel->rd_rel->relkind)
706 {
707 case RELKIND_RELATION:
708 case RELKIND_MATVIEW:
709 case RELKIND_PARTITIONED_TABLE:
710 /* OK */
711 break;
712 default:
714 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
715 errmsg("cannot create index on relation \"%s\"",
718 break;
719 }
720
721 /*
722 * Establish behavior for partitioned tables, and verify sanity of
723 * parameters.
724 *
725 * We do not build an actual index in this case; we only create a few
726 * catalog entries. The actual indexes are built by recursing for each
727 * partition.
728 */
729 partitioned = rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
730 if (partitioned)
731 {
732 /*
733 * Note: we check 'stmt->concurrent' rather than 'concurrent', so that
734 * the error is thrown also for temporary tables. Seems better to be
735 * consistent, even though we could do it on temporary table because
736 * we're not actually doing it concurrently.
737 */
738 if (stmt->concurrent)
740 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
741 errmsg("cannot create index on partitioned table \"%s\" concurrently",
743 }
744
745 /*
746 * Don't try to CREATE INDEX on temp tables of other backends.
747 */
748 if (RELATION_IS_OTHER_TEMP(rel))
750 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
751 errmsg("cannot create indexes on temporary tables of other sessions")));
752
753 /*
754 * Unless our caller vouches for having checked this already, insist that
755 * the table not be in use by our own session, either. Otherwise we might
756 * fail to make entries in the new index (for instance, if an INSERT or
757 * UPDATE is in progress and has already made its list of target indexes).
758 */
759 if (check_not_in_use)
760 CheckTableNotInUse(rel, "CREATE INDEX");
761
762 /*
763 * Verify we (still) have CREATE rights in the rel's namespace.
764 * (Presumably we did when the rel was created, but maybe not anymore.)
765 * Skip check if caller doesn't want it. Also skip check if
766 * bootstrapping, since permissions machinery may not be working yet.
767 */
768 if (check_rights && !IsBootstrapProcessingMode())
769 {
770 AclResult aclresult;
771
772 aclresult = object_aclcheck(NamespaceRelationId, namespaceId, root_save_userid,
773 ACL_CREATE);
774 if (aclresult != ACLCHECK_OK)
775 aclcheck_error(aclresult, OBJECT_SCHEMA,
776 get_namespace_name(namespaceId));
777 }
778
779 /*
780 * Select tablespace to use. If not specified, use default tablespace
781 * (which may in turn default to database's default).
782 */
783 if (stmt->tableSpace)
784 {
785 tablespaceId = get_tablespace_oid(stmt->tableSpace, false);
786 if (partitioned && tablespaceId == MyDatabaseTableSpace)
788 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
789 errmsg("cannot specify default tablespace for partitioned relations")));
790 }
791 else
792 {
793 tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence,
794 partitioned);
795 /* note InvalidOid is OK in this case */
796 }
797
798 /* Check tablespace permissions */
799 if (check_rights &&
800 OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
801 {
802 AclResult aclresult;
803
804 aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, root_save_userid,
805 ACL_CREATE);
806 if (aclresult != ACLCHECK_OK)
808 get_tablespace_name(tablespaceId));
809 }
810
811 /*
812 * Force shared indexes into the pg_global tablespace. This is a bit of a
813 * hack but seems simpler than marking them in the BKI commands. On the
814 * other hand, if it's not shared, don't allow it to be placed there.
815 */
816 if (rel->rd_rel->relisshared)
817 tablespaceId = GLOBALTABLESPACE_OID;
818 else if (tablespaceId == GLOBALTABLESPACE_OID)
820 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
821 errmsg("only shared relations can be placed in pg_global tablespace")));
822
823 /*
824 * Choose the index column names.
825 */
826 indexColNames = ChooseIndexColumnNames(allIndexParams);
827
828 /*
829 * Select name for index if caller didn't specify
830 */
831 indexRelationName = stmt->idxname;
832 if (indexRelationName == NULL)
833 indexRelationName = ChooseIndexName(RelationGetRelationName(rel),
834 namespaceId,
835 indexColNames,
836 stmt->excludeOpNames,
837 stmt->primary,
838 stmt->isconstraint);
839
840 /*
841 * look up the access method, verify it can handle the requested features
842 */
843 accessMethodName = stmt->accessMethod;
844 tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
845 if (!HeapTupleIsValid(tuple))
846 {
847 /*
848 * Hack to provide more-or-less-transparent updating of old RTREE
849 * indexes to GiST: if RTREE is requested and not found, use GIST.
850 */
851 if (strcmp(accessMethodName, "rtree") == 0)
852 {
854 (errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
855 accessMethodName = "gist";
856 tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
857 }
858
859 if (!HeapTupleIsValid(tuple))
861 (errcode(ERRCODE_UNDEFINED_OBJECT),
862 errmsg("access method \"%s\" does not exist",
863 accessMethodName)));
864 }
865 accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
866 accessMethodId = accessMethodForm->oid;
867 amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
868
870 accessMethodId);
871
872 if (stmt->unique && !stmt->iswithoutoverlaps && !amRoutine->amcanunique)
874 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
875 errmsg("access method \"%s\" does not support unique indexes",
876 accessMethodName)));
877 if (stmt->indexIncludingParams != NIL && !amRoutine->amcaninclude)
879 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
880 errmsg("access method \"%s\" does not support included columns",
881 accessMethodName)));
882 if (numberOfKeyAttributes > 1 && !amRoutine->amcanmulticol)
884 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
885 errmsg("access method \"%s\" does not support multicolumn indexes",
886 accessMethodName)));
887 if (exclusion && amRoutine->amgettuple == NULL)
889 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
890 errmsg("access method \"%s\" does not support exclusion constraints",
891 accessMethodName)));
892 if (stmt->iswithoutoverlaps && strcmp(accessMethodName, "gist") != 0)
894 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
895 errmsg("access method \"%s\" does not support WITHOUT OVERLAPS constraints",
896 accessMethodName)));
897
898 amcanorder = amRoutine->amcanorder;
899 amoptions = amRoutine->amoptions;
900 amissummarizing = amRoutine->amsummarizing;
901
902 ReleaseSysCache(tuple);
903
904 /*
905 * Validate predicate, if given
906 */
907 if (stmt->whereClause)
908 CheckPredicate((Expr *) stmt->whereClause);
909
910 /*
911 * Parse AM-specific options, convert to text array form, validate.
912 */
913 reloptions = transformRelOptions((Datum) 0, stmt->options,
914 NULL, NULL, false, false);
915
916 (void) index_reloptions(amoptions, reloptions, true);
917
918 /*
919 * Prepare arguments for index_create, primarily an IndexInfo structure.
920 * Note that predicates must be in implicit-AND format. In a concurrent
921 * build, mark it not-ready-for-inserts.
922 */
923 indexInfo = makeIndexInfo(numberOfAttributes,
924 numberOfKeyAttributes,
925 accessMethodId,
926 NIL, /* expressions, NIL for now */
927 make_ands_implicit((Expr *) stmt->whereClause),
928 stmt->unique,
929 stmt->nulls_not_distinct,
930 !concurrent,
931 concurrent,
932 amissummarizing,
933 stmt->iswithoutoverlaps);
934
935 typeIds = palloc_array(Oid, numberOfAttributes);
936 collationIds = palloc_array(Oid, numberOfAttributes);
937 opclassIds = palloc_array(Oid, numberOfAttributes);
938 opclassOptions = palloc_array(Datum, numberOfAttributes);
939 coloptions = palloc_array(int16, numberOfAttributes);
940 ComputeIndexAttrs(pstate,
941 indexInfo,
942 typeIds, collationIds, opclassIds, opclassOptions,
943 coloptions, allIndexParams,
944 stmt->excludeOpNames, tableId,
945 accessMethodName, accessMethodId,
946 amcanorder, stmt->isconstraint, stmt->iswithoutoverlaps,
947 root_save_userid, root_save_sec_context,
948 &root_save_nestlevel);
949
950 /*
951 * Extra checks when creating a PRIMARY KEY index.
952 */
953 if (stmt->primary)
954 index_check_primary_key(rel, indexInfo, is_alter_table, stmt);
955
956 /*
957 * If this table is partitioned and we're creating a unique index, primary
958 * key, or exclusion constraint, make sure that the partition key is a
959 * subset of the index's columns. Otherwise it would be possible to
960 * violate uniqueness by putting values that ought to be unique in
961 * different partitions.
962 *
963 * We could lift this limitation if we had global indexes, but those have
964 * their own problems, so this is a useful feature combination.
965 */
966 if (partitioned && (stmt->unique || exclusion))
967 {
969 const char *constraint_type;
970 int i;
971
972 if (stmt->primary)
973 constraint_type = "PRIMARY KEY";
974 else if (stmt->unique)
975 constraint_type = "UNIQUE";
976 else if (stmt->excludeOpNames)
977 constraint_type = "EXCLUDE";
978 else
979 {
980 elog(ERROR, "unknown constraint type");
981 constraint_type = NULL; /* keep compiler quiet */
982 }
983
984 /*
985 * Verify that all the columns in the partition key appear in the
986 * unique key definition, with the same notion of equality.
987 */
988 for (i = 0; i < key->partnatts; i++)
989 {
990 bool found = false;
991 int eq_strategy;
992 Oid ptkey_eqop;
993 int j;
994
995 /*
996 * Identify the equality operator associated with this partkey
997 * column. For list and range partitioning, partkeys use btree
998 * operator classes; hash partitioning uses hash operator classes.
999 * (Keep this in sync with ComputePartitionAttrs!)
1000 */
1001 if (key->strategy == PARTITION_STRATEGY_HASH)
1002 eq_strategy = HTEqualStrategyNumber;
1003 else
1004 eq_strategy = BTEqualStrategyNumber;
1005
1006 ptkey_eqop = get_opfamily_member(key->partopfamily[i],
1007 key->partopcintype[i],
1008 key->partopcintype[i],
1009 eq_strategy);
1010 if (!OidIsValid(ptkey_eqop))
1011 elog(ERROR, "missing operator %d(%u,%u) in partition opfamily %u",
1012 eq_strategy, key->partopcintype[i], key->partopcintype[i],
1013 key->partopfamily[i]);
1014
1015 /*
1016 * It may be possible to support UNIQUE constraints when partition
1017 * keys are expressions, but is it worth it? Give up for now.
1018 */
1019 if (key->partattrs[i] == 0)
1020 ereport(ERROR,
1021 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1022 errmsg("unsupported %s constraint with partition key definition",
1023 constraint_type),
1024 errdetail("%s constraints cannot be used when partition keys include expressions.",
1025 constraint_type)));
1026
1027 /* Search the index column(s) for a match */
1028 for (j = 0; j < indexInfo->ii_NumIndexKeyAttrs; j++)
1029 {
1030 if (key->partattrs[i] == indexInfo->ii_IndexAttrNumbers[j])
1031 {
1032 /*
1033 * Matched the column, now what about the collation and
1034 * equality op?
1035 */
1036 Oid idx_opfamily;
1037 Oid idx_opcintype;
1038
1039 if (key->partcollation[i] != collationIds[j])
1040 continue;
1041
1042 if (get_opclass_opfamily_and_input_type(opclassIds[j],
1043 &idx_opfamily,
1044 &idx_opcintype))
1045 {
1046 Oid idx_eqop = InvalidOid;
1047
1048 if (stmt->unique && !stmt->iswithoutoverlaps)
1049 idx_eqop = get_opfamily_member_for_cmptype(idx_opfamily,
1050 idx_opcintype,
1051 idx_opcintype,
1052 COMPARE_EQ);
1053 else if (exclusion)
1054 idx_eqop = indexInfo->ii_ExclusionOps[j];
1055
1056 if (!idx_eqop)
1057 ereport(ERROR,
1058 errcode(ERRCODE_UNDEFINED_OBJECT),
1059 errmsg("could not identify an equality operator for type %s", format_type_be(idx_opcintype)),
1060 errdetail("There is no suitable operator in operator family \"%s\" for access method \"%s\".",
1061 get_opfamily_name(idx_opfamily, false), get_am_name(get_opfamily_method(idx_opfamily))));
1062
1063 if (ptkey_eqop == idx_eqop)
1064 {
1065 found = true;
1066 break;
1067 }
1068 else if (exclusion)
1069 {
1070 /*
1071 * We found a match, but it's not an equality
1072 * operator. Instead of failing below with an
1073 * error message about a missing column, fail now
1074 * and explain that the operator is wrong.
1075 */
1076 Form_pg_attribute att = TupleDescAttr(RelationGetDescr(rel), key->partattrs[i] - 1);
1077
1078 ereport(ERROR,
1079 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1080 errmsg("cannot match partition key to index on column \"%s\" using non-equal operator \"%s\"",
1081 NameStr(att->attname),
1082 get_opname(indexInfo->ii_ExclusionOps[j]))));
1083 }
1084 }
1085 }
1086 }
1087
1088 if (!found)
1089 {
1091
1093 key->partattrs[i] - 1);
1094 ereport(ERROR,
1095 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1096 errmsg("unique constraint on partitioned table must include all partitioning columns"),
1097 errdetail("%s constraint on table \"%s\" lacks column \"%s\" which is part of the partition key.",
1098 constraint_type, RelationGetRelationName(rel),
1099 NameStr(att->attname))));
1100 }
1101 }
1102 }
1103
1104
1105 /*
1106 * We disallow indexes on system columns. They would not necessarily get
1107 * updated correctly, and they don't seem useful anyway.
1108 *
1109 * Also disallow virtual generated columns in indexes (use expression
1110 * index instead).
1111 */
1112 for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1113 {
1114 AttrNumber attno = indexInfo->ii_IndexAttrNumbers[i];
1115
1116 if (attno < 0)
1117 ereport(ERROR,
1118 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1119 errmsg("index creation on system columns is not supported")));
1120
1121
1122 if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
1123 ereport(ERROR,
1124 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1125 stmt->primary ?
1126 errmsg("primary keys on virtual generated columns are not supported") :
1127 stmt->isconstraint ?
1128 errmsg("unique constraints on virtual generated columns are not supported") :
1129 errmsg("indexes on virtual generated columns are not supported"));
1130 }
1131
1132 /*
1133 * Also check for system and generated columns used in expressions or
1134 * predicates.
1135 */
1136 if (indexInfo->ii_Expressions || indexInfo->ii_Predicate)
1137 {
1138 Bitmapset *indexattrs = NULL;
1139 int j;
1140
1141 pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs);
1142 pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs);
1143
1144 for (int i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
1145 {
1147 indexattrs))
1148 ereport(ERROR,
1149 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1150 errmsg("index creation on system columns is not supported")));
1151 }
1152
1153 /*
1154 * XXX Virtual generated columns in index expressions or predicates
1155 * could be supported, but it needs support in
1156 * RelationGetIndexExpressions() and RelationGetIndexPredicate().
1157 */
1158 j = -1;
1159 while ((j = bms_next_member(indexattrs, j)) >= 0)
1160 {
1162
1163 if (TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
1164 ereport(ERROR,
1165 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1166 stmt->isconstraint ?
1167 errmsg("unique constraints on virtual generated columns are not supported") :
1168 errmsg("indexes on virtual generated columns are not supported")));
1169 }
1170 }
1171
1172 /* Is index safe for others to ignore? See set_indexsafe_procflags() */
1173 safe_index = indexInfo->ii_Expressions == NIL &&
1174 indexInfo->ii_Predicate == NIL;
1175
1176 /*
1177 * Report index creation if appropriate (delay this till after most of the
1178 * error checks)
1179 */
1180 if (stmt->isconstraint && !quiet)
1181 {
1182 const char *constraint_type;
1183
1184 if (stmt->primary)
1185 constraint_type = "PRIMARY KEY";
1186 else if (stmt->unique)
1187 constraint_type = "UNIQUE";
1188 else if (stmt->excludeOpNames)
1189 constraint_type = "EXCLUDE";
1190 else
1191 {
1192 elog(ERROR, "unknown constraint type");
1193 constraint_type = NULL; /* keep compiler quiet */
1194 }
1195
1197 (errmsg_internal("%s %s will create implicit index \"%s\" for table \"%s\"",
1198 is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
1199 constraint_type,
1200 indexRelationName, RelationGetRelationName(rel))));
1201 }
1202
1203 /*
1204 * A valid stmt->oldNumber implies that we already have a built form of
1205 * the index. The caller should also decline any index build.
1206 */
1207 Assert(!RelFileNumberIsValid(stmt->oldNumber) || (skip_build && !concurrent));
1208
1209 /*
1210 * Make the catalog entries for the index, including constraints. This
1211 * step also actually builds the index, except if caller requested not to
1212 * or in concurrent mode, in which case it'll be done later, or doing a
1213 * partitioned index (because those don't have storage).
1214 */
1215 flags = constr_flags = 0;
1216 if (stmt->isconstraint)
1218 if (skip_build || concurrent || partitioned)
1219 flags |= INDEX_CREATE_SKIP_BUILD;
1220 if (stmt->if_not_exists)
1222 if (concurrent)
1223 flags |= INDEX_CREATE_CONCURRENT;
1224 if (partitioned)
1225 flags |= INDEX_CREATE_PARTITIONED;
1226 if (stmt->primary)
1227 flags |= INDEX_CREATE_IS_PRIMARY;
1228
1229 /*
1230 * If the table is partitioned, and recursion was declined but partitions
1231 * exist, mark the index as invalid.
1232 */
1233 if (partitioned && stmt->relation && !stmt->relation->inh)
1234 {
1236
1237 if (pd->nparts != 0)
1238 flags |= INDEX_CREATE_INVALID;
1239 }
1240
1241 if (stmt->deferrable)
1242 constr_flags |= INDEX_CONSTR_CREATE_DEFERRABLE;
1243 if (stmt->initdeferred)
1244 constr_flags |= INDEX_CONSTR_CREATE_INIT_DEFERRED;
1245 if (stmt->iswithoutoverlaps)
1247
1248 indexRelationId =
1249 index_create(rel, indexRelationName, indexRelationId, parentIndexId,
1250 parentConstraintId,
1251 stmt->oldNumber, indexInfo, indexColNames,
1252 accessMethodId, tablespaceId,
1253 collationIds, opclassIds, opclassOptions,
1254 coloptions, NULL, reloptions,
1255 flags, constr_flags,
1256 allowSystemTableMods, !check_rights,
1257 &createdConstraintId);
1258
1259 ObjectAddressSet(address, RelationRelationId, indexRelationId);
1260
1261 if (!OidIsValid(indexRelationId))
1262 {
1263 /*
1264 * Roll back any GUC changes executed by index functions. Also revert
1265 * to original default_tablespace if we changed it above.
1266 */
1267 AtEOXact_GUC(false, root_save_nestlevel);
1268
1269 /* Restore userid and security context */
1270 SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
1271
1272 table_close(rel, NoLock);
1273
1274 /* If this is the top-level index, we're done */
1275 if (!OidIsValid(parentIndexId))
1277
1278 return address;
1279 }
1280
1281 /*
1282 * Roll back any GUC changes executed by index functions, and keep
1283 * subsequent changes local to this command. This is essential if some
1284 * index function changed a behavior-affecting GUC, e.g. search_path.
1285 */
1286 AtEOXact_GUC(false, root_save_nestlevel);
1287 root_save_nestlevel = NewGUCNestLevel();
1289
1290 /* Add any requested comment */
1291 if (stmt->idxcomment != NULL)
1292 CreateComments(indexRelationId, RelationRelationId, 0,
1293 stmt->idxcomment);
1294
1295 if (partitioned)
1296 {
1297 PartitionDesc partdesc;
1298
1299 /*
1300 * Unless caller specified to skip this step (via ONLY), process each
1301 * partition to make sure they all contain a corresponding index.
1302 *
1303 * If we're called internally (no stmt->relation), recurse always.
1304 */
1305 partdesc = RelationGetPartitionDesc(rel, true);
1306 if ((!stmt->relation || stmt->relation->inh) && partdesc->nparts > 0)
1307 {
1308 int nparts = partdesc->nparts;
1309 Oid *part_oids = palloc_array(Oid, nparts);
1310 bool invalidate_parent = false;
1311 Relation parentIndex;
1312 TupleDesc parentDesc;
1313
1314 /*
1315 * Report the total number of partitions at the start of the
1316 * command; don't update it when being called recursively.
1317 */
1318 if (!OidIsValid(parentIndexId))
1319 {
1320 /*
1321 * When called by ProcessUtilitySlow, the number of partitions
1322 * is passed in as an optimization; but other callers pass -1
1323 * since they don't have the value handy. This should count
1324 * partitions the same way, ie one less than the number of
1325 * relations find_all_inheritors reports.
1326 *
1327 * We assume we needn't ask find_all_inheritors to take locks,
1328 * because that should have happened already for all callers.
1329 * Even if it did not, this is safe as long as we don't try to
1330 * touch the partitions here; the worst consequence would be a
1331 * bogus progress-reporting total.
1332 */
1333 if (total_parts < 0)
1334 {
1335 List *children = find_all_inheritors(tableId, NoLock, NULL);
1336
1337 total_parts = list_length(children) - 1;
1338 list_free(children);
1339 }
1340
1342 total_parts);
1343 }
1344
1345 /* Make a local copy of partdesc->oids[], just for safety */
1346 memcpy(part_oids, partdesc->oids, sizeof(Oid) * nparts);
1347
1348 /*
1349 * We'll need an IndexInfo describing the parent index. The one
1350 * built above is almost good enough, but not quite, because (for
1351 * example) its predicate expression if any hasn't been through
1352 * expression preprocessing. The most reliable way to get an
1353 * IndexInfo that will match those for child indexes is to build
1354 * it the same way, using BuildIndexInfo().
1355 */
1356 parentIndex = index_open(indexRelationId, lockmode);
1357 indexInfo = BuildIndexInfo(parentIndex);
1358
1359 parentDesc = RelationGetDescr(rel);
1360
1361 /*
1362 * For each partition, scan all existing indexes; if one matches
1363 * our index definition and is not already attached to some other
1364 * parent index, attach it to the one we just created.
1365 *
1366 * If none matches, build a new index by calling ourselves
1367 * recursively with the same options (except for the index name).
1368 */
1369 for (int i = 0; i < nparts; i++)
1370 {
1371 Oid childRelid = part_oids[i];
1372 Relation childrel;
1373 Oid child_save_userid;
1374 int child_save_sec_context;
1375 int child_save_nestlevel;
1376 List *childidxs;
1377 ListCell *cell;
1378 AttrMap *attmap;
1379 bool found = false;
1380
1381 childrel = table_open(childRelid, lockmode);
1382
1383 GetUserIdAndSecContext(&child_save_userid,
1384 &child_save_sec_context);
1385 SetUserIdAndSecContext(childrel->rd_rel->relowner,
1386 child_save_sec_context | SECURITY_RESTRICTED_OPERATION);
1387 child_save_nestlevel = NewGUCNestLevel();
1389
1390 /*
1391 * Don't try to create indexes on foreign tables, though. Skip
1392 * those if a regular index, or fail if trying to create a
1393 * constraint index.
1394 */
1395 if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1396 {
1397 if (stmt->unique || stmt->primary)
1398 ereport(ERROR,
1399 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1400 errmsg("cannot create unique index on partitioned table \"%s\"",
1402 errdetail("Table \"%s\" contains partitions that are foreign tables.",
1404
1405 AtEOXact_GUC(false, child_save_nestlevel);
1406 SetUserIdAndSecContext(child_save_userid,
1407 child_save_sec_context);
1408 table_close(childrel, lockmode);
1409 continue;
1410 }
1411
1412 childidxs = RelationGetIndexList(childrel);
1413 attmap =
1415 parentDesc,
1416 false);
1417
1418 foreach(cell, childidxs)
1419 {
1420 Oid cldidxid = lfirst_oid(cell);
1421 Relation cldidx;
1422 IndexInfo *cldIdxInfo;
1423
1424 /* this index is already partition of another one */
1425 if (has_superclass(cldidxid))
1426 continue;
1427
1428 cldidx = index_open(cldidxid, lockmode);
1429 cldIdxInfo = BuildIndexInfo(cldidx);
1430 if (CompareIndexInfo(cldIdxInfo, indexInfo,
1431 cldidx->rd_indcollation,
1432 parentIndex->rd_indcollation,
1433 cldidx->rd_opfamily,
1434 parentIndex->rd_opfamily,
1435 attmap))
1436 {
1437 Oid cldConstrOid = InvalidOid;
1438
1439 /*
1440 * Found a match.
1441 *
1442 * If this index is being created in the parent
1443 * because of a constraint, then the child needs to
1444 * have a constraint also, so look for one. If there
1445 * is no such constraint, this index is no good, so
1446 * keep looking.
1447 */
1448 if (createdConstraintId != InvalidOid)
1449 {
1450 cldConstrOid =
1452 cldidxid);
1453 if (cldConstrOid == InvalidOid)
1454 {
1455 index_close(cldidx, lockmode);
1456 continue;
1457 }
1458 }
1459
1460 /* Attach index to parent and we're done. */
1461 IndexSetParentIndex(cldidx, indexRelationId);
1462 if (createdConstraintId != InvalidOid)
1463 ConstraintSetParentConstraint(cldConstrOid,
1464 createdConstraintId,
1465 childRelid);
1466
1467 if (!cldidx->rd_index->indisvalid)
1468 invalidate_parent = true;
1469
1470 found = true;
1471
1472 /*
1473 * Report this partition as processed. Note that if
1474 * the partition has children itself, we'd ideally
1475 * count the children and update the progress report
1476 * for all of them; but that seems unduly expensive.
1477 * Instead, the progress report will act like all such
1478 * indirect children were processed in zero time at
1479 * the end of the command.
1480 */
1482
1483 /* keep lock till commit */
1484 index_close(cldidx, NoLock);
1485 break;
1486 }
1487
1488 index_close(cldidx, lockmode);
1489 }
1490
1491 list_free(childidxs);
1492 AtEOXact_GUC(false, child_save_nestlevel);
1493 SetUserIdAndSecContext(child_save_userid,
1494 child_save_sec_context);
1495 table_close(childrel, NoLock);
1496
1497 /*
1498 * If no matching index was found, create our own.
1499 */
1500 if (!found)
1501 {
1502 IndexStmt *childStmt;
1503 ObjectAddress childAddr;
1504
1505 /*
1506 * Build an IndexStmt describing the desired child index
1507 * in the same way that we do during ATTACH PARTITION.
1508 * Notably, we rely on generateClonedIndexStmt to produce
1509 * a search-path-independent representation, which the
1510 * original IndexStmt might not be.
1511 */
1512 childStmt = generateClonedIndexStmt(NULL,
1513 parentIndex,
1514 attmap,
1515 NULL);
1516
1517 /*
1518 * Recurse as the starting user ID. Callee will use that
1519 * for permission checks, then switch again.
1520 */
1521 Assert(GetUserId() == child_save_userid);
1522 SetUserIdAndSecContext(root_save_userid,
1523 root_save_sec_context);
1524 childAddr =
1525 DefineIndex(NULL, /* original pstate not applicable */
1526 childRelid, childStmt,
1527 InvalidOid, /* no predefined OID */
1528 indexRelationId, /* this is our child */
1529 createdConstraintId,
1530 -1,
1531 is_alter_table, check_rights,
1532 check_not_in_use,
1533 skip_build, quiet);
1534 SetUserIdAndSecContext(child_save_userid,
1535 child_save_sec_context);
1536
1537 /*
1538 * Check if the index just created is valid or not, as it
1539 * could be possible that it has been switched as invalid
1540 * when recursing across multiple partition levels.
1541 */
1542 if (!get_index_isvalid(childAddr.objectId))
1543 invalidate_parent = true;
1544 }
1545
1546 free_attrmap(attmap);
1547 }
1548
1549 index_close(parentIndex, lockmode);
1550
1551 /*
1552 * The pg_index row we inserted for this index was marked
1553 * indisvalid=true. But if we attached an existing index that is
1554 * invalid, this is incorrect, so update our row to invalid too.
1555 */
1556 if (invalidate_parent)
1557 {
1558 Relation pg_index = table_open(IndexRelationId, RowExclusiveLock);
1559 HeapTuple tup,
1560 newtup;
1561
1562 tup = SearchSysCache1(INDEXRELID,
1563 ObjectIdGetDatum(indexRelationId));
1564 if (!HeapTupleIsValid(tup))
1565 elog(ERROR, "cache lookup failed for index %u",
1566 indexRelationId);
1567 newtup = heap_copytuple(tup);
1568 ((Form_pg_index) GETSTRUCT(newtup))->indisvalid = false;
1569 CatalogTupleUpdate(pg_index, &tup->t_self, newtup);
1570 ReleaseSysCache(tup);
1571 table_close(pg_index, RowExclusiveLock);
1572 heap_freetuple(newtup);
1573
1574 /*
1575 * CCI here to make this update visible, in case this recurses
1576 * across multiple partition levels.
1577 */
1579 }
1580 }
1581
1582 /*
1583 * Indexes on partitioned tables are not themselves built, so we're
1584 * done here.
1585 */
1586 AtEOXact_GUC(false, root_save_nestlevel);
1587 SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
1588 table_close(rel, NoLock);
1589 if (!OidIsValid(parentIndexId))
1591 else
1592 {
1593 /* Update progress for an intermediate partitioned index itself */
1595 }
1596
1597 return address;
1598 }
1599
1600 AtEOXact_GUC(false, root_save_nestlevel);
1601 SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
1602
1603 if (!concurrent)
1604 {
1605 /* Close the heap and we're done, in the non-concurrent case */
1606 table_close(rel, NoLock);
1607
1608 /*
1609 * If this is the top-level index, the command is done overall;
1610 * otherwise, increment progress to report one child index is done.
1611 */
1612 if (!OidIsValid(parentIndexId))
1614 else
1616
1617 return address;
1618 }
1619
1620 /* save lockrelid and locktag for below, then close rel */
1621 heaprelid = rel->rd_lockInfo.lockRelId;
1622 SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
1623 table_close(rel, NoLock);
1624
1625 /*
1626 * For a concurrent build, it's important to make the catalog entries
1627 * visible to other transactions before we start to build the index. That
1628 * will prevent them from making incompatible HOT updates. The new index
1629 * will be marked not indisready and not indisvalid, so that no one else
1630 * tries to either insert into it or use it for queries.
1631 *
1632 * We must commit our current transaction so that the index becomes
1633 * visible; then start another. Note that all the data structures we just
1634 * built are lost in the commit. The only data we keep past here are the
1635 * relation IDs.
1636 *
1637 * Before committing, get a session-level lock on the table, to ensure
1638 * that neither it nor the index can be dropped before we finish. This
1639 * cannot block, even if someone else is waiting for access, because we
1640 * already have the same lock within our transaction.
1641 *
1642 * Note: we don't currently bother with a session lock on the index,
1643 * because there are no operations that could change its state while we
1644 * hold lock on the parent table. This might need to change later.
1645 */
1647
1651
1652 /* Tell concurrent index builds to ignore us, if index qualifies */
1653 if (safe_index)
1655
1656 /*
1657 * The index is now visible, so we can report the OID. While on it,
1658 * include the report for the beginning of phase 2.
1659 */
1660 {
1661 const int progress_cols[] = {
1664 };
1665 const int64 progress_vals[] = {
1666 indexRelationId,
1668 };
1669
1670 pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
1671 }
1672
1673 /*
1674 * Phase 2 of concurrent index build (see comments for validate_index()
1675 * for an overview of how this works)
1676 *
1677 * Now we must wait until no running transaction could have the table open
1678 * with the old list of indexes. Use ShareLock to consider running
1679 * transactions that hold locks that permit writing to the table. Note we
1680 * do not need to worry about xacts that open the table for writing after
1681 * this point; they will see the new index when they open it.
1682 *
1683 * Note: the reason we use actual lock acquisition here, rather than just
1684 * checking the ProcArray and sleeping, is that deadlock is possible if
1685 * one of the transactions in question is blocked trying to acquire an
1686 * exclusive lock on our table. The lock code will detect deadlock and
1687 * error out properly.
1688 */
1689 WaitForLockers(heaplocktag, ShareLock, true);
1690
1691 /*
1692 * At this moment we are sure that there are no transactions with the
1693 * table open for write that don't have this new index in their list of
1694 * indexes. We have waited out all the existing transactions and any new
1695 * transaction will have the new index in its list, but the index is still
1696 * marked as "not-ready-for-inserts". The index is consulted while
1697 * deciding HOT-safety though. This arrangement ensures that no new HOT
1698 * chains can be created where the new tuple and the old tuple in the
1699 * chain have different index keys.
1700 *
1701 * We now take a new snapshot, and build the index using all tuples that
1702 * are visible in this snapshot. We can be sure that any HOT updates to
1703 * these tuples will be compatible with the index, since any updates made
1704 * by transactions that didn't know about the index are now committed or
1705 * rolled back. Thus, each visible tuple is either the end of its
1706 * HOT-chain or the extension of the chain is HOT-safe for this index.
1707 */
1708
1709 /* Set ActiveSnapshot since functions in the indexes may need it */
1711
1712 /* Perform concurrent build of index */
1713 index_concurrently_build(tableId, indexRelationId);
1714
1715 /* we can do away with our snapshot */
1717
1718 /*
1719 * Commit this transaction to make the indisready update visible.
1720 */
1723
1724 /* Tell concurrent index builds to ignore us, if index qualifies */
1725 if (safe_index)
1727
1728 /*
1729 * Phase 3 of concurrent index build
1730 *
1731 * We once again wait until no transaction can have the table open with
1732 * the index marked as read-only for updates.
1733 */
1736 WaitForLockers(heaplocktag, ShareLock, true);
1737
1738 /*
1739 * Now take the "reference snapshot" that will be used by validate_index()
1740 * to filter candidate tuples. Beware! There might still be snapshots in
1741 * use that treat some transaction as in-progress that our reference
1742 * snapshot treats as committed. If such a recently-committed transaction
1743 * deleted tuples in the table, we will not include them in the index; yet
1744 * those transactions which see the deleting one as still-in-progress will
1745 * expect such tuples to be there once we mark the index as valid.
1746 *
1747 * We solve this by waiting for all endangered transactions to exit before
1748 * we mark the index as valid.
1749 *
1750 * We also set ActiveSnapshot to this snap, since functions in indexes may
1751 * need a snapshot.
1752 */
1754 PushActiveSnapshot(snapshot);
1755
1756 /*
1757 * Scan the index and the heap, insert any missing index entries.
1758 */
1759 validate_index(tableId, indexRelationId, snapshot);
1760
1761 /*
1762 * Drop the reference snapshot. We must do this before waiting out other
1763 * snapshot holders, else we will deadlock against other processes also
1764 * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
1765 * they must wait for. But first, save the snapshot's xmin to use as
1766 * limitXmin for GetCurrentVirtualXIDs().
1767 */
1768 limitXmin = snapshot->xmin;
1769
1771 UnregisterSnapshot(snapshot);
1772
1773 /*
1774 * The snapshot subsystem could still contain registered snapshots that
1775 * are holding back our process's advertised xmin; in particular, if
1776 * default_transaction_isolation = serializable, there is a transaction
1777 * snapshot that is still active. The CatalogSnapshot is likewise a
1778 * hazard. To ensure no deadlocks, we must commit and start yet another
1779 * transaction, and do our wait before any snapshot has been taken in it.
1780 */
1783
1784 /* Tell concurrent index builds to ignore us, if index qualifies */
1785 if (safe_index)
1787
1788 /* We should now definitely not be advertising any xmin. */
1790
1791 /*
1792 * The index is now valid in the sense that it contains all currently
1793 * interesting tuples. But since it might not contain tuples deleted just
1794 * before the reference snap was taken, we have to wait out any
1795 * transactions that might have older snapshots.
1796 */
1797 INJECTION_POINT("define-index-before-set-valid", NULL);
1800 WaitForOlderSnapshots(limitXmin, true);
1801
1802 /*
1803 * Updating pg_index might involve TOAST table access, so ensure we have a
1804 * valid snapshot.
1805 */
1807
1808 /*
1809 * Index can now be marked valid -- update its pg_index entry
1810 */
1812
1814
1815 /*
1816 * The pg_index update will cause backends (including this one) to update
1817 * relcache entries for the index itself, but we should also send a
1818 * relcache inval on the parent table to force replanning of cached plans.
1819 * Otherwise existing sessions might fail to use the new index where it
1820 * would be useful. (Note that our earlier commits did not create reasons
1821 * to replan; so relcache flush on the index itself was sufficient.)
1822 */
1824
1825 /*
1826 * Last thing to do is release the session-level lock on the parent table.
1827 */
1829
1831
1832 return address;
1833}
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2654
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3836
bytea *(* amoptions_function)(Datum reloptions, bool validate)
Definition: amapi.h:165
char * get_am_name(Oid amOid)
Definition: amcmds.c:192
void free_attrmap(AttrMap *map)
Definition: attmap.c:56
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:175
int16 AttrNumber
Definition: attnum.h:21
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1472
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1426
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1143
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
void pgstat_progress_incr_param(int index, int64 incr)
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
void pgstat_progress_end_command(void)
@ PROGRESS_COMMAND_CREATE_INDEX
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1305
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
#define NameStr(name)
Definition: c.h:765
uint16 bits16
Definition: c.h:560
int64_t int64
Definition: c.h:549
uint32 TransactionId
Definition: c.h:671
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:143
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
#define DEBUG1
Definition: elog.h:30
#define NOTICE
Definition: elog.h:35
bool allowSystemTableMods
Definition: globals.c:130
Oid MyDatabaseTableSpace
Definition: globals.c:96
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:3216
@ GUC_ACTION_SAVE
Definition: guc.h:205
@ PGC_S_SESSION
Definition: guc.h:126
@ PGC_USERSET
Definition: guc.h:79
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:778
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
#define stmt
Definition: indent_codes.h:59
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3348
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, RelFileNumber relFileNumber, IndexInfo *indexInfo, const List *indexColNames, Oid accessMethodId, Oid tableSpaceId, const Oid *collationIds, const Oid *opclassIds, const Datum *opclassOptions, const int16 *coloptions, const NullableDatum *stattargets, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
Definition: index.c:724
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3501
bool CompareIndexInfo(const IndexInfo *info1, const IndexInfo *info2, const Oid *collations1, const Oid *collations2, const Oid *opfamilies1, const Oid *opfamilies2, const AttrMap *attmap)
Definition: index.c:2535
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2426
void index_check_primary_key(Relation heapRel, const IndexInfo *indexInfo, bool is_alter_table, const IndexStmt *stmt)
Definition: index.c:202
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1483
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:61
#define INDEX_CREATE_IF_NOT_EXISTS
Definition: index.h:65
#define INDEX_CREATE_PARTITIONED
Definition: index.h:66
#define INDEX_CREATE_INVALID
Definition: index.h:67
#define INDEX_CONSTR_CREATE_WITHOUT_OVERLAPS
Definition: index.h:96
#define INDEX_CREATE_ADD_CONSTRAINT
Definition: index.h:62
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:63
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:92
@ INDEX_CREATE_SET_VALID
Definition: index.h:27
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:93
#define INDEX_CREATE_CONCURRENT
Definition: index.h:64
static void set_indexsafe_procflags(void)
Definition: indexcmds.c:4637
ObjectAddress DefineIndex(ParseState *pstate, Oid tableId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, int total_parts, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:544
void IndexSetParentIndex(Relation partitionIdx, Oid parentOid)
Definition: indexcmds.c:4467
void WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
Definition: indexcmds.c:435
static void CheckPredicate(Expr *predicate)
Definition: indexcmds.c:1848
static List * ChooseIndexColumnNames(const List *indexElems)
Definition: indexcmds.c:2785
static char * ChooseIndexName(const char *tabname, Oid namespaceId, const List *colnames, const List *exclusionOpNames, bool primary, bool isconstraint)
Definition: indexcmds.c:2696
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition: indexing.c:313
#define INJECTION_POINT(name, arg)
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1691
int j
Definition: isn.c:78
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:598
void list_free(List *list)
Definition: list.c:1546
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:391
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:989
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:404
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:183
int LOCKMODE
Definition: lockdefs.h:26
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define ShareLock
Definition: lockdefs.h:40
#define RowExclusiveLock
Definition: lockdefs.h:38
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2228
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3728
Oid get_opfamily_member_for_cmptype(Oid opfamily, Oid lefttype, Oid righttype, CompareType cmptype)
Definition: lsyscache.c:197
bool get_opclass_opfamily_and_input_type(Oid opclass, Oid *opfamily, Oid *opcintype)
Definition: lsyscache.c:1337
char * get_opname(Oid opno)
Definition: lsyscache.c:1460
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:168
Oid get_opfamily_method(Oid opfid)
Definition: lsyscache.c:1386
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3516
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:810
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:477
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:319
Oid GetUserId(void)
Definition: miscinit.c:469
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ PARTITION_STRATEGY_HASH
Definition: parsenodes.h:903
@ OBJECT_SCHEMA
Definition: parsenodes.h:2388
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2394
#define ACL_CREATE
Definition: parsenodes.h:85
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:51
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:71
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
Oid get_relation_idx_constraint_oid(Oid relationId, Oid indexId)
void ConstraintSetParentConstraint(Oid childConstrId, Oid parentConstrId, Oid childTableId)
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:255
bool has_superclass(Oid relationId)
Definition: pg_inherits.c:377
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define PROGRESS_CREATEIDX_PARTITIONS_DONE
Definition: progress.h:109
#define PROGRESS_CREATEIDX_PHASE_WAIT_1
Definition: progress.h:113
#define PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY
Definition: progress.h:131
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:103
#define PROGRESS_CREATEIDX_PHASE_WAIT_3
Definition: progress.h:119
#define PROGRESS_CREATEIDX_COMMAND_CREATE
Definition: progress.h:130
#define PROGRESS_CREATEIDX_PHASE_WAIT_2
Definition: progress.h:115
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:104
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:102
#define PROGRESS_CREATEIDX_PARTITIONS_TOTAL
Definition: progress.h:108
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:101
#define RelationGetDescr(relation)
Definition: rel.h:541
#define RelationGetRelationName(relation)
Definition: rel.h:549
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:668
#define RelationGetNamespace(relation)
Definition: rel.h:556
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4831
bytea * index_reloptions(amoptions_function amoptions, Datum reloptions, bool validate)
Definition: reloptions.c:2101
#define RelFileNumberIsValid(relnumber)
Definition: relpath.h:27
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:272
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:866
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:682
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:824
void PopActiveSnapshot(void)
Definition: snapmgr.c:775
PGPROC * MyProc
Definition: proc.c:67
#define HTEqualStrategyNumber
Definition: stratnum.h:41
Definition: attmap.h:35
ItemPointerData t_self
Definition: htup.h:65
amoptions_function amoptions
Definition: amapi.h:304
amgettuple_function amgettuple
Definition: amapi.h:311
bool amcanunique
Definition: amapi.h:258
bool amcanmulticol
Definition: amapi.h:260
bool amcaninclude
Definition: amapi.h:278
int ii_NumIndexAttrs
Definition: execnodes.h:167
List * ii_Predicate
Definition: execnodes.h:183
Definition: lock.h:167
LockRelId lockRelId
Definition: rel.h:46
Definition: rel.h:39
Oid relId
Definition: rel.h:40
Oid dbId
Definition: rel.h:41
TransactionId xmin
Definition: proc.h:194
LockInfoData rd_lockInfo
Definition: rel.h:114
Form_pg_index rd_index
Definition: rel.h:192
Oid * rd_opfamily
Definition: rel.h:207
Oid * rd_indcollation
Definition: rel.h:217
Form_pg_class rd_rel
Definition: rel.h:111
TransactionId xmin
Definition: snapshot.h:153
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:4414
#define InvalidTransactionId
Definition: transam.h:31
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:296
void CommandCounterIncrement(void)
Definition: xact.c:1101
void StartTransactionCommand(void)
Definition: xact.c:3080
void CommitTransactionCommand(void)
Definition: xact.c:3178

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, IndexAmRoutine::amcaninclude, IndexAmRoutine::amcanmulticol, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanunique, IndexAmRoutine::amgettuple, IndexAmRoutine::amoptions, IndexAmRoutine::amsummarizing, Assert(), AtEOXact_GUC(), bms_is_member(), bms_next_member(), BTEqualStrategyNumber, build_attrmap_by_name(), BuildIndexInfo(), CacheInvalidateRelcacheByRelid(), CatalogTupleUpdate(), CheckPredicate(), CheckTableNotInUse(), ChooseIndexColumnNames(), ChooseIndexName(), CommandCounterIncrement(), CommitTransactionCommand(), COMPARE_EQ, CompareIndexInfo(), ComputeIndexAttrs(), ConstraintSetParentConstraint(), CreateComments(), LockRelId::dbId, DEBUG1, DefineIndex(), elog, ereport, errcode(), errdetail(), errdetail_relkind_not_supported(), errmsg(), errmsg_internal(), ERROR, find_all_inheritors(), FirstLowInvalidHeapAttributeNumber, format_type_be(), free_attrmap(), generateClonedIndexStmt(), get_am_name(), get_index_isvalid(), get_namespace_name(), get_opclass_opfamily_and_input_type(), get_opfamily_member(), get_opfamily_member_for_cmptype(), get_opfamily_method(), get_opfamily_name(), get_opname(), get_rel_persistence(), get_relation_idx_constraint_oid(), get_tablespace_name(), get_tablespace_oid(), GetDefaultTablespace(), GetIndexAmRoutine(), GETSTRUCT(), GetTransactionSnapshot(), GetUserId(), GetUserIdAndSecContext(), GUC_ACTION_SAVE, has_superclass(), heap_copytuple(), heap_freetuple(), HeapTupleIsValid, HTEqualStrategyNumber, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_Predicate, index_check_primary_key(), index_close(), index_concurrently_build(), INDEX_CONSTR_CREATE_DEFERRABLE, INDEX_CONSTR_CREATE_INIT_DEFERRED, INDEX_CONSTR_CREATE_WITHOUT_OVERLAPS, index_create(), INDEX_CREATE_ADD_CONSTRAINT, INDEX_CREATE_CONCURRENT, INDEX_CREATE_IF_NOT_EXISTS, INDEX_CREATE_INVALID, INDEX_CREATE_IS_PRIMARY, INDEX_CREATE_PARTITIONED, INDEX_CREATE_SET_VALID, INDEX_CREATE_SKIP_BUILD, INDEX_MAX_KEYS, index_open(), index_reloptions(), index_set_state_flags(), IndexSetParentIndex(), INJECTION_POINT, InvalidOid, InvalidTransactionId, IsBootstrapProcessingMode, j, sort-test::key, lfirst_oid, list_concat_copy(), list_free(), list_length(), LockRelationIdForSession(), LockInfoData::lockRelId, make_ands_implicit(), makeIndexInfo(), MyDatabaseTableSpace, MyProc, NameStr, NewGUCNestLevel(), NIL, NoLock, NOTICE, PartitionDescData::nparts, object_aclcheck(), OBJECT_SCHEMA, OBJECT_TABLESPACE, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum(), OidIsValid, PartitionDescData::oids, palloc_array, PARTITION_STRATEGY_HASH, PGC_S_SESSION, PGC_USERSET, pgstat_progress_end_command(), pgstat_progress_incr_param(), pgstat_progress_start_command(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PointerGetDatum(), PopActiveSnapshot(), PROGRESS_COMMAND_CREATE_INDEX, PROGRESS_CREATEIDX_ACCESS_METHOD_OID, PROGRESS_CREATEIDX_COMMAND, PROGRESS_CREATEIDX_COMMAND_CREATE, PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY, PROGRESS_CREATEIDX_INDEX_OID, PROGRESS_CREATEIDX_PARTITIONS_DONE, PROGRESS_CREATEIDX_PARTITIONS_TOTAL, PROGRESS_CREATEIDX_PHASE, PROGRESS_CREATEIDX_PHASE_WAIT_1, PROGRESS_CREATEIDX_PHASE_WAIT_2, PROGRESS_CREATEIDX_PHASE_WAIT_3, pull_varattnos(), PushActiveSnapshot(), RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_lockInfo, RelationData::rd_opfamily, RelationData::rd_rel, RegisterSnapshot(), RELATION_IS_OTHER_TEMP, RelationGetDescr, RelationGetIndexList(), RelationGetNamespace, RelationGetPartitionDesc(), RelationGetPartitionKey(), RelationGetRelationName, ReleaseSysCache(), RelFileNumberIsValid, LockRelId::relId, RestrictSearchPath(), RowExclusiveLock, SearchSysCache1(), SECURITY_RESTRICTED_OPERATION, set_config_option(), set_indexsafe_procflags(), SET_LOCKTAG_RELATION, SetUserIdAndSecContext(), ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), stmt, HeapTupleData::t_self, table_close(), table_open(), transformRelOptions(), TupleDescAttr(), UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockers(), WaitForOlderSnapshots(), PGPROC::xmin, and SnapshotData::xmin.

Referenced by ATExecAddIndex(), AttachPartitionEnsureIndexes(), DefineIndex(), DefineRelation(), and ProcessUtilitySlow().

◆ ExecReindex()

void ExecReindex ( ParseState pstate,
const ReindexStmt stmt,
bool  isTopLevel 
)

Definition at line 2846 of file indexcmds.c.

2847{
2848 ReindexParams params = {0};
2849 ListCell *lc;
2850 bool concurrently = false;
2851 bool verbose = false;
2852 char *tablespacename = NULL;
2853
2854 /* Parse option list */
2855 foreach(lc, stmt->params)
2856 {
2857 DefElem *opt = (DefElem *) lfirst(lc);
2858
2859 if (strcmp(opt->defname, "verbose") == 0)
2860 verbose = defGetBoolean(opt);
2861 else if (strcmp(opt->defname, "concurrently") == 0)
2862 concurrently = defGetBoolean(opt);
2863 else if (strcmp(opt->defname, "tablespace") == 0)
2864 tablespacename = defGetString(opt);
2865 else
2866 ereport(ERROR,
2867 (errcode(ERRCODE_SYNTAX_ERROR),
2868 errmsg("unrecognized %s option \"%s\"",
2869 "REINDEX", opt->defname),
2870 parser_errposition(pstate, opt->location)));
2871 }
2872
2873 if (concurrently)
2874 PreventInTransactionBlock(isTopLevel,
2875 "REINDEX CONCURRENTLY");
2876
2877 params.options =
2878 (verbose ? REINDEXOPT_VERBOSE : 0) |
2879 (concurrently ? REINDEXOPT_CONCURRENTLY : 0);
2880
2881 /*
2882 * Assign the tablespace OID to move indexes to, with InvalidOid to do
2883 * nothing.
2884 */
2885 if (tablespacename != NULL)
2886 {
2887 params.tablespaceOid = get_tablespace_oid(tablespacename, false);
2888
2889 /* Check permissions except when moving to database's default */
2890 if (OidIsValid(params.tablespaceOid) &&
2892 {
2893 AclResult aclresult;
2894
2895 aclresult = object_aclcheck(TableSpaceRelationId, params.tablespaceOid,
2897 if (aclresult != ACLCHECK_OK)
2900 }
2901 }
2902 else
2903 params.tablespaceOid = InvalidOid;
2904
2905 switch (stmt->kind)
2906 {
2908 ReindexIndex(stmt, &params, isTopLevel);
2909 break;
2911 ReindexTable(stmt, &params, isTopLevel);
2912 break;
2916
2917 /*
2918 * This cannot run inside a user transaction block; if we were
2919 * inside a transaction, then its commit- and
2920 * start-transaction-command calls would not have the intended
2921 * effect!
2922 */
2923 PreventInTransactionBlock(isTopLevel,
2924 (stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" :
2925 (stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" :
2926 "REINDEX DATABASE");
2927 ReindexMultipleTables(stmt, &params);
2928 break;
2929 default:
2930 elog(ERROR, "unrecognized object type: %d",
2931 (int) stmt->kind);
2932 break;
2933 }
2934}
char * defGetString(DefElem *def)
Definition: define.c:35
bool defGetBoolean(DefElem *def)
Definition: define.c:94
int verbose
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44
#define REINDEXOPT_VERBOSE
Definition: index.h:41
static void ReindexIndex(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2941
static void ReindexMultipleTables(const ReindexStmt *stmt, const ReindexParams *params)
Definition: indexcmds.c:3130
static Oid ReindexTable(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:3071
@ REINDEX_OBJECT_DATABASE
Definition: parsenodes.h:4137
@ REINDEX_OBJECT_INDEX
Definition: parsenodes.h:4133
@ REINDEX_OBJECT_SCHEMA
Definition: parsenodes.h:4135
@ REINDEX_OBJECT_SYSTEM
Definition: parsenodes.h:4136
@ REINDEX_OBJECT_TABLE
Definition: parsenodes.h:4134
char * defname
Definition: parsenodes.h:844
ParseLoc location
Definition: parsenodes.h:848
Oid tablespaceOid
Definition: index.h:36
bits32 options
Definition: index.h:35
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3669

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, defGetBoolean(), defGetString(), DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, get_tablespace_name(), get_tablespace_oid(), GetUserId(), InvalidOid, lfirst, DefElem::location, MyDatabaseTableSpace, object_aclcheck(), OBJECT_TABLESPACE, OidIsValid, ReindexParams::options, parser_errposition(), PreventInTransactionBlock(), REINDEX_OBJECT_DATABASE, REINDEX_OBJECT_INDEX, REINDEX_OBJECT_SCHEMA, REINDEX_OBJECT_SYSTEM, REINDEX_OBJECT_TABLE, ReindexIndex(), ReindexMultipleTables(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_VERBOSE, ReindexTable(), stmt, ReindexParams::tablespaceOid, and verbose.

Referenced by ProcessUtilitySlow().

◆ GetDefaultOpClass()

Oid GetDefaultOpClass ( Oid  type_id,
Oid  am_id 
)

Definition at line 2365 of file indexcmds.c.

2366{
2367 Oid result = InvalidOid;
2368 int nexact = 0;
2369 int ncompatible = 0;
2370 int ncompatiblepreferred = 0;
2371 Relation rel;
2372 ScanKeyData skey[1];
2373 SysScanDesc scan;
2374 HeapTuple tup;
2375 TYPCATEGORY tcategory;
2376
2377 /* If it's a domain, look at the base type instead */
2378 type_id = getBaseType(type_id);
2379
2380 tcategory = TypeCategory(type_id);
2381
2382 /*
2383 * We scan through all the opclasses available for the access method,
2384 * looking for one that is marked default and matches the target type
2385 * (either exactly or binary-compatibly, but prefer an exact match).
2386 *
2387 * We could find more than one binary-compatible match. If just one is
2388 * for a preferred type, use that one; otherwise we fail, forcing the user
2389 * to specify which one he wants. (The preferred-type special case is a
2390 * kluge for varchar: it's binary-compatible to both text and bpchar, so
2391 * we need a tiebreaker.) If we find more than one exact match, then
2392 * someone put bogus entries in pg_opclass.
2393 */
2394 rel = table_open(OperatorClassRelationId, AccessShareLock);
2395
2396 ScanKeyInit(&skey[0],
2397 Anum_pg_opclass_opcmethod,
2398 BTEqualStrategyNumber, F_OIDEQ,
2399 ObjectIdGetDatum(am_id));
2400
2401 scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
2402 NULL, 1, skey);
2403
2404 while (HeapTupleIsValid(tup = systable_getnext(scan)))
2405 {
2406 Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
2407
2408 /* ignore altogether if not a default opclass */
2409 if (!opclass->opcdefault)
2410 continue;
2411 if (opclass->opcintype == type_id)
2412 {
2413 nexact++;
2414 result = opclass->oid;
2415 }
2416 else if (nexact == 0 &&
2417 IsBinaryCoercible(type_id, opclass->opcintype))
2418 {
2419 if (IsPreferredType(tcategory, opclass->opcintype))
2420 {
2421 ncompatiblepreferred++;
2422 result = opclass->oid;
2423 }
2424 else if (ncompatiblepreferred == 0)
2425 {
2426 ncompatible++;
2427 result = opclass->oid;
2428 }
2429 }
2430 }
2431
2432 systable_endscan(scan);
2433
2435
2436 /* raise error if pg_opclass contains inconsistent data */
2437 if (nexact > 1)
2438 ereport(ERROR,
2440 errmsg("there are multiple default operator classes for data type %s",
2441 format_type_be(type_id))));
2442
2443 if (nexact == 1 ||
2444 ncompatiblepreferred == 1 ||
2445 (ncompatiblepreferred == 0 && ncompatible == 1))
2446 return result;
2447
2448 return InvalidOid;
2449}
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2671
TYPCATEGORY TypeCategory(Oid type)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
bool IsPreferredType(TYPCATEGORY category, Oid type)
char TYPCATEGORY
Definition: parse_coerce.h:21
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30

References AccessShareLock, BTEqualStrategyNumber, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, format_type_be(), getBaseType(), GETSTRUCT(), HeapTupleIsValid, InvalidOid, IsBinaryCoercible(), IsPreferredType(), ObjectIdGetDatum(), ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), and TypeCategory().

Referenced by ComputePartitionAttrs(), findRangeSubOpclass(), get_opclass(), get_opclass_name(), lookup_type_cache(), ResolveOpClass(), and transformIndexConstraint().

◆ GetOperatorFromCompareType()

void GetOperatorFromCompareType ( Oid  opclass,
Oid  rhstype,
CompareType  cmptype,
Oid opid,
StrategyNumber strat 
)

Definition at line 2467 of file indexcmds.c.

2469{
2470 Oid amid;
2471 Oid opfamily;
2472 Oid opcintype;
2473
2474 Assert(cmptype == COMPARE_EQ || cmptype == COMPARE_OVERLAP || cmptype == COMPARE_CONTAINED_BY);
2475
2476 /*
2477 * Use the opclass to get the opfamily, opcintype, and access method. If
2478 * any of this fails, quit early.
2479 */
2480 if (!get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype))
2481 elog(ERROR, "cache lookup failed for opclass %u", opclass);
2482
2483 amid = get_opclass_method(opclass);
2484
2485 /*
2486 * Ask the index AM to translate to its internal stratnum
2487 */
2488 *strat = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
2489 if (*strat == InvalidStrategy)
2490 ereport(ERROR,
2491 errcode(ERRCODE_UNDEFINED_OBJECT),
2492 cmptype == COMPARE_EQ ? errmsg("could not identify an equality operator for type %s", format_type_be(opcintype)) :
2493 cmptype == COMPARE_OVERLAP ? errmsg("could not identify an overlaps operator for type %s", format_type_be(opcintype)) :
2494 cmptype == COMPARE_CONTAINED_BY ? errmsg("could not identify a contained-by operator for type %s", format_type_be(opcintype)) : 0,
2495 errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".",
2496 cmptype, get_opfamily_name(opfamily, false), get_am_name(amid)));
2497
2498 /*
2499 * We parameterize rhstype so foreign keys can ask for a <@ operator whose
2500 * rhs matches the aggregate function. For example range_agg returns
2501 * anymultirange.
2502 */
2503 if (!OidIsValid(rhstype))
2504 rhstype = opcintype;
2505 *opid = get_opfamily_member(opfamily, opcintype, rhstype, *strat);
2506
2507 if (!OidIsValid(*opid))
2508 ereport(ERROR,
2509 errcode(ERRCODE_UNDEFINED_OBJECT),
2510 cmptype == COMPARE_EQ ? errmsg("could not identify an equality operator for type %s", format_type_be(opcintype)) :
2511 cmptype == COMPARE_OVERLAP ? errmsg("could not identify an overlaps operator for type %s", format_type_be(opcintype)) :
2512 cmptype == COMPARE_CONTAINED_BY ? errmsg("could not identify a contained-by operator for type %s", format_type_be(opcintype)) : 0,
2513 errdetail("There is no suitable operator in operator family \"%s\" for access method \"%s\".",
2514 get_opfamily_name(opfamily, false), get_am_name(amid)));
2515}
StrategyNumber IndexAmTranslateCompareType(CompareType cmptype, Oid amoid, Oid opfamily, bool missing_ok)
Definition: amapi.c:161
@ COMPARE_CONTAINED_BY
Definition: cmptype.h:41
Oid get_opclass_method(Oid opclass)
Definition: lsyscache.c:1362
#define InvalidStrategy
Definition: stratnum.h:24

References Assert(), COMPARE_CONTAINED_BY, COMPARE_EQ, COMPARE_OVERLAP, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, format_type_be(), get_am_name(), get_opclass_method(), get_opclass_opfamily_and_input_type(), get_opfamily_member(), get_opfamily_name(), IndexAmTranslateCompareType(), InvalidStrategy, and OidIsValid.

Referenced by ComputeIndexAttrs(), and FindFKPeriodOpers().

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  partitionIdx,
Oid  parentOid 
)

Definition at line 4467 of file indexcmds.c.

4468{
4469 Relation pg_inherits;
4470 ScanKeyData key[2];
4471 SysScanDesc scan;
4472 Oid partRelid = RelationGetRelid(partitionIdx);
4473 HeapTuple tuple;
4474 bool fix_dependencies;
4475
4476 /* Make sure this is an index */
4477 Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
4478 partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
4479
4480 /*
4481 * Scan pg_inherits for rows linking our index to some parent.
4482 */
4483 pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
4484 ScanKeyInit(&key[0],
4485 Anum_pg_inherits_inhrelid,
4486 BTEqualStrategyNumber, F_OIDEQ,
4487 ObjectIdGetDatum(partRelid));
4488 ScanKeyInit(&key[1],
4489 Anum_pg_inherits_inhseqno,
4490 BTEqualStrategyNumber, F_INT4EQ,
4491 Int32GetDatum(1));
4492 scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
4493 NULL, 2, key);
4494 tuple = systable_getnext(scan);
4495
4496 if (!HeapTupleIsValid(tuple))
4497 {
4498 if (parentOid == InvalidOid)
4499 {
4500 /*
4501 * No pg_inherits row, and no parent wanted: nothing to do in this
4502 * case.
4503 */
4504 fix_dependencies = false;
4505 }
4506 else
4507 {
4508 StoreSingleInheritance(partRelid, parentOid, 1);
4509 fix_dependencies = true;
4510 }
4511 }
4512 else
4513 {
4514 Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
4515
4516 if (parentOid == InvalidOid)
4517 {
4518 /*
4519 * There exists a pg_inherits row, which we want to clear; do so.
4520 */
4521 CatalogTupleDelete(pg_inherits, &tuple->t_self);
4522 fix_dependencies = true;
4523 }
4524 else
4525 {
4526 /*
4527 * A pg_inherits row exists. If it's the same we want, then we're
4528 * good; if it differs, that amounts to a corrupt catalog and
4529 * should not happen.
4530 */
4531 if (inhForm->inhparent != parentOid)
4532 {
4533 /* unexpected: we should not get called in this case */
4534 elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
4535 inhForm->inhrelid, inhForm->inhparent);
4536 }
4537
4538 /* already in the right state */
4539 fix_dependencies = false;
4540 }
4541 }
4542
4543 /* done with pg_inherits */
4544 systable_endscan(scan);
4545 relation_close(pg_inherits, RowExclusiveLock);
4546
4547 /* set relhassubclass if an index partition has been added to the parent */
4548 if (OidIsValid(parentOid))
4549 {
4551 SetRelationHasSubclass(parentOid, true);
4552 }
4553
4554 /* set relispartition correctly on the partition */
4555 update_relispartition(partRelid, OidIsValid(parentOid));
4556
4557 if (fix_dependencies)
4558 {
4559 /*
4560 * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4561 * dependencies on the parent index and the table; if removing a
4562 * parent, delete PARTITION dependencies.
4563 */
4564 if (OidIsValid(parentOid))
4565 {
4566 ObjectAddress partIdx;
4567 ObjectAddress parentIdx;
4568 ObjectAddress partitionTbl;
4569
4570 ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4571 ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4572 ObjectAddressSet(partitionTbl, RelationRelationId,
4573 partitionIdx->rd_index->indrelid);
4574 recordDependencyOn(&partIdx, &parentIdx,
4576 recordDependencyOn(&partIdx, &partitionTbl,
4578 }
4579 else
4580 {
4581 deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4582 RelationRelationId,
4584 deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4585 RelationRelationId,
4587 }
4588
4589 /* make our updates visible */
4591 }
4592}
@ DEPENDENCY_PARTITION_PRI
Definition: dependency.h:36
@ DEPENDENCY_PARTITION_SEC
Definition: dependency.h:37
static void update_relispartition(Oid relationId, bool newval)
Definition: indexcmds.c:4599
void CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
Definition: indexing.c:365
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:107
static void fix_dependencies(ArchiveHandle *AH)
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:45
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:351
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:508
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:45
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
#define RelationGetRelid(relation)
Definition: rel.h:515
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3645

References Assert(), BTEqualStrategyNumber, CatalogTupleDelete(), CommandCounterIncrement(), deleteDependencyRecordsForClass(), DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, elog, ERROR, fix_dependencies(), GETSTRUCT(), HeapTupleIsValid, Int32GetDatum(), InvalidOid, sort-test::key, LockRelationOid(), ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, RelationData::rd_index, RelationData::rd_rel, recordDependencyOn(), relation_close(), relation_open(), RelationGetRelid, RowExclusiveLock, ScanKeyInit(), SetRelationHasSubclass(), ShareUpdateExclusiveLock, StoreSingleInheritance(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, and update_relispartition().

Referenced by ATExecAttachPartitionIdx(), AttachPartitionEnsureIndexes(), DefineIndex(), and DetachPartitionFinalize().

◆ makeObjectName()

char * makeObjectName ( const char *  name1,
const char *  name2,
const char *  label 
)

Definition at line 2540 of file indexcmds.c.

2541{
2542 char *name;
2543 int overhead = 0; /* chars needed for label and underscores */
2544 int availchars; /* chars available for name(s) */
2545 int name1chars; /* chars allocated to name1 */
2546 int name2chars; /* chars allocated to name2 */
2547 int ndx;
2548
2549 name1chars = strlen(name1);
2550 if (name2)
2551 {
2552 name2chars = strlen(name2);
2553 overhead++; /* allow for separating underscore */
2554 }
2555 else
2556 name2chars = 0;
2557 if (label)
2558 overhead += strlen(label) + 1;
2559
2560 availchars = NAMEDATALEN - 1 - overhead;
2561 Assert(availchars > 0); /* else caller chose a bad label */
2562
2563 /*
2564 * If we must truncate, preferentially truncate the longer name. This
2565 * logic could be expressed without a loop, but it's simple and obvious as
2566 * a loop.
2567 */
2568 while (name1chars + name2chars > availchars)
2569 {
2570 if (name1chars > name2chars)
2571 name1chars--;
2572 else
2573 name2chars--;
2574 }
2575
2576 name1chars = pg_mbcliplen(name1, name1chars, name1chars);
2577 if (name2)
2578 name2chars = pg_mbcliplen(name2, name2chars, name2chars);
2579
2580 /* Now construct the string using the chosen lengths */
2581 name = palloc(name1chars + name2chars + overhead + 1);
2582 memcpy(name, name1, name1chars);
2583 ndx = name1chars;
2584 if (name2)
2585 {
2586 name[ndx++] = '_';
2587 memcpy(name + ndx, name2, name2chars);
2588 ndx += name2chars;
2589 }
2590 if (label)
2591 {
2592 name[ndx++] = '_';
2593 strcpy(name + ndx, label);
2594 }
2595 else
2596 name[ndx] = '\0';
2597
2598 return name;
2599}
void * palloc(Size size)
Definition: mcxt.c:1387

References Assert(), label, name, NAMEDATALEN, palloc(), and pg_mbcliplen().

Referenced by ChooseConstraintName(), ChooseExtendedStatisticName(), ChooseRelationName(), and makeArrayTypeName().

◆ RangeVarCallbackForReindexIndex()

static void RangeVarCallbackForReindexIndex ( const RangeVar relation,
Oid  relId,
Oid  oldRelId,
void *  arg 
)
static

Definition at line 2995 of file indexcmds.c.

2997{
2998 char relkind;
3000 LOCKMODE table_lockmode;
3001 Oid table_oid;
3002 AclResult aclresult;
3003
3004 /*
3005 * Lock level here should match table lock in reindex_index() for
3006 * non-concurrent case and table locks used by index_concurrently_*() for
3007 * concurrent case.
3008 */
3009 table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ?
3011
3012 /*
3013 * If we previously locked some other index's heap, and the name we're
3014 * looking up no longer refers to that relation, release the now-useless
3015 * lock.
3016 */
3017 if (relId != oldRelId && OidIsValid(oldRelId))
3018 {
3019 UnlockRelationOid(state->locked_table_oid, table_lockmode);
3020 state->locked_table_oid = InvalidOid;
3021 }
3022
3023 /* If the relation does not exist, there's nothing more to do. */
3024 if (!OidIsValid(relId))
3025 return;
3026
3027 /* If the relation does exist, check whether it's an index. */
3028 relkind = get_rel_relkind(relId);
3029 if (relkind != RELKIND_INDEX &&
3030 relkind != RELKIND_PARTITIONED_INDEX)
3031 ereport(ERROR,
3032 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3033 errmsg("\"%s\" is not an index", relation->relname)));
3034
3035 /* Look up the index's table. */
3036 table_oid = IndexGetRelation(relId, false);
3037
3038 /*
3039 * In the unlikely event that, upon retry, we get the same index OID with
3040 * a different table OID, fail. RangeVarGetRelidExtended() will have
3041 * already locked the index in this case, and it won't retry again, so we
3042 * can't lock the newly discovered table OID without risking deadlock.
3043 * Also, while this corner case is indeed possible, it is extremely
3044 * unlikely to happen in practice, so it's probably not worth any more
3045 * effort than this.
3046 */
3047 if (relId == oldRelId && table_oid != state->locked_table_oid)
3048 ereport(ERROR,
3049 (errcode(ERRCODE_UNDEFINED_OBJECT),
3050 errmsg("index \"%s\" was concurrently dropped",
3051 relation->relname)));
3052
3053 /* Check permissions. */
3054 aclresult = pg_class_aclcheck(table_oid, GetUserId(), ACL_MAINTAIN);
3055 if (aclresult != ACLCHECK_OK)
3056 aclcheck_error(aclresult, OBJECT_INDEX, relation->relname);
3057
3058 /* Lock heap before index to avoid deadlock. */
3059 if (relId != oldRelId)
3060 {
3061 LockRelationOid(table_oid, table_lockmode);
3062 state->locked_table_oid = table_oid;
3063 }
3064}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4039
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:229
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2153
#define ACL_MAINTAIN
Definition: parsenodes.h:90
@ OBJECT_INDEX
Definition: parsenodes.h:2372
char * relname
Definition: primnodes.h:83
Definition: regguts.h:323

References ACL_MAINTAIN, aclcheck_error(), ACLCHECK_OK, arg, ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), GetUserId(), IndexGetRelation(), InvalidOid, LockRelationOid(), OBJECT_INDEX, OidIsValid, pg_class_aclcheck(), REINDEXOPT_CONCURRENTLY, RangeVar::relname, ShareLock, ShareUpdateExclusiveLock, and UnlockRelationOid().

Referenced by ReindexIndex().

◆ reindex_error_callback()

static void reindex_error_callback ( void *  arg)
static

Definition at line 3349 of file indexcmds.c.

3350{
3351 ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
3352
3353 Assert(RELKIND_HAS_PARTITIONS(errinfo->relkind));
3354
3355 if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
3356 errcontext("while reindexing partitioned table \"%s.%s\"",
3357 errinfo->relnamespace, errinfo->relname);
3358 else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
3359 errcontext("while reindexing partitioned index \"%s.%s\"",
3360 errinfo->relnamespace, errinfo->relname);
3361}
#define errcontext
Definition: elog.h:198
char * relnamespace
Definition: indexcmds.c:135

References arg, Assert(), errcontext, ReindexErrorInfo::relkind, ReindexErrorInfo::relname, and ReindexErrorInfo::relnamespace.

Referenced by ReindexPartitions().

◆ ReindexIndex()

static void ReindexIndex ( const ReindexStmt stmt,
const ReindexParams params,
bool  isTopLevel 
)
static

Definition at line 2941 of file indexcmds.c.

2942{
2943 const RangeVar *indexRelation = stmt->relation;
2945 Oid indOid;
2946 char persistence;
2947 char relkind;
2948
2949 /*
2950 * Find and lock index, and check permissions on table; use callback to
2951 * obtain lock on table first, to avoid deadlock hazard. The lock level
2952 * used here must match the index lock obtained in reindex_index().
2953 *
2954 * If it's a temporary index, we will perform a non-concurrent reindex,
2955 * even if CONCURRENTLY was requested. In that case, reindex_index() will
2956 * upgrade the lock, but that's OK, because other sessions can't hold
2957 * locks on our temporary table.
2958 */
2959 state.params = *params;
2960 state.locked_table_oid = InvalidOid;
2961 indOid = RangeVarGetRelidExtended(indexRelation,
2964 0,
2966 &state);
2967
2968 /*
2969 * Obtain the current persistence and kind of the existing index. We
2970 * already hold a lock on the index.
2971 */
2972 persistence = get_rel_persistence(indOid);
2973 relkind = get_rel_relkind(indOid);
2974
2975 if (relkind == RELKIND_PARTITIONED_INDEX)
2976 ReindexPartitions(stmt, indOid, params, isTopLevel);
2977 else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2978 persistence != RELPERSISTENCE_TEMP)
2980 else
2981 {
2982 ReindexParams newparams = *params;
2983
2985 reindex_index(stmt, indOid, false, persistence, &newparams);
2986 }
2987}
void reindex_index(const ReindexStmt *stmt, Oid indexId, bool skip_constraint_checks, char persistence, const ReindexParams *params)
Definition: index.c:3606
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
static bool ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const ReindexParams *params)
Definition: indexcmds.c:3590
static void ReindexPartitions(const ReindexStmt *stmt, Oid relid, const ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:3370
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2995
#define AccessExclusiveLock
Definition: lockdefs.h:43
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:440
ReindexParams params
Definition: indexcmds.c:125

References AccessExclusiveLock, get_rel_persistence(), get_rel_relkind(), InvalidOid, ReindexParams::options, ReindexIndexCallbackState::params, RangeVarCallbackForReindexIndex(), RangeVarGetRelidExtended(), reindex_index(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_REPORT_PROGRESS, ReindexPartitions(), ReindexRelationConcurrently(), ShareUpdateExclusiveLock, and stmt.

Referenced by ExecReindex().

◆ ReindexMultipleInternal()

static void ReindexMultipleInternal ( const ReindexStmt stmt,
const List relids,
const ReindexParams params 
)
static

Definition at line 3464 of file indexcmds.c.

3465{
3466 ListCell *l;
3467
3470
3471 foreach(l, relids)
3472 {
3473 Oid relid = lfirst_oid(l);
3474 char relkind;
3475 char relpersistence;
3476
3478
3479 /* functions in indexes may want a snapshot set */
3481
3482 /* check if the relation still exists */
3483 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
3484 {
3487 continue;
3488 }
3489
3490 /*
3491 * Check permissions except when moving to database's default if a new
3492 * tablespace is chosen. Note that this check also happens in
3493 * ExecReindex(), but we do an extra check here as this runs across
3494 * multiple transactions.
3495 */
3496 if (OidIsValid(params->tablespaceOid) &&
3498 {
3499 AclResult aclresult;
3500
3501 aclresult = object_aclcheck(TableSpaceRelationId, params->tablespaceOid,
3503 if (aclresult != ACLCHECK_OK)
3506 }
3507
3508 relkind = get_rel_relkind(relid);
3509 relpersistence = get_rel_persistence(relid);
3510
3511 /*
3512 * Partitioned tables and indexes can never be processed directly, and
3513 * a list of their leaves should be built first.
3514 */
3515 Assert(!RELKIND_HAS_PARTITIONS(relkind));
3516
3517 if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3518 relpersistence != RELPERSISTENCE_TEMP)
3519 {
3520 ReindexParams newparams = *params;
3521
3522 newparams.options |= REINDEXOPT_MISSING_OK;
3523 (void) ReindexRelationConcurrently(stmt, relid, &newparams);
3524 if (ActiveSnapshotSet())
3526 /* ReindexRelationConcurrently() does the verbose output */
3527 }
3528 else if (relkind == RELKIND_INDEX)
3529 {
3530 ReindexParams newparams = *params;
3531
3532 newparams.options |=
3534 reindex_index(stmt, relid, false, relpersistence, &newparams);
3536 /* reindex_index() does the verbose output */
3537 }
3538 else
3539 {
3540 bool result;
3541 ReindexParams newparams = *params;
3542
3543 newparams.options |=
3545 result = reindex_relation(stmt, relid,
3548 &newparams);
3549
3550 if (result && (params->options & REINDEXOPT_VERBOSE) != 0)
3551 ereport(INFO,
3552 (errmsg("table \"%s.%s\" was reindexed",
3554 get_rel_name(relid))));
3555
3557 }
3558
3560 }
3561
3563}
#define INFO
Definition: elog.h:34
bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params)
Definition: index.c:3946
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:159
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:161
char * get_rel_name(Oid relid)
Definition: lsyscache.c:2078
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:2102
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:812
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:100

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, ActiveSnapshotSet(), Assert(), CommitTransactionCommand(), ereport, errmsg(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_persistence(), get_rel_relkind(), get_tablespace_name(), GetTransactionSnapshot(), GetUserId(), INFO, lfirst_oid, MyDatabaseTableSpace, object_aclcheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, ReindexParams::options, ReindexIndexCallbackState::params, PopActiveSnapshot(), PushActiveSnapshot(), reindex_index(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_PROCESS_TOAST, reindex_relation(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_MISSING_OK, REINDEXOPT_REPORT_PROGRESS, REINDEXOPT_VERBOSE, ReindexRelationConcurrently(), SearchSysCacheExists1, StartTransactionCommand(), stmt, and ReindexParams::tablespaceOid.

Referenced by ReindexMultipleTables(), and ReindexPartitions().

◆ ReindexMultipleTables()

static void ReindexMultipleTables ( const ReindexStmt stmt,
const ReindexParams params 
)
static

Definition at line 3130 of file indexcmds.c.

3131{
3132
3133 Oid objectOid;
3134 Relation relationRelation;
3135 TableScanDesc scan;
3136 ScanKeyData scan_keys[1];
3137 HeapTuple tuple;
3138 MemoryContext private_context;
3139 MemoryContext old;
3140 List *relids = NIL;
3141 int num_keys;
3142 bool concurrent_warning = false;
3143 bool tablespace_warning = false;
3144 const char *objectName = stmt->name;
3145 const ReindexObjectType objectKind = stmt->kind;
3146
3147 Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
3148 objectKind == REINDEX_OBJECT_SYSTEM ||
3149 objectKind == REINDEX_OBJECT_DATABASE);
3150
3151 /*
3152 * This matches the options enforced by the grammar, where the object name
3153 * is optional for DATABASE and SYSTEM.
3154 */
3155 Assert(objectName || objectKind != REINDEX_OBJECT_SCHEMA);
3156
3157 if (objectKind == REINDEX_OBJECT_SYSTEM &&
3158 (params->options & REINDEXOPT_CONCURRENTLY) != 0)
3159 ereport(ERROR,
3160 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3161 errmsg("cannot reindex system catalogs concurrently")));
3162
3163 /*
3164 * Get OID of object to reindex, being the database currently being used
3165 * by session for a database or for system catalogs, or the schema defined
3166 * by caller. At the same time do permission checks that need different
3167 * processing depending on the object type.
3168 */
3169 if (objectKind == REINDEX_OBJECT_SCHEMA)
3170 {
3171 objectOid = get_namespace_oid(objectName, false);
3172
3173 if (!object_ownercheck(NamespaceRelationId, objectOid, GetUserId()) &&
3174 !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
3176 objectName);
3177 }
3178 else
3179 {
3180 objectOid = MyDatabaseId;
3181
3182 if (objectName && strcmp(objectName, get_database_name(objectOid)) != 0)
3183 ereport(ERROR,
3184 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3185 errmsg("can only reindex the currently open database")));
3186 if (!object_ownercheck(DatabaseRelationId, objectOid, GetUserId()) &&
3187 !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
3189 get_database_name(objectOid));
3190 }
3191
3192 /*
3193 * Create a memory context that will survive forced transaction commits we
3194 * do below. Since it is a child of PortalContext, it will go away
3195 * eventually even if we suffer an error; there's no need for special
3196 * abort cleanup logic.
3197 */
3198 private_context = AllocSetContextCreate(PortalContext,
3199 "ReindexMultipleTables",
3201
3202 /*
3203 * Define the search keys to find the objects to reindex. For a schema, we
3204 * select target relations using relnamespace, something not necessary for
3205 * a database-wide operation.
3206 */
3207 if (objectKind == REINDEX_OBJECT_SCHEMA)
3208 {
3209 num_keys = 1;
3210 ScanKeyInit(&scan_keys[0],
3211 Anum_pg_class_relnamespace,
3212 BTEqualStrategyNumber, F_OIDEQ,
3213 ObjectIdGetDatum(objectOid));
3214 }
3215 else
3216 num_keys = 0;
3217
3218 /*
3219 * Scan pg_class to build a list of the relations we need to reindex.
3220 *
3221 * We only consider plain relations and materialized views here (toast
3222 * rels will be processed indirectly by reindex_relation).
3223 */
3224 relationRelation = table_open(RelationRelationId, AccessShareLock);
3225 scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
3226 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3227 {
3228 Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
3229 Oid relid = classtuple->oid;
3230
3231 /*
3232 * Only regular tables and matviews can have indexes, so ignore any
3233 * other kind of relation.
3234 *
3235 * Partitioned tables/indexes are skipped but matching leaf partitions
3236 * are processed.
3237 */
3238 if (classtuple->relkind != RELKIND_RELATION &&
3239 classtuple->relkind != RELKIND_MATVIEW)
3240 continue;
3241
3242 /* Skip temp tables of other backends; we can't reindex them at all */
3243 if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
3244 !isTempNamespace(classtuple->relnamespace))
3245 continue;
3246
3247 /*
3248 * Check user/system classification. SYSTEM processes all the
3249 * catalogs, and DATABASE processes everything that's not a catalog.
3250 */
3251 if (objectKind == REINDEX_OBJECT_SYSTEM &&
3252 !IsCatalogRelationOid(relid))
3253 continue;
3254 else if (objectKind == REINDEX_OBJECT_DATABASE &&
3255 IsCatalogRelationOid(relid))
3256 continue;
3257
3258 /*
3259 * We already checked privileges on the database or schema, but we
3260 * further restrict reindexing shared catalogs to roles with the
3261 * MAINTAIN privilege on the relation.
3262 */
3263 if (classtuple->relisshared &&
3265 continue;
3266
3267 /*
3268 * Skip system tables, since index_create() would reject indexing them
3269 * concurrently (and it would likely fail if we tried).
3270 */
3271 if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3272 IsCatalogRelationOid(relid))
3273 {
3274 if (!concurrent_warning)
3276 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3277 errmsg("cannot reindex system catalogs concurrently, skipping all")));
3278 concurrent_warning = true;
3279 continue;
3280 }
3281
3282 /*
3283 * If a new tablespace is set, check if this relation has to be
3284 * skipped.
3285 */
3286 if (OidIsValid(params->tablespaceOid))
3287 {
3288 bool skip_rel = false;
3289
3290 /*
3291 * Mapped relations cannot be moved to different tablespaces (in
3292 * particular this eliminates all shared catalogs.).
3293 */
3294 if (RELKIND_HAS_STORAGE(classtuple->relkind) &&
3295 !RelFileNumberIsValid(classtuple->relfilenode))
3296 skip_rel = true;
3297
3298 /*
3299 * A system relation is always skipped, even with
3300 * allow_system_table_mods enabled.
3301 */
3302 if (IsSystemClass(relid, classtuple))
3303 skip_rel = true;
3304
3305 if (skip_rel)
3306 {
3307 if (!tablespace_warning)
3309 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3310 errmsg("cannot move system relations, skipping all")));
3311 tablespace_warning = true;
3312 continue;
3313 }
3314 }
3315
3316 /* Save the list of relation OIDs in private context */
3317 old = MemoryContextSwitchTo(private_context);
3318
3319 /*
3320 * We always want to reindex pg_class first if it's selected to be
3321 * reindexed. This ensures that if there is any corruption in
3322 * pg_class' indexes, they will be fixed before we process any other
3323 * tables. This is critical because reindexing itself will try to
3324 * update pg_class.
3325 */
3326 if (relid == RelationRelationId)
3327 relids = lcons_oid(relid, relids);
3328 else
3329 relids = lappend_oid(relids, relid);
3330
3332 }
3333 table_endscan(scan);
3334 table_close(relationRelation, AccessShareLock);
3335
3336 /*
3337 * Process each relation listed in a separate transaction. Note that this
3338 * commits and then starts a new transaction immediately.
3339 */
3340 ReindexMultipleInternal(stmt, relids, params);
3341
3342 MemoryContextDelete(private_context);
3343}
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5284
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4090
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:121
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:86
#define WARNING
Definition: elog.h:36
Oid MyDatabaseId
Definition: globals.c:94
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1364
static void ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids, const ReindexParams *params)
Definition: indexcmds.c:3464
List * lcons_oid(Oid datum, List *list)
Definition: list.c:531
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
char * get_database_name(Oid dbid)
Definition: lsyscache.c:1242
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:472
MemoryContext PortalContext
Definition: mcxt.c:175
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3719
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3605
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
@ OBJECT_DATABASE
Definition: parsenodes.h:2361
ReindexObjectType
Definition: parsenodes.h:4132
FormData_pg_class * Form_pg_class
Definition: pg_class.h:156
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, ScanKeyData *key)
Definition: tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:985

References AccessShareLock, ACL_MAINTAIN, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, Assert(), BTEqualStrategyNumber, ereport, errcode(), errmsg(), ERROR, ForwardScanDirection, get_database_name(), get_namespace_oid(), GETSTRUCT(), GetUserId(), has_privs_of_role(), heap_getnext(), IsCatalogRelationOid(), IsSystemClass(), isTempNamespace(), lappend_oid(), lcons_oid(), MemoryContextDelete(), MemoryContextSwitchTo(), MyDatabaseId, NIL, OBJECT_DATABASE, object_ownercheck(), OBJECT_SCHEMA, ObjectIdGetDatum(), OidIsValid, ReindexParams::options, ReindexIndexCallbackState::params, pg_class_aclcheck(), PortalContext, REINDEX_OBJECT_DATABASE, REINDEX_OBJECT_SCHEMA, REINDEX_OBJECT_SYSTEM, ReindexMultipleInternal(), REINDEXOPT_CONCURRENTLY, RelFileNumberIsValid, ScanKeyInit(), stmt, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), ReindexParams::tablespaceOid, and WARNING.

Referenced by ExecReindex().

◆ ReindexPartitions()

static void ReindexPartitions ( const ReindexStmt stmt,
Oid  relid,
const ReindexParams params,
bool  isTopLevel 
)
static

Definition at line 3370 of file indexcmds.c.

3371{
3372 List *partitions = NIL;
3373 char relkind = get_rel_relkind(relid);
3374 char *relname = get_rel_name(relid);
3375 char *relnamespace = get_namespace_name(get_rel_namespace(relid));
3376 MemoryContext reindex_context;
3377 List *inhoids;
3378 ListCell *lc;
3379 ErrorContextCallback errcallback;
3380 ReindexErrorInfo errinfo;
3381
3382 Assert(RELKIND_HAS_PARTITIONS(relkind));
3383
3384 /*
3385 * Check if this runs in a transaction block, with an error callback to
3386 * provide more context under which a problem happens.
3387 */
3388 errinfo.relname = pstrdup(relname);
3389 errinfo.relnamespace = pstrdup(relnamespace);
3390 errinfo.relkind = relkind;
3391 errcallback.callback = reindex_error_callback;
3392 errcallback.arg = &errinfo;
3393 errcallback.previous = error_context_stack;
3394 error_context_stack = &errcallback;
3395
3396 PreventInTransactionBlock(isTopLevel,
3397 relkind == RELKIND_PARTITIONED_TABLE ?
3398 "REINDEX TABLE" : "REINDEX INDEX");
3399
3400 /* Pop the error context stack */
3401 error_context_stack = errcallback.previous;
3402
3403 /*
3404 * Create special memory context for cross-transaction storage.
3405 *
3406 * Since it is a child of PortalContext, it will go away eventually even
3407 * if we suffer an error so there is no need for special abort cleanup
3408 * logic.
3409 */
3410 reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
3412
3413 /* ShareLock is enough to prevent schema modifications */
3414 inhoids = find_all_inheritors(relid, ShareLock, NULL);
3415
3416 /*
3417 * The list of relations to reindex are the physical partitions of the
3418 * tree so discard any partitioned table or index.
3419 */
3420 foreach(lc, inhoids)
3421 {
3422 Oid partoid = lfirst_oid(lc);
3423 char partkind = get_rel_relkind(partoid);
3424 MemoryContext old_context;
3425
3426 /*
3427 * This discards partitioned tables, partitioned indexes and foreign
3428 * tables.
3429 */
3430 if (!RELKIND_HAS_STORAGE(partkind))
3431 continue;
3432
3433 Assert(partkind == RELKIND_INDEX ||
3434 partkind == RELKIND_RELATION);
3435
3436 /* Save partition OID */
3437 old_context = MemoryContextSwitchTo(reindex_context);
3438 partitions = lappend_oid(partitions, partoid);
3439 MemoryContextSwitchTo(old_context);
3440 }
3441
3442 /*
3443 * Process each partition listed in a separate transaction. Note that
3444 * this commits and then starts a new transaction immediately.
3445 */
3447
3448 /*
3449 * Clean up working storage --- note we must do this after
3450 * StartTransactionCommand, else we might be trying to delete the active
3451 * context!
3452 */
3453 MemoryContextDelete(reindex_context);
3454}
ErrorContextCallback * error_context_stack
Definition: elog.c:95
static void reindex_error_callback(void *arg)
Definition: indexcmds.c:3349
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
static int partitions
Definition: pgbench.c:224
struct ErrorContextCallback * previous
Definition: elog.h:297
void(* callback)(void *arg)
Definition: elog.h:298

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, Assert(), ErrorContextCallback::callback, error_context_stack, find_all_inheritors(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_relkind(), lappend_oid(), lfirst_oid, MemoryContextDelete(), MemoryContextSwitchTo(), NIL, ReindexIndexCallbackState::params, partitions, PortalContext, PreventInTransactionBlock(), ErrorContextCallback::previous, pstrdup(), reindex_error_callback(), ReindexMultipleInternal(), ReindexErrorInfo::relkind, ReindexErrorInfo::relname, relname, ReindexErrorInfo::relnamespace, ShareLock, and stmt.

Referenced by ReindexIndex(), and ReindexTable().

◆ ReindexRelationConcurrently()

static bool ReindexRelationConcurrently ( const ReindexStmt stmt,
Oid  relationOid,
const ReindexParams params 
)
static

Definition at line 3590 of file indexcmds.c.

3591{
3592 typedef struct ReindexIndexInfo
3593 {
3594 Oid indexId;
3595 Oid tableId;
3596 Oid amId;
3597 bool safe; /* for set_indexsafe_procflags */
3598 } ReindexIndexInfo;
3599 List *heapRelationIds = NIL;
3600 List *indexIds = NIL;
3601 List *newIndexIds = NIL;
3602 List *relationLocks = NIL;
3603 List *lockTags = NIL;
3604 ListCell *lc,
3605 *lc2;
3606 MemoryContext private_context;
3607 MemoryContext oldcontext;
3608 char relkind;
3609 char *relationName = NULL;
3610 char *relationNamespace = NULL;
3611 PGRUsage ru0;
3612 const int progress_index[] = {
3617 };
3618 int64 progress_vals[4];
3619
3620 /*
3621 * Create a memory context that will survive forced transaction commits we
3622 * do below. Since it is a child of PortalContext, it will go away
3623 * eventually even if we suffer an error; there's no need for special
3624 * abort cleanup logic.
3625 */
3626 private_context = AllocSetContextCreate(PortalContext,
3627 "ReindexConcurrent",
3629
3630 if ((params->options & REINDEXOPT_VERBOSE) != 0)
3631 {
3632 /* Save data needed by REINDEX VERBOSE in private context */
3633 oldcontext = MemoryContextSwitchTo(private_context);
3634
3635 relationName = get_rel_name(relationOid);
3636 relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
3637
3638 pg_rusage_init(&ru0);
3639
3640 MemoryContextSwitchTo(oldcontext);
3641 }
3642
3643 relkind = get_rel_relkind(relationOid);
3644
3645 /*
3646 * Extract the list of indexes that are going to be rebuilt based on the
3647 * relation Oid given by caller.
3648 */
3649 switch (relkind)
3650 {
3651 case RELKIND_RELATION:
3652 case RELKIND_MATVIEW:
3653 case RELKIND_TOASTVALUE:
3654 {
3655 /*
3656 * In the case of a relation, find all its indexes including
3657 * toast indexes.
3658 */
3659 Relation heapRelation;
3660
3661 /* Save the list of relation OIDs in private context */
3662 oldcontext = MemoryContextSwitchTo(private_context);
3663
3664 /* Track this relation for session locks */
3665 heapRelationIds = lappend_oid(heapRelationIds, relationOid);
3666
3667 MemoryContextSwitchTo(oldcontext);
3668
3669 if (IsCatalogRelationOid(relationOid))
3670 ereport(ERROR,
3671 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3672 errmsg("cannot reindex system catalogs concurrently")));
3673
3674 /* Open relation to get its indexes */
3675 if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3676 {
3677 heapRelation = try_table_open(relationOid,
3679 /* leave if relation does not exist */
3680 if (!heapRelation)
3681 break;
3682 }
3683 else
3684 heapRelation = table_open(relationOid,
3686
3687 if (OidIsValid(params->tablespaceOid) &&
3688 IsSystemRelation(heapRelation))
3689 ereport(ERROR,
3690 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3691 errmsg("cannot move system relation \"%s\"",
3692 RelationGetRelationName(heapRelation))));
3693
3694 /* Add all the valid indexes of relation to list */
3695 foreach(lc, RelationGetIndexList(heapRelation))
3696 {
3697 Oid cellOid = lfirst_oid(lc);
3698 Relation indexRelation = index_open(cellOid,
3700
3701 if (!indexRelation->rd_index->indisvalid)
3703 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3704 errmsg("skipping reindex of invalid index \"%s.%s\"",
3706 get_rel_name(cellOid)),
3707 errhint("Use DROP INDEX or REINDEX INDEX.")));
3708 else if (indexRelation->rd_index->indisexclusion)
3710 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3711 errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
3713 get_rel_name(cellOid))));
3714 else
3715 {
3716 ReindexIndexInfo *idx;
3717
3718 /* Save the list of relation OIDs in private context */
3719 oldcontext = MemoryContextSwitchTo(private_context);
3720
3721 idx = palloc_object(ReindexIndexInfo);
3722 idx->indexId = cellOid;
3723 /* other fields set later */
3724
3725 indexIds = lappend(indexIds, idx);
3726
3727 MemoryContextSwitchTo(oldcontext);
3728 }
3729
3730 index_close(indexRelation, NoLock);
3731 }
3732
3733 /* Also add the toast indexes */
3734 if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
3735 {
3736 Oid toastOid = heapRelation->rd_rel->reltoastrelid;
3737 Relation toastRelation = table_open(toastOid,
3739
3740 /* Save the list of relation OIDs in private context */
3741 oldcontext = MemoryContextSwitchTo(private_context);
3742
3743 /* Track this relation for session locks */
3744 heapRelationIds = lappend_oid(heapRelationIds, toastOid);
3745
3746 MemoryContextSwitchTo(oldcontext);
3747
3748 foreach(lc2, RelationGetIndexList(toastRelation))
3749 {
3750 Oid cellOid = lfirst_oid(lc2);
3751 Relation indexRelation = index_open(cellOid,
3753
3754 if (!indexRelation->rd_index->indisvalid)
3756 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3757 errmsg("skipping reindex of invalid index \"%s.%s\"",
3759 get_rel_name(cellOid)),
3760 errhint("Use DROP INDEX or REINDEX INDEX.")));
3761 else
3762 {
3763 ReindexIndexInfo *idx;
3764
3765 /*
3766 * Save the list of relation OIDs in private
3767 * context
3768 */
3769 oldcontext = MemoryContextSwitchTo(private_context);
3770
3771 idx = palloc_object(ReindexIndexInfo);
3772 idx->indexId = cellOid;
3773 indexIds = lappend(indexIds, idx);
3774 /* other fields set later */
3775
3776 MemoryContextSwitchTo(oldcontext);
3777 }
3778
3779 index_close(indexRelation, NoLock);
3780 }
3781
3782 table_close(toastRelation, NoLock);
3783 }
3784
3785 table_close(heapRelation, NoLock);
3786 break;
3787 }
3788 case RELKIND_INDEX:
3789 {
3790 Oid heapId = IndexGetRelation(relationOid,
3791 (params->options & REINDEXOPT_MISSING_OK) != 0);
3792 Relation heapRelation;
3793 ReindexIndexInfo *idx;
3794
3795 /* if relation is missing, leave */
3796 if (!OidIsValid(heapId))
3797 break;
3798
3799 if (IsCatalogRelationOid(heapId))
3800 ereport(ERROR,
3801 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3802 errmsg("cannot reindex system catalogs concurrently")));
3803
3804 /*
3805 * Don't allow reindex for an invalid index on TOAST table, as
3806 * if rebuilt it would not be possible to drop it. Match
3807 * error message in reindex_index().
3808 */
3809 if (IsToastNamespace(get_rel_namespace(relationOid)) &&
3810 !get_index_isvalid(relationOid))
3811 ereport(ERROR,
3812 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3813 errmsg("cannot reindex invalid index on TOAST table")));
3814
3815 /*
3816 * Check if parent relation can be locked and if it exists,
3817 * this needs to be done at this stage as the list of indexes
3818 * to rebuild is not complete yet, and REINDEXOPT_MISSING_OK
3819 * should not be used once all the session locks are taken.
3820 */
3821 if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3822 {
3823 heapRelation = try_table_open(heapId,
3825 /* leave if relation does not exist */
3826 if (!heapRelation)
3827 break;
3828 }
3829 else
3830 heapRelation = table_open(heapId,
3832
3833 if (OidIsValid(params->tablespaceOid) &&
3834 IsSystemRelation(heapRelation))
3835 ereport(ERROR,
3836 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3837 errmsg("cannot move system relation \"%s\"",
3838 get_rel_name(relationOid))));
3839
3840 table_close(heapRelation, NoLock);
3841
3842 /* Save the list of relation OIDs in private context */
3843 oldcontext = MemoryContextSwitchTo(private_context);
3844
3845 /* Track the heap relation of this index for session locks */
3846 heapRelationIds = list_make1_oid(heapId);
3847
3848 /*
3849 * Save the list of relation OIDs in private context. Note
3850 * that invalid indexes are allowed here.
3851 */
3852 idx = palloc_object(ReindexIndexInfo);
3853 idx->indexId = relationOid;
3854 indexIds = lappend(indexIds, idx);
3855 /* other fields set later */
3856
3857 MemoryContextSwitchTo(oldcontext);
3858 break;
3859 }
3860
3861 case RELKIND_PARTITIONED_TABLE:
3862 case RELKIND_PARTITIONED_INDEX:
3863 default:
3864 /* Return error if type of relation is not supported */
3865 ereport(ERROR,
3866 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3867 errmsg("cannot reindex this type of relation concurrently")));
3868 break;
3869 }
3870
3871 /*
3872 * Definitely no indexes, so leave. Any checks based on
3873 * REINDEXOPT_MISSING_OK should be done only while the list of indexes to
3874 * work on is built as the session locks taken before this transaction
3875 * commits will make sure that they cannot be dropped by a concurrent
3876 * session until this operation completes.
3877 */
3878 if (indexIds == NIL)
3879 return false;
3880
3881 /* It's not a shared catalog, so refuse to move it to shared tablespace */
3882 if (params->tablespaceOid == GLOBALTABLESPACE_OID)
3883 ereport(ERROR,
3884 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3885 errmsg("cannot move non-shared relation to tablespace \"%s\"",
3887
3888 Assert(heapRelationIds != NIL);
3889
3890 /*-----
3891 * Now we have all the indexes we want to process in indexIds.
3892 *
3893 * The phases now are:
3894 *
3895 * 1. create new indexes in the catalog
3896 * 2. build new indexes
3897 * 3. let new indexes catch up with tuples inserted in the meantime
3898 * 4. swap index names
3899 * 5. mark old indexes as dead
3900 * 6. drop old indexes
3901 *
3902 * We process each phase for all indexes before moving to the next phase,
3903 * for efficiency.
3904 */
3905
3906 /*
3907 * Phase 1 of REINDEX CONCURRENTLY
3908 *
3909 * Create a new index with the same properties as the old one, but it is
3910 * only registered in catalogs and will be built later. Then get session
3911 * locks on all involved tables. See analogous code in DefineIndex() for
3912 * more detailed comments.
3913 */
3914
3915 foreach(lc, indexIds)
3916 {
3917 char *concurrentName;
3918 ReindexIndexInfo *idx = lfirst(lc);
3919 ReindexIndexInfo *newidx;
3920 Oid newIndexId;
3921 Relation indexRel;
3922 Relation heapRel;
3923 Oid save_userid;
3924 int save_sec_context;
3925 int save_nestlevel;
3926 Relation newIndexRel;
3927 LockRelId *lockrelid;
3928 Oid tablespaceid;
3929
3930 indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock);
3931 heapRel = table_open(indexRel->rd_index->indrelid,
3933
3934 /*
3935 * Switch to the table owner's userid, so that any index functions are
3936 * run as that user. Also lock down security-restricted operations
3937 * and arrange to make GUC variable changes local to this command.
3938 */
3939 GetUserIdAndSecContext(&save_userid, &save_sec_context);
3940 SetUserIdAndSecContext(heapRel->rd_rel->relowner,
3941 save_sec_context | SECURITY_RESTRICTED_OPERATION);
3942 save_nestlevel = NewGUCNestLevel();
3944
3945 /* determine safety of this index for set_indexsafe_procflags */
3946 idx->safe = (RelationGetIndexExpressions(indexRel) == NIL &&
3947 RelationGetIndexPredicate(indexRel) == NIL);
3948
3949#ifdef USE_INJECTION_POINTS
3950 if (idx->safe)
3951 INJECTION_POINT("reindex-conc-index-safe", NULL);
3952 else
3953 INJECTION_POINT("reindex-conc-index-not-safe", NULL);
3954#endif
3955
3956 idx->tableId = RelationGetRelid(heapRel);
3957 idx->amId = indexRel->rd_rel->relam;
3958
3959 /* This function shouldn't be called for temporary relations. */
3960 if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
3961 elog(ERROR, "cannot reindex a temporary table concurrently");
3962
3964
3966 progress_vals[1] = 0; /* initializing */
3967 progress_vals[2] = idx->indexId;
3968 progress_vals[3] = idx->amId;
3969 pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3970
3971 /* Choose a temporary relation name for the new index */
3972 concurrentName = ChooseRelationName(get_rel_name(idx->indexId),
3973 NULL,
3974 "ccnew",
3975 get_rel_namespace(indexRel->rd_index->indrelid),
3976 false);
3977
3978 /* Choose the new tablespace, indexes of toast tables are not moved */
3979 if (OidIsValid(params->tablespaceOid) &&
3980 heapRel->rd_rel->relkind != RELKIND_TOASTVALUE)
3981 tablespaceid = params->tablespaceOid;
3982 else
3983 tablespaceid = indexRel->rd_rel->reltablespace;
3984
3985 /* Create new index definition based on given index */
3986 newIndexId = index_concurrently_create_copy(heapRel,
3987 idx->indexId,
3988 tablespaceid,
3989 concurrentName);
3990
3991 /*
3992 * Now open the relation of the new index, a session-level lock is
3993 * also needed on it.
3994 */
3995 newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3996
3997 /*
3998 * Save the list of OIDs and locks in private context
3999 */
4000 oldcontext = MemoryContextSwitchTo(private_context);
4001
4002 newidx = palloc_object(ReindexIndexInfo);
4003 newidx->indexId = newIndexId;
4004 newidx->safe = idx->safe;
4005 newidx->tableId = idx->tableId;
4006 newidx->amId = idx->amId;
4007
4008 newIndexIds = lappend(newIndexIds, newidx);
4009
4010 /*
4011 * Save lockrelid to protect each relation from drop then close
4012 * relations. The lockrelid on parent relation is not taken here to
4013 * avoid multiple locks taken on the same relation, instead we rely on
4014 * parentRelationIds built earlier.
4015 */
4016 lockrelid = palloc_object(LockRelId);
4017 *lockrelid = indexRel->rd_lockInfo.lockRelId;
4018 relationLocks = lappend(relationLocks, lockrelid);
4019 lockrelid = palloc_object(LockRelId);
4020 *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
4021 relationLocks = lappend(relationLocks, lockrelid);
4022
4023 MemoryContextSwitchTo(oldcontext);
4024
4025 index_close(indexRel, NoLock);
4026 index_close(newIndexRel, NoLock);
4027
4028 /* Roll back any GUC changes executed by index functions */
4029 AtEOXact_GUC(false, save_nestlevel);
4030
4031 /* Restore userid and security context */
4032 SetUserIdAndSecContext(save_userid, save_sec_context);
4033
4034 table_close(heapRel, NoLock);
4035
4036 /*
4037 * If a statement is available, telling that this comes from a REINDEX
4038 * command, collect the new index for event triggers.
4039 */
4040 if (stmt)
4041 {
4042 ObjectAddress address;
4043
4044 ObjectAddressSet(address, RelationRelationId, newIndexId);
4047 (Node *) stmt);
4048 }
4049 }
4050
4051 /*
4052 * Save the heap lock for following visibility checks with other backends
4053 * might conflict with this session.
4054 */
4055 foreach(lc, heapRelationIds)
4056 {
4058 LockRelId *lockrelid;
4059 LOCKTAG *heaplocktag;
4060
4061 /* Save the list of locks in private context */
4062 oldcontext = MemoryContextSwitchTo(private_context);
4063
4064 /* Add lockrelid of heap relation to the list of locked relations */
4065 lockrelid = palloc_object(LockRelId);
4066 *lockrelid = heapRelation->rd_lockInfo.lockRelId;
4067 relationLocks = lappend(relationLocks, lockrelid);
4068
4069 heaplocktag = palloc_object(LOCKTAG);
4070
4071 /* Save the LOCKTAG for this parent relation for the wait phase */
4072 SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
4073 lockTags = lappend(lockTags, heaplocktag);
4074
4075 MemoryContextSwitchTo(oldcontext);
4076
4077 /* Close heap relation */
4078 table_close(heapRelation, NoLock);
4079 }
4080
4081 /* Get a session-level lock on each table. */
4082 foreach(lc, relationLocks)
4083 {
4084 LockRelId *lockrelid = (LockRelId *) lfirst(lc);
4085
4087 }
4088
4092
4093 /*
4094 * Because we don't take a snapshot in this transaction, there's no need
4095 * to set the PROC_IN_SAFE_IC flag here.
4096 */
4097
4098 /*
4099 * Phase 2 of REINDEX CONCURRENTLY
4100 *
4101 * Build the new indexes in a separate transaction for each index to avoid
4102 * having open transactions for an unnecessary long time. But before
4103 * doing that, wait until no running transactions could have the table of
4104 * the index open with the old list of indexes. See "phase 2" in
4105 * DefineIndex() for more details.
4106 */
4107
4110 WaitForLockersMultiple(lockTags, ShareLock, true);
4112
4113 foreach(lc, newIndexIds)
4114 {
4115 ReindexIndexInfo *newidx = lfirst(lc);
4116
4117 /* Start new transaction for this index's concurrent build */
4119
4120 /*
4121 * Check for user-requested abort. This is inside a transaction so as
4122 * xact.c does not issue a useless WARNING, and ensures that
4123 * session-level locks are cleaned up on abort.
4124 */
4126
4127 /* Tell concurrent indexing to ignore us, if index qualifies */
4128 if (newidx->safe)
4130
4131 /* Set ActiveSnapshot since functions in the indexes may need it */
4133
4134 /*
4135 * Update progress for the index to build, with the correct parent
4136 * table involved.
4137 */
4140 progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD;
4141 progress_vals[2] = newidx->indexId;
4142 progress_vals[3] = newidx->amId;
4143 pgstat_progress_update_multi_param(4, progress_index, progress_vals);
4144
4145 /* Perform concurrent build of new index */
4146 index_concurrently_build(newidx->tableId, newidx->indexId);
4147
4150 }
4151
4153
4154 /*
4155 * Because we don't take a snapshot or Xid in this transaction, there's no
4156 * need to set the PROC_IN_SAFE_IC flag here.
4157 */
4158
4159 /*
4160 * Phase 3 of REINDEX CONCURRENTLY
4161 *
4162 * During this phase the old indexes catch up with any new tuples that
4163 * were created during the previous phase. See "phase 3" in DefineIndex()
4164 * for more details.
4165 */
4166
4169 WaitForLockersMultiple(lockTags, ShareLock, true);
4171
4172 foreach(lc, newIndexIds)
4173 {
4174 ReindexIndexInfo *newidx = lfirst(lc);
4175 TransactionId limitXmin;
4176 Snapshot snapshot;
4177
4179
4180 /*
4181 * Check for user-requested abort. This is inside a transaction so as
4182 * xact.c does not issue a useless WARNING, and ensures that
4183 * session-level locks are cleaned up on abort.
4184 */
4186
4187 /* Tell concurrent indexing to ignore us, if index qualifies */
4188 if (newidx->safe)
4190
4191 /*
4192 * Take the "reference snapshot" that will be used by validate_index()
4193 * to filter candidate tuples.
4194 */
4196 PushActiveSnapshot(snapshot);
4197
4198 /*
4199 * Update progress for the index to build, with the correct parent
4200 * table involved.
4201 */
4205 progress_vals[2] = newidx->indexId;
4206 progress_vals[3] = newidx->amId;
4207 pgstat_progress_update_multi_param(4, progress_index, progress_vals);
4208
4209 validate_index(newidx->tableId, newidx->indexId, snapshot);
4210
4211 /*
4212 * We can now do away with our active snapshot, we still need to save
4213 * the xmin limit to wait for older snapshots.
4214 */
4215 limitXmin = snapshot->xmin;
4216
4218 UnregisterSnapshot(snapshot);
4219
4220 /*
4221 * To ensure no deadlocks, we must commit and start yet another
4222 * transaction, and do our wait before any snapshot has been taken in
4223 * it.
4224 */
4227
4228 /*
4229 * The index is now valid in the sense that it contains all currently
4230 * interesting tuples. But since it might not contain tuples deleted
4231 * just before the reference snap was taken, we have to wait out any
4232 * transactions that might have older snapshots.
4233 *
4234 * Because we don't take a snapshot or Xid in this transaction,
4235 * there's no need to set the PROC_IN_SAFE_IC flag here.
4236 */
4239 WaitForOlderSnapshots(limitXmin, true);
4240
4242 }
4243
4244 /*
4245 * Phase 4 of REINDEX CONCURRENTLY
4246 *
4247 * Now that the new indexes have been validated, swap each new index with
4248 * its corresponding old index.
4249 *
4250 * We mark the new indexes as valid and the old indexes as not valid at
4251 * the same time to make sure we only get constraint violations from the
4252 * indexes with the correct names.
4253 */
4254
4255 INJECTION_POINT("reindex-relation-concurrently-before-swap", NULL);
4257
4258 /*
4259 * Because this transaction only does catalog manipulations and doesn't do
4260 * any index operations, we can set the PROC_IN_SAFE_IC flag here
4261 * unconditionally.
4262 */
4264
4265 forboth(lc, indexIds, lc2, newIndexIds)
4266 {
4267 ReindexIndexInfo *oldidx = lfirst(lc);
4268 ReindexIndexInfo *newidx = lfirst(lc2);
4269 char *oldName;
4270
4271 /*
4272 * Check for user-requested abort. This is inside a transaction so as
4273 * xact.c does not issue a useless WARNING, and ensures that
4274 * session-level locks are cleaned up on abort.
4275 */
4277
4278 /* Choose a relation name for old index */
4279 oldName = ChooseRelationName(get_rel_name(oldidx->indexId),
4280 NULL,
4281 "ccold",
4282 get_rel_namespace(oldidx->tableId),
4283 false);
4284
4285 /*
4286 * Swapping the indexes might involve TOAST table access, so ensure we
4287 * have a valid snapshot.
4288 */
4290
4291 /*
4292 * Swap old index with the new one. This also marks the new one as
4293 * valid and the old one as not valid.
4294 */
4295 index_concurrently_swap(newidx->indexId, oldidx->indexId, oldName);
4296
4298
4299 /*
4300 * Invalidate the relcache for the table, so that after this commit
4301 * all sessions will refresh any cached plans that might reference the
4302 * index.
4303 */
4304 CacheInvalidateRelcacheByRelid(oldidx->tableId);
4305
4306 /*
4307 * CCI here so that subsequent iterations see the oldName in the
4308 * catalog and can choose a nonconflicting name for their oldName.
4309 * Otherwise, this could lead to conflicts if a table has two indexes
4310 * whose names are equal for the first NAMEDATALEN-minus-a-few
4311 * characters.
4312 */
4314 }
4315
4316 /* Commit this transaction and make index swaps visible */
4319
4320 /*
4321 * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
4322 * real need for that, because we only acquire an Xid after the wait is
4323 * done, and that lasts for a very short period.
4324 */
4325
4326 /*
4327 * Phase 5 of REINDEX CONCURRENTLY
4328 *
4329 * Mark the old indexes as dead. First we must wait until no running
4330 * transaction could be using the index for a query. See also
4331 * index_drop() for more details.
4332 */
4333
4334 INJECTION_POINT("reindex-relation-concurrently-before-set-dead", NULL);
4338
4339 foreach(lc, indexIds)
4340 {
4341 ReindexIndexInfo *oldidx = lfirst(lc);
4342
4343 /*
4344 * Check for user-requested abort. This is inside a transaction so as
4345 * xact.c does not issue a useless WARNING, and ensures that
4346 * session-level locks are cleaned up on abort.
4347 */
4349
4350 /*
4351 * Updating pg_index might involve TOAST table access, so ensure we
4352 * have a valid snapshot.
4353 */
4355
4356 index_concurrently_set_dead(oldidx->tableId, oldidx->indexId);
4357
4359 }
4360
4361 /* Commit this transaction to make the updates visible. */
4364
4365 /*
4366 * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
4367 * real need for that, because we only acquire an Xid after the wait is
4368 * done, and that lasts for a very short period.
4369 */
4370
4371 /*
4372 * Phase 6 of REINDEX CONCURRENTLY
4373 *
4374 * Drop the old indexes.
4375 */
4376
4380
4382
4383 {
4385
4386 foreach(lc, indexIds)
4387 {
4388 ReindexIndexInfo *idx = lfirst(lc);
4389 ObjectAddress object;
4390
4391 object.classId = RelationRelationId;
4392 object.objectId = idx->indexId;
4393 object.objectSubId = 0;
4394
4395 add_exact_object_address(&object, objects);
4396 }
4397
4398 /*
4399 * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
4400 * right lock level.
4401 */
4404 }
4405
4408
4409 /*
4410 * Finally, release the session-level lock on the table.
4411 */
4412 foreach(lc, relationLocks)
4413 {
4414 LockRelId *lockrelid = (LockRelId *) lfirst(lc);
4415
4417 }
4418
4419 /* Start a new transaction to finish process properly */
4421
4422 /* Log what we did */
4423 if ((params->options & REINDEXOPT_VERBOSE) != 0)
4424 {
4425 if (relkind == RELKIND_INDEX)
4426 ereport(INFO,
4427 (errmsg("index \"%s.%s\" was reindexed",
4428 relationNamespace, relationName),
4429 errdetail("%s.",
4430 pg_rusage_show(&ru0))));
4431 else
4432 {
4433 foreach(lc, newIndexIds)
4434 {
4435 ReindexIndexInfo *idx = lfirst(lc);
4436 Oid indOid = idx->indexId;
4437
4438 ereport(INFO,
4439 (errmsg("index \"%s.%s\" was reindexed",
4441 get_rel_name(indOid))));
4442 /* Don't show rusage here, since it's not per index. */
4443 }
4444
4445 ereport(INFO,
4446 (errmsg("table \"%s.%s\" was reindexed",
4447 relationNamespace, relationName),
4448 errdetail("%s.",
4449 pg_rusage_show(&ru0))));
4450 }
4451 }
4452
4453 MemoryContextDelete(private_context);
4454
4456
4457 return true;
4458}
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:262
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:261
bool IsSystemRelation(Relation relation)
Definition: catalog.c:74
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:383
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2709
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2664
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:97
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:92
void EventTriggerCollectSimpleCommand(ObjectAddress address, ObjectAddress secondaryObject, Node *parsetree)
#define palloc_object(type)
Definition: fe_memutils.h:74
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1821
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1550
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
Definition: index.c:1298
void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:911
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
const ObjectAddress InvalidObjectAddress
@ DROP_RESTRICT
Definition: parsenodes.h:2425
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define list_make1_oid(x1)
Definition: pg_list.h:242
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
#define PROGRESS_CREATEIDX_PHASE_WAIT_4
Definition: progress.h:120
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:114
#define PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY
Definition: progress.h:133
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:116
#define PROGRESS_CREATEIDX_PHASE_WAIT_5
Definition: progress.h:121
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5205
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:5092
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:60

References AccessExclusiveLock, add_exact_object_address(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate, Assert(), AtEOXact_GUC(), CacheInvalidateRelcacheByRelid(), CHECK_FOR_INTERRUPTS, ChooseRelationName(), ObjectAddress::classId, CommandCounterIncrement(), CommitTransactionCommand(), LockRelId::dbId, DROP_RESTRICT, elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, EventTriggerCollectSimpleCommand(), forboth, get_index_isvalid(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_relkind(), get_tablespace_name(), GetTransactionSnapshot(), GetUserIdAndSecContext(), idx(), index_close(), index_concurrently_build(), index_concurrently_create_copy(), index_concurrently_set_dead(), index_concurrently_swap(), index_open(), IndexGetRelation(), INFO, INJECTION_POINT, InvalidObjectAddress, IsCatalogRelationOid(), IsSystemRelation(), IsToastNamespace(), lappend(), lappend_oid(), lfirst, lfirst_oid, list_make1_oid, LockRelationIdForSession(), LockInfoData::lockRelId, MemoryContextDelete(), MemoryContextSwitchTo(), new_object_addresses(), NewGUCNestLevel(), NIL, NoLock, ObjectAddressSet, OidIsValid, ReindexParams::options, palloc_object, PERFORM_DELETION_CONCURRENT_LOCK, PERFORM_DELETION_INTERNAL, performMultipleDeletions(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PopActiveSnapshot(), PortalContext, PROGRESS_COMMAND_CREATE_INDEX, PROGRESS_CREATEIDX_ACCESS_METHOD_OID, PROGRESS_CREATEIDX_COMMAND, PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY, PROGRESS_CREATEIDX_INDEX_OID, PROGRESS_CREATEIDX_PHASE, PROGRESS_CREATEIDX_PHASE_BUILD, PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN, PROGRESS_CREATEIDX_PHASE_WAIT_1, PROGRESS_CREATEIDX_PHASE_WAIT_2, PROGRESS_CREATEIDX_PHASE_WAIT_3, PROGRESS_CREATEIDX_PHASE_WAIT_4, PROGRESS_CREATEIDX_PHASE_WAIT_5, PushActiveSnapshot(), RelationData::rd_index, RelationData::rd_lockInfo, RelationData::rd_rel, RegisterSnapshot(), REINDEXOPT_MISSING_OK, REINDEXOPT_VERBOSE, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RelationGetRelationName, RelationGetRelid, LockRelId::relId, RestrictSearchPath(), SECURITY_RESTRICTED_OPERATION, set_indexsafe_procflags(), SET_LOCKTAG_RELATION, SetUserIdAndSecContext(), ShareLock, ShareUpdateExclusiveLock, StartTransactionCommand(), stmt, table_close(), table_open(), ReindexParams::tablespaceOid, try_table_open(), UnlockRelationIdForSession(), UnregisterSnapshot(), validate_index(), WaitForLockersMultiple(), WaitForOlderSnapshots(), WARNING, and SnapshotData::xmin.

Referenced by ReindexIndex(), ReindexMultipleInternal(), and ReindexTable().

◆ ReindexTable()

static Oid ReindexTable ( const ReindexStmt stmt,
const ReindexParams params,
bool  isTopLevel 
)
static

Definition at line 3071 of file indexcmds.c.

3072{
3073 Oid heapOid;
3074 bool result;
3075 const RangeVar *relation = stmt->relation;
3076
3077 /*
3078 * The lock level used here should match reindex_relation().
3079 *
3080 * If it's a temporary table, we will perform a non-concurrent reindex,
3081 * even if CONCURRENTLY was requested. In that case, reindex_relation()
3082 * will upgrade the lock, but that's OK, because other sessions can't hold
3083 * locks on our temporary table.
3084 */
3085 heapOid = RangeVarGetRelidExtended(relation,
3086 (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
3088 0,
3090
3091 if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
3092 ReindexPartitions(stmt, heapOid, params, isTopLevel);
3093 else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3094 get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
3095 {
3096 result = ReindexRelationConcurrently(stmt, heapOid, params);
3097
3098 if (!result)
3100 (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
3101 relation->relname)));
3102 }
3103 else
3104 {
3105 ReindexParams newparams = *params;
3106
3108 result = reindex_relation(stmt, heapOid,
3111 &newparams);
3112 if (!result)
3114 (errmsg("table \"%s\" has no indexes to reindex",
3115 relation->relname)));
3116 }
3117
3118 return heapOid;
3119}
void RangeVarCallbackMaintainsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:19522

References ereport, errmsg(), get_rel_persistence(), get_rel_relkind(), NOTICE, ReindexParams::options, ReindexIndexCallbackState::params, RangeVarCallbackMaintainsTable(), RangeVarGetRelidExtended(), REINDEX_REL_CHECK_CONSTRAINTS, REINDEX_REL_PROCESS_TOAST, reindex_relation(), REINDEXOPT_CONCURRENTLY, REINDEXOPT_REPORT_PROGRESS, ReindexPartitions(), ReindexRelationConcurrently(), RangeVar::relname, ShareLock, ShareUpdateExclusiveLock, and stmt.

Referenced by ExecReindex().

◆ ResolveOpClass()

Oid ResolveOpClass ( const List opclass,
Oid  attrType,
const char *  accessMethodName,
Oid  accessMethodId 
)

Definition at line 2280 of file indexcmds.c.

2282{
2283 char *schemaname;
2284 char *opcname;
2285 HeapTuple tuple;
2286 Form_pg_opclass opform;
2287 Oid opClassId,
2288 opInputType;
2289
2290 if (opclass == NIL)
2291 {
2292 /* no operator class specified, so find the default */
2293 opClassId = GetDefaultOpClass(attrType, accessMethodId);
2294 if (!OidIsValid(opClassId))
2295 ereport(ERROR,
2296 (errcode(ERRCODE_UNDEFINED_OBJECT),
2297 errmsg("data type %s has no default operator class for access method \"%s\"",
2298 format_type_be(attrType), accessMethodName),
2299 errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
2300 return opClassId;
2301 }
2302
2303 /*
2304 * Specific opclass name given, so look up the opclass.
2305 */
2306
2307 /* deconstruct the name list */
2308 DeconstructQualifiedName(opclass, &schemaname, &opcname);
2309
2310 if (schemaname)
2311 {
2312 /* Look in specific schema only */
2313 Oid namespaceId;
2314
2315 namespaceId = LookupExplicitNamespace(schemaname, false);
2316 tuple = SearchSysCache3(CLAAMNAMENSP,
2317 ObjectIdGetDatum(accessMethodId),
2318 PointerGetDatum(opcname),
2319 ObjectIdGetDatum(namespaceId));
2320 }
2321 else
2322 {
2323 /* Unqualified opclass name, so search the search path */
2324 opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
2325 if (!OidIsValid(opClassId))
2326 ereport(ERROR,
2327 (errcode(ERRCODE_UNDEFINED_OBJECT),
2328 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2329 opcname, accessMethodName)));
2330 tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
2331 }
2332
2333 if (!HeapTupleIsValid(tuple))
2334 ereport(ERROR,
2335 (errcode(ERRCODE_UNDEFINED_OBJECT),
2336 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2337 NameListToString(opclass), accessMethodName)));
2338
2339 /*
2340 * Verify that the index operator class accepts this datatype. Note we
2341 * will accept binary compatibility.
2342 */
2343 opform = (Form_pg_opclass) GETSTRUCT(tuple);
2344 opClassId = opform->oid;
2345 opInputType = opform->opcintype;
2346
2347 if (!IsBinaryCoercible(attrType, opInputType))
2348 ereport(ERROR,
2349 (errcode(ERRCODE_DATATYPE_MISMATCH),
2350 errmsg("operator class \"%s\" does not accept data type %s",
2351 NameListToString(opclass), format_type_be(attrType))));
2352
2353 ReleaseSysCache(tuple);
2354
2355 return opClassId;
2356}
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2365
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:2188
char * NameListToString(const List *names)
Definition: namespace.c:3664
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:3455
void DeconstructQualifiedName(const List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:3371
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:240

References DeconstructQualifiedName(), ereport, errcode(), errhint(), errmsg(), ERROR, format_type_be(), GetDefaultOpClass(), GETSTRUCT(), HeapTupleIsValid, IsBinaryCoercible(), LookupExplicitNamespace(), NameListToString(), NIL, ObjectIdGetDatum(), OidIsValid, OpclassnameGetOpcid(), PointerGetDatum(), ReleaseSysCache(), SearchSysCache1(), and SearchSysCache3().

Referenced by ComputeIndexAttrs(), and ComputePartitionAttrs().

◆ set_indexsafe_procflags()

static void set_indexsafe_procflags ( void  )
inlinestatic

Definition at line 4637 of file indexcmds.c.

4638{
4639 /*
4640 * This should only be called before installing xid or xmin in MyProc;
4641 * otherwise, concurrent processes could see an Xmin that moves backwards.
4642 */
4645
4646 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
4649 LWLockRelease(ProcArrayLock);
4650}
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1178
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1898
@ LW_EXCLUSIVE
Definition: lwlock.h:112
#define PROC_IN_SAFE_IC
Definition: proc.h:59
PROC_HDR * ProcGlobal
Definition: proc.c:79
uint8 statusFlags
Definition: proc.h:259
int pgxactoff
Definition: proc.h:201
TransactionId xid
Definition: proc.h:189
uint8 * statusFlags
Definition: proc.h:403

References Assert(), InvalidTransactionId, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyProc, PGPROC::pgxactoff, PROC_IN_SAFE_IC, ProcGlobal, PGPROC::statusFlags, PROC_HDR::statusFlags, PGPROC::xid, and PGPROC::xmin.

Referenced by DefineIndex(), and ReindexRelationConcurrently().

◆ update_relispartition()

static void update_relispartition ( Oid  relationId,
bool  newval 
)
static

Definition at line 4599 of file indexcmds.c.

4600{
4601 HeapTuple tup;
4602 Relation classRel;
4603 ItemPointerData otid;
4604
4605 classRel = table_open(RelationRelationId, RowExclusiveLock);
4606 tup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relationId));
4607 if (!HeapTupleIsValid(tup))
4608 elog(ERROR, "cache lookup failed for relation %u", relationId);
4609 otid = tup->t_self;
4610 Assert(((Form_pg_class) GETSTRUCT(tup))->relispartition != newval);
4611 ((Form_pg_class) GETSTRUCT(tup))->relispartition = newval;
4612 CatalogTupleUpdate(classRel, &otid, tup);
4613 UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
4614 heap_freetuple(tup);
4615 table_close(classRel, RowExclusiveLock);
4616}
#define newval
void UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition: lmgr.c:601
#define InplaceUpdateTupleLock
Definition: lockdefs.h:48
HeapTuple SearchSysCacheLockedCopy1(int cacheId, Datum key1)
Definition: syscache.c:399

References Assert(), CatalogTupleUpdate(), elog, ERROR, GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, newval, ObjectIdGetDatum(), RowExclusiveLock, SearchSysCacheLockedCopy1(), HeapTupleData::t_self, table_close(), table_open(), and UnlockTuple().

Referenced by IndexSetParentIndex().

◆ WaitForOlderSnapshots()

void WaitForOlderSnapshots ( TransactionId  limitXmin,
bool  progress 
)

Definition at line 435 of file indexcmds.c.

436{
437 int n_old_snapshots;
438 int i;
439 VirtualTransactionId *old_snapshots;
440
441 old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
444 &n_old_snapshots);
445 if (progress)
447
448 for (i = 0; i < n_old_snapshots; i++)
449 {
450 if (!VirtualTransactionIdIsValid(old_snapshots[i]))
451 continue; /* found uninteresting in previous cycle */
452
453 if (i > 0)
454 {
455 /* see if anything's changed ... */
456 VirtualTransactionId *newer_snapshots;
457 int n_newer_snapshots;
458 int j;
459 int k;
460
461 newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
462 true, false,
465 &n_newer_snapshots);
466 for (j = i; j < n_old_snapshots; j++)
467 {
468 if (!VirtualTransactionIdIsValid(old_snapshots[j]))
469 continue; /* found uninteresting in previous cycle */
470 for (k = 0; k < n_newer_snapshots; k++)
471 {
472 if (VirtualTransactionIdEquals(old_snapshots[j],
473 newer_snapshots[k]))
474 break;
475 }
476 if (k >= n_newer_snapshots) /* not there anymore */
477 SetInvalidVirtualTransactionId(old_snapshots[j]);
478 }
479 pfree(newer_snapshots);
480 }
481
482 if (VirtualTransactionIdIsValid(old_snapshots[i]))
483 {
484 /* If requested, publish who we're going to wait for. */
485 if (progress)
486 {
487 PGPROC *holder = ProcNumberGetProc(old_snapshots[i].procNumber);
488
489 if (holder)
491 holder->pid);
492 }
493 VirtualXactLock(old_snapshots[i], true);
494 }
495
496 if (progress)
498 }
499}
bool VirtualXactLock(VirtualTransactionId vxid, bool wait)
Definition: lock.c:4743
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:69
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:73
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:76
static int progress
Definition: pgbench.c:262
#define PROC_IN_VACUUM
Definition: proc.h:58
#define PROC_IS_AUTOVACUUM
Definition: proc.h:57
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:3287
PGPROC * ProcNumberGetProc(ProcNumber procNumber)
Definition: procarray.c:3101
#define PROGRESS_WAITFOR_DONE
Definition: progress.h:137
#define PROGRESS_WAITFOR_TOTAL
Definition: progress.h:136
#define PROGRESS_WAITFOR_CURRENT_PID
Definition: progress.h:138
Definition: proc.h:179
int pid
Definition: proc.h:199

References GetCurrentVirtualXIDs(), i, j, pfree(), pgstat_progress_update_param(), PGPROC::pid, PROC_IN_SAFE_IC, PROC_IN_VACUUM, PROC_IS_AUTOVACUUM, ProcNumberGetProc(), progress, PROGRESS_WAITFOR_CURRENT_PID, PROGRESS_WAITFOR_DONE, PROGRESS_WAITFOR_TOTAL, SetInvalidVirtualTransactionId, VirtualTransactionIdEquals, VirtualTransactionIdIsValid, and VirtualXactLock().

Referenced by ATExecDetachPartitionFinalize(), DefineIndex(), and ReindexRelationConcurrently().