PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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/dbcommands.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 (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 (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 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(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}
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
int16_t int16
Definition: c.h:497
uint16_t uint16
Definition: c.h:501
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:149
#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:3583
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
static void ComputeIndexAttrs(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:1870
static bool CompareOpclassOptions(const Datum *opts1, const Datum *opts2, int natts)
Definition: indexcmds.c:362
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:1304
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:1062
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1498
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:2146
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:327
uintptr_t Datum
Definition: postgres.h:69
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5650
bool amsummarizing
Definition: amapi.h:280
bool amcanorder
Definition: amapi.h:244
Oid * ii_ExclusionOps
Definition: execnodes.h:203
TupleDesc rd_att
Definition: rel.h:112
Definition: c.h:697
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:704
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:631
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 1843 of file indexcmds.c.

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

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 2729 of file indexcmds.c.

2730{
2731 List *result = NIL;
2732 ListCell *lc;
2733
2734 foreach(lc, indexElems)
2735 {
2736 IndexElem *ielem = (IndexElem *) lfirst(lc);
2737 const char *origname;
2738 const char *curname;
2739 int i;
2740 char buf[NAMEDATALEN];
2741
2742 /* Get the preliminary name from the IndexElem */
2743 if (ielem->indexcolname)
2744 origname = ielem->indexcolname; /* caller-specified name */
2745 else if (ielem->name)
2746 origname = ielem->name; /* simple column reference */
2747 else
2748 origname = "expr"; /* default name for expression */
2749
2750 /* If it conflicts with any previous column, tweak it */
2751 curname = origname;
2752 for (i = 1;; i++)
2753 {
2754 ListCell *lc2;
2755 char nbuf[32];
2756 int nlen;
2757
2758 foreach(lc2, result)
2759 {
2760 if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2761 break;
2762 }
2763 if (lc2 == NULL)
2764 break; /* found nonconflicting name */
2765
2766 sprintf(nbuf, "%d", i);
2767
2768 /* Ensure generated names are shorter than NAMEDATALEN */
2769 nlen = pg_mbcliplen(origname, strlen(origname),
2770 NAMEDATALEN - 1 - strlen(nbuf));
2771 memcpy(buf, origname, nlen);
2772 strcpy(buf + nlen, nbuf);
2773 curname = buf;
2774 }
2775
2776 /* And attach to the result list */
2777 result = lappend(result, pstrdup(curname));
2778 }
2779 return result;
2780}
List * lappend(List *list, void *datum)
Definition: list.c:339
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1083
char * pstrdup(const char *in)
Definition: mcxt.c:2321
#define NAMEDATALEN
#define lfirst(lc)
Definition: pg_list.h:172
static char * buf
Definition: pg_test_fsync.c:72
#define sprintf
Definition: port.h:241
char * indexcolname
Definition: parsenodes.h:796
char * name
Definition: parsenodes.h:794
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 2640 of file indexcmds.c.

2643{
2644 char *indexname;
2645
2646 if (primary)
2647 {
2648 /* the primary key's name does not depend on the specific column(s) */
2649 indexname = ChooseRelationName(tabname,
2650 NULL,
2651 "pkey",
2652 namespaceId,
2653 true);
2654 }
2655 else if (exclusionOpNames != NIL)
2656 {
2657 indexname = ChooseRelationName(tabname,
2658 ChooseIndexNameAddition(colnames),
2659 "excl",
2660 namespaceId,
2661 true);
2662 }
2663 else if (isconstraint)
2664 {
2665 indexname = ChooseRelationName(tabname,
2666 ChooseIndexNameAddition(colnames),
2667 "key",
2668 namespaceId,
2669 true);
2670 }
2671 else
2672 {
2673 indexname = ChooseRelationName(tabname,
2674 ChooseIndexNameAddition(colnames),
2675 "idx",
2676 namespaceId,
2677 false);
2678 }
2679
2680 return indexname;
2681}
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2604
static char * ChooseIndexNameAddition(const List *colnames)
Definition: indexcmds.c:2695

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

Referenced by DefineIndex().

◆ ChooseIndexNameAddition()

static char * ChooseIndexNameAddition ( const List colnames)
static

Definition at line 2695 of file indexcmds.c.

2696{
2697 char buf[NAMEDATALEN * 2];
2698 int buflen = 0;
2699 ListCell *lc;
2700
2701 buf[0] = '\0';
2702 foreach(lc, colnames)
2703 {
2704 const char *name = (const char *) lfirst(lc);
2705
2706 if (buflen > 0)
2707 buf[buflen++] = '_'; /* insert _ between names */
2708
2709 /*
2710 * At this point we have buflen <= NAMEDATALEN. name should be less
2711 * than NAMEDATALEN already, but use strlcpy for paranoia.
2712 */
2713 strlcpy(buf + buflen, name, NAMEDATALEN);
2714 buflen += strlen(buf + buflen);
2715 if (buflen >= NAMEDATALEN)
2716 break;
2717 }
2718 return pstrdup(buf);
2719}
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 2604 of file indexcmds.c.

2607{
2608 int pass = 0;
2609 char *relname = NULL;
2610 char modlabel[NAMEDATALEN];
2611
2612 /* try the unmodified label first */
2613 strlcpy(modlabel, label, sizeof(modlabel));
2614
2615 for (;;)
2616 {
2617 relname = makeObjectName(name1, name2, modlabel);
2618
2619 if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2620 {
2621 if (!isconstraint ||
2622 !ConstraintNameExists(relname, namespaceid))
2623 break;
2624 }
2625
2626 /* found a conflict, so try a new name component */
2627 pfree(relname);
2628 snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2629 }
2630
2631 return relname;
2632}
#define OidIsValid(objectId)
Definition: c.h:746
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2518
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:2025
static char * label
NameData relname
Definition: pg_class.h:38
bool ConstraintNameExists(const char *conname, Oid namespaceid)
#define snprintf
Definition: port.h:239

References ConstraintNameExists(), get_relname_relid(), label, makeObjectName(), NAMEDATALEN, OidIsValid, pfree(), relname, snprintf, and strlcpy().

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:1149
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
static bool DatumGetBool(Datum X)
Definition: postgres.h:95
Definition: fmgr.h:57

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

Referenced by CheckIndexCompatible().

◆ ComputeIndexAttrs()

static void ComputeIndexAttrs ( 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 1870 of file indexcmds.c.

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

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::name, NewGUCNestLevel(), NIL, IndexElem::nulls_ordering, OidIsValid, IndexElem::opclass, IndexElem::opclassopts, IndexElem::ordering, palloc_array, 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 ( 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 542 of file indexcmds.c.

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

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(), 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, pfree(), 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 2790 of file indexcmds.c.

2791{
2792 ReindexParams params = {0};
2793 ListCell *lc;
2794 bool concurrently = false;
2795 bool verbose = false;
2796 char *tablespacename = NULL;
2797
2798 /* Parse option list */
2799 foreach(lc, stmt->params)
2800 {
2801 DefElem *opt = (DefElem *) lfirst(lc);
2802
2803 if (strcmp(opt->defname, "verbose") == 0)
2804 verbose = defGetBoolean(opt);
2805 else if (strcmp(opt->defname, "concurrently") == 0)
2806 concurrently = defGetBoolean(opt);
2807 else if (strcmp(opt->defname, "tablespace") == 0)
2808 tablespacename = defGetString(opt);
2809 else
2810 ereport(ERROR,
2811 (errcode(ERRCODE_SYNTAX_ERROR),
2812 errmsg("unrecognized REINDEX option \"%s\"",
2813 opt->defname),
2814 parser_errposition(pstate, opt->location)));
2815 }
2816
2817 if (concurrently)
2818 PreventInTransactionBlock(isTopLevel,
2819 "REINDEX CONCURRENTLY");
2820
2821 params.options =
2822 (verbose ? REINDEXOPT_VERBOSE : 0) |
2823 (concurrently ? REINDEXOPT_CONCURRENTLY : 0);
2824
2825 /*
2826 * Assign the tablespace OID to move indexes to, with InvalidOid to do
2827 * nothing.
2828 */
2829 if (tablespacename != NULL)
2830 {
2831 params.tablespaceOid = get_tablespace_oid(tablespacename, false);
2832
2833 /* Check permissions except when moving to database's default */
2834 if (OidIsValid(params.tablespaceOid) &&
2836 {
2837 AclResult aclresult;
2838
2839 aclresult = object_aclcheck(TableSpaceRelationId, params.tablespaceOid,
2841 if (aclresult != ACLCHECK_OK)
2844 }
2845 }
2846 else
2847 params.tablespaceOid = InvalidOid;
2848
2849 switch (stmt->kind)
2850 {
2852 ReindexIndex(stmt, &params, isTopLevel);
2853 break;
2855 ReindexTable(stmt, &params, isTopLevel);
2856 break;
2860
2861 /*
2862 * This cannot run inside a user transaction block; if we were
2863 * inside a transaction, then its commit- and
2864 * start-transaction-command calls would not have the intended
2865 * effect!
2866 */
2867 PreventInTransactionBlock(isTopLevel,
2868 (stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" :
2869 (stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" :
2870 "REINDEX DATABASE");
2871 ReindexMultipleTables(stmt, &params);
2872 break;
2873 default:
2874 elog(ERROR, "unrecognized object type: %d",
2875 (int) stmt->kind);
2876 break;
2877 }
2878}
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:2885
static void ReindexMultipleTables(const ReindexStmt *stmt, const ReindexParams *params)
Definition: indexcmds.c:3074
static Oid ReindexTable(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:3015
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
@ REINDEX_OBJECT_DATABASE
Definition: parsenodes.h:4067
@ REINDEX_OBJECT_INDEX
Definition: parsenodes.h:4063
@ REINDEX_OBJECT_SCHEMA
Definition: parsenodes.h:4065
@ REINDEX_OBJECT_SYSTEM
Definition: parsenodes.h:4066
@ REINDEX_OBJECT_TABLE
Definition: parsenodes.h:4064
char * defname
Definition: parsenodes.h:826
ParseLoc location
Definition: parsenodes.h:830
Oid tablespaceOid
Definition: index.h:36
bits32 options
Definition: index.h:35
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3648

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 2345 of file indexcmds.c.

2346{
2347 Oid result = InvalidOid;
2348 int nexact = 0;
2349 int ncompatible = 0;
2350 int ncompatiblepreferred = 0;
2351 Relation rel;
2352 ScanKeyData skey[1];
2353 SysScanDesc scan;
2354 HeapTuple tup;
2355 TYPCATEGORY tcategory;
2356
2357 /* If it's a domain, look at the base type instead */
2358 type_id = getBaseType(type_id);
2359
2360 tcategory = TypeCategory(type_id);
2361
2362 /*
2363 * We scan through all the opclasses available for the access method,
2364 * looking for one that is marked default and matches the target type
2365 * (either exactly or binary-compatibly, but prefer an exact match).
2366 *
2367 * We could find more than one binary-compatible match. If just one is
2368 * for a preferred type, use that one; otherwise we fail, forcing the user
2369 * to specify which one he wants. (The preferred-type special case is a
2370 * kluge for varchar: it's binary-compatible to both text and bpchar, so
2371 * we need a tiebreaker.) If we find more than one exact match, then
2372 * someone put bogus entries in pg_opclass.
2373 */
2374 rel = table_open(OperatorClassRelationId, AccessShareLock);
2375
2376 ScanKeyInit(&skey[0],
2377 Anum_pg_opclass_opcmethod,
2378 BTEqualStrategyNumber, F_OIDEQ,
2379 ObjectIdGetDatum(am_id));
2380
2381 scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
2382 NULL, 1, skey);
2383
2384 while (HeapTupleIsValid(tup = systable_getnext(scan)))
2385 {
2386 Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
2387
2388 /* ignore altogether if not a default opclass */
2389 if (!opclass->opcdefault)
2390 continue;
2391 if (opclass->opcintype == type_id)
2392 {
2393 nexact++;
2394 result = opclass->oid;
2395 }
2396 else if (nexact == 0 &&
2397 IsBinaryCoercible(type_id, opclass->opcintype))
2398 {
2399 if (IsPreferredType(tcategory, opclass->opcintype))
2400 {
2401 ncompatiblepreferred++;
2402 result = opclass->oid;
2403 }
2404 else if (ncompatiblepreferred == 0)
2405 {
2406 ncompatible++;
2407 result = opclass->oid;
2408 }
2409 }
2410 }
2411
2412 systable_endscan(scan);
2413
2415
2416 /* raise error if pg_opclass contains inconsistent data */
2417 if (nexact > 1)
2418 ereport(ERROR,
2420 errmsg("there are multiple default operator classes for data type %s",
2421 format_type_be(type_id))));
2422
2423 if (nexact == 1 ||
2424 ncompatiblepreferred == 1 ||
2425 (ncompatiblepreferred == 0 && ncompatible == 1))
2426 return result;
2427
2428 return InvalidOid;
2429}
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
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2661
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
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#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 2447 of file indexcmds.c.

2449{
2450 Oid amid;
2451 Oid opfamily;
2452 Oid opcintype;
2453
2454 Assert(cmptype == COMPARE_EQ || cmptype == COMPARE_OVERLAP || cmptype == COMPARE_CONTAINED_BY);
2455
2456 amid = get_opclass_method(opclass);
2457
2458 *opid = InvalidOid;
2459
2460 if (get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype))
2461 {
2462 /*
2463 * Ask the index AM to translate to its internal stratnum
2464 */
2465 *strat = IndexAmTranslateCompareType(cmptype, amid, opfamily, true);
2466 if (*strat == InvalidStrategy)
2467 ereport(ERROR,
2468 errcode(ERRCODE_UNDEFINED_OBJECT),
2469 cmptype == COMPARE_EQ ? errmsg("could not identify an equality operator for type %s", format_type_be(opcintype)) :
2470 cmptype == COMPARE_OVERLAP ? errmsg("could not identify an overlaps operator for type %s", format_type_be(opcintype)) :
2471 cmptype == COMPARE_CONTAINED_BY ? errmsg("could not identify a contained-by operator for type %s", format_type_be(opcintype)) : 0,
2472 errdetail("Could not translate compare type %d for operator family \"%s\", input type %s, access method \"%s\".",
2473 cmptype, get_opfamily_name(opfamily, false), format_type_be(opcintype), get_am_name(amid)));
2474
2475 /*
2476 * We parameterize rhstype so foreign keys can ask for a <@ operator
2477 * whose rhs matches the aggregate function. For example range_agg
2478 * returns anymultirange.
2479 */
2480 if (!OidIsValid(rhstype))
2481 rhstype = opcintype;
2482 *opid = get_opfamily_member(opfamily, opcintype, rhstype, *strat);
2483 }
2484
2485 if (!OidIsValid(*opid))
2486 ereport(ERROR,
2487 errcode(ERRCODE_UNDEFINED_OBJECT),
2488 cmptype == COMPARE_EQ ? errmsg("could not identify an equality operator for type %s", format_type_be(opcintype)) :
2489 cmptype == COMPARE_OVERLAP ? errmsg("could not identify an overlaps operator for type %s", format_type_be(opcintype)) :
2490 cmptype == COMPARE_CONTAINED_BY ? errmsg("could not identify a contained-by operator for type %s", format_type_be(opcintype)) : 0,
2491 errdetail("There is no suitable operator in operator family \"%s\" for access method \"%s\".",
2492 get_opfamily_name(opfamily, false), get_am_name(amid)));
2493}
StrategyNumber IndexAmTranslateCompareType(CompareType cmptype, Oid amoid, Oid opfamily, bool missing_ok)
Definition: amapi.c:148
@ COMPARE_CONTAINED_BY
Definition: cmptype.h:41
Oid get_opclass_method(Oid opclass)
Definition: lsyscache.c:1352
#define InvalidStrategy
Definition: stratnum.h:24

References Assert(), COMPARE_CONTAINED_BY, COMPARE_EQ, COMPARE_OVERLAP, 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(), InvalidOid, InvalidStrategy, and OidIsValid.

Referenced by ComputeIndexAttrs(), and FindFKPeriodOpers().

◆ IndexSetParentIndex()

void IndexSetParentIndex ( Relation  partitionIdx,
Oid  parentOid 
)

Definition at line 4409 of file indexcmds.c.

4410{
4411 Relation pg_inherits;
4412 ScanKeyData key[2];
4413 SysScanDesc scan;
4414 Oid partRelid = RelationGetRelid(partitionIdx);
4415 HeapTuple tuple;
4416 bool fix_dependencies;
4417
4418 /* Make sure this is an index */
4419 Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
4420 partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
4421
4422 /*
4423 * Scan pg_inherits for rows linking our index to some parent.
4424 */
4425 pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
4426 ScanKeyInit(&key[0],
4427 Anum_pg_inherits_inhrelid,
4428 BTEqualStrategyNumber, F_OIDEQ,
4429 ObjectIdGetDatum(partRelid));
4430 ScanKeyInit(&key[1],
4431 Anum_pg_inherits_inhseqno,
4432 BTEqualStrategyNumber, F_INT4EQ,
4433 Int32GetDatum(1));
4434 scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
4435 NULL, 2, key);
4436 tuple = systable_getnext(scan);
4437
4438 if (!HeapTupleIsValid(tuple))
4439 {
4440 if (parentOid == InvalidOid)
4441 {
4442 /*
4443 * No pg_inherits row, and no parent wanted: nothing to do in this
4444 * case.
4445 */
4446 fix_dependencies = false;
4447 }
4448 else
4449 {
4450 StoreSingleInheritance(partRelid, parentOid, 1);
4451 fix_dependencies = true;
4452 }
4453 }
4454 else
4455 {
4456 Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
4457
4458 if (parentOid == InvalidOid)
4459 {
4460 /*
4461 * There exists a pg_inherits row, which we want to clear; do so.
4462 */
4463 CatalogTupleDelete(pg_inherits, &tuple->t_self);
4464 fix_dependencies = true;
4465 }
4466 else
4467 {
4468 /*
4469 * A pg_inherits row exists. If it's the same we want, then we're
4470 * good; if it differs, that amounts to a corrupt catalog and
4471 * should not happen.
4472 */
4473 if (inhForm->inhparent != parentOid)
4474 {
4475 /* unexpected: we should not get called in this case */
4476 elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
4477 inhForm->inhrelid, inhForm->inhparent);
4478 }
4479
4480 /* already in the right state */
4481 fix_dependencies = false;
4482 }
4483 }
4484
4485 /* done with pg_inherits */
4486 systable_endscan(scan);
4487 relation_close(pg_inherits, RowExclusiveLock);
4488
4489 /* set relhassubclass if an index partition has been added to the parent */
4490 if (OidIsValid(parentOid))
4491 {
4493 SetRelationHasSubclass(parentOid, true);
4494 }
4495
4496 /* set relispartition correctly on the partition */
4497 update_relispartition(partRelid, OidIsValid(parentOid));
4498
4499 if (fix_dependencies)
4500 {
4501 /*
4502 * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4503 * dependencies on the parent index and the table; if removing a
4504 * parent, delete PARTITION dependencies.
4505 */
4506 if (OidIsValid(parentOid))
4507 {
4508 ObjectAddress partIdx;
4509 ObjectAddress parentIdx;
4510 ObjectAddress partitionTbl;
4511
4512 ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4513 ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4514 ObjectAddressSet(partitionTbl, RelationRelationId,
4515 partitionIdx->rd_index->indrelid);
4516 recordDependencyOn(&partIdx, &parentIdx,
4518 recordDependencyOn(&partIdx, &partitionTbl,
4520 }
4521 else
4522 {
4523 deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4524 RelationRelationId,
4526 deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4527 RelationRelationId,
4529 }
4530
4531 /* make our updates visible */
4533 }
4534}
@ 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:4541
void CatalogTupleDelete(Relation heapRel, ItemPointer 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:217
#define RelationGetRelid(relation)
Definition: rel.h:516
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:3637

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 2518 of file indexcmds.c.

2519{
2520 char *name;
2521 int overhead = 0; /* chars needed for label and underscores */
2522 int availchars; /* chars available for name(s) */
2523 int name1chars; /* chars allocated to name1 */
2524 int name2chars; /* chars allocated to name2 */
2525 int ndx;
2526
2527 name1chars = strlen(name1);
2528 if (name2)
2529 {
2530 name2chars = strlen(name2);
2531 overhead++; /* allow for separating underscore */
2532 }
2533 else
2534 name2chars = 0;
2535 if (label)
2536 overhead += strlen(label) + 1;
2537
2538 availchars = NAMEDATALEN - 1 - overhead;
2539 Assert(availchars > 0); /* else caller chose a bad label */
2540
2541 /*
2542 * If we must truncate, preferentially truncate the longer name. This
2543 * logic could be expressed without a loop, but it's simple and obvious as
2544 * a loop.
2545 */
2546 while (name1chars + name2chars > availchars)
2547 {
2548 if (name1chars > name2chars)
2549 name1chars--;
2550 else
2551 name2chars--;
2552 }
2553
2554 name1chars = pg_mbcliplen(name1, name1chars, name1chars);
2555 if (name2)
2556 name2chars = pg_mbcliplen(name2, name2chars, name2chars);
2557
2558 /* Now construct the string using the chosen lengths */
2559 name = palloc(name1chars + name2chars + overhead + 1);
2560 memcpy(name, name1, name1chars);
2561 ndx = name1chars;
2562 if (name2)
2563 {
2564 name[ndx++] = '_';
2565 memcpy(name + ndx, name2, name2chars);
2566 ndx += name2chars;
2567 }
2568 if (label)
2569 {
2570 name[ndx++] = '_';
2571 strcpy(name + ndx, label);
2572 }
2573 else
2574 name[ndx] = '\0';
2575
2576 return name;
2577}
void * palloc(Size size)
Definition: mcxt.c:1939

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 2939 of file indexcmds.c.

2941{
2942 char relkind;
2944 LOCKMODE table_lockmode;
2945 Oid table_oid;
2946
2947 /*
2948 * Lock level here should match table lock in reindex_index() for
2949 * non-concurrent case and table locks used by index_concurrently_*() for
2950 * concurrent case.
2951 */
2952 table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ?
2954
2955 /*
2956 * If we previously locked some other index's heap, and the name we're
2957 * looking up no longer refers to that relation, release the now-useless
2958 * lock.
2959 */
2960 if (relId != oldRelId && OidIsValid(oldRelId))
2961 {
2962 UnlockRelationOid(state->locked_table_oid, table_lockmode);
2963 state->locked_table_oid = InvalidOid;
2964 }
2965
2966 /* If the relation does not exist, there's nothing more to do. */
2967 if (!OidIsValid(relId))
2968 return;
2969
2970 /*
2971 * If the relation does exist, check whether it's an index. But note that
2972 * the relation might have been dropped between the time we did the name
2973 * lookup and now. In that case, there's nothing to do.
2974 */
2975 relkind = get_rel_relkind(relId);
2976 if (!relkind)
2977 return;
2978 if (relkind != RELKIND_INDEX &&
2979 relkind != RELKIND_PARTITIONED_INDEX)
2980 ereport(ERROR,
2981 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2982 errmsg("\"%s\" is not an index", relation->relname)));
2983
2984 /* Check permissions */
2985 table_oid = IndexGetRelation(relId, true);
2986 if (OidIsValid(table_oid))
2987 {
2988 AclResult aclresult;
2989
2990 aclresult = pg_class_aclcheck(table_oid, GetUserId(), ACL_MAINTAIN);
2991 if (aclresult != ACLCHECK_OK)
2992 aclcheck_error(aclresult, OBJECT_INDEX, relation->relname);
2993 }
2994
2995 /* Lock heap before index to avoid deadlock. */
2996 if (relId != oldRelId)
2997 {
2998 /*
2999 * If the OID isn't valid, it means the index was concurrently
3000 * dropped, which is not a problem for us; just return normally.
3001 */
3002 if (OidIsValid(table_oid))
3003 {
3004 LockRelationOid(table_oid, table_lockmode);
3005 state->locked_table_oid = table_oid;
3006 }
3007 }
3008}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4024
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:229
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2143
#define ACL_MAINTAIN
Definition: parsenodes.h:90
@ OBJECT_INDEX
Definition: parsenodes.h:2337
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 3293 of file indexcmds.c.

3294{
3295 ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
3296
3297 Assert(RELKIND_HAS_PARTITIONS(errinfo->relkind));
3298
3299 if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
3300 errcontext("while reindexing partitioned table \"%s.%s\"",
3301 errinfo->relnamespace, errinfo->relname);
3302 else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
3303 errcontext("while reindexing partitioned index \"%s.%s\"",
3304 errinfo->relnamespace, errinfo->relname);
3305}
#define errcontext
Definition: elog.h:197
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 2885 of file indexcmds.c.

2886{
2887 const RangeVar *indexRelation = stmt->relation;
2889 Oid indOid;
2890 char persistence;
2891 char relkind;
2892
2893 /*
2894 * Find and lock index, and check permissions on table; use callback to
2895 * obtain lock on table first, to avoid deadlock hazard. The lock level
2896 * used here must match the index lock obtained in reindex_index().
2897 *
2898 * If it's a temporary index, we will perform a non-concurrent reindex,
2899 * even if CONCURRENTLY was requested. In that case, reindex_index() will
2900 * upgrade the lock, but that's OK, because other sessions can't hold
2901 * locks on our temporary table.
2902 */
2903 state.params = *params;
2904 state.locked_table_oid = InvalidOid;
2905 indOid = RangeVarGetRelidExtended(indexRelation,
2908 0,
2910 &state);
2911
2912 /*
2913 * Obtain the current persistence and kind of the existing index. We
2914 * already hold a lock on the index.
2915 */
2916 persistence = get_rel_persistence(indOid);
2917 relkind = get_rel_relkind(indOid);
2918
2919 if (relkind == RELKIND_PARTITIONED_INDEX)
2920 ReindexPartitions(stmt, indOid, params, isTopLevel);
2921 else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2922 persistence != RELPERSISTENCE_TEMP)
2924 else
2925 {
2926 ReindexParams newparams = *params;
2927
2929 reindex_index(stmt, indOid, false, persistence, &newparams);
2930 }
2931}
void reindex_index(const ReindexStmt *stmt, Oid indexId, bool skip_constraint_checks, char persistence, const ReindexParams *params)
Definition: index.c:3608
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
static bool ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const ReindexParams *params)
Definition: indexcmds.c:3534
static void ReindexPartitions(const ReindexStmt *stmt, Oid relid, const ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:3314
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2939
#define AccessExclusiveLock
Definition: lockdefs.h:43
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:441
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 3408 of file indexcmds.c.

3409{
3410 ListCell *l;
3411
3414
3415 foreach(l, relids)
3416 {
3417 Oid relid = lfirst_oid(l);
3418 char relkind;
3419 char relpersistence;
3420
3422
3423 /* functions in indexes may want a snapshot set */
3425
3426 /* check if the relation still exists */
3427 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
3428 {
3431 continue;
3432 }
3433
3434 /*
3435 * Check permissions except when moving to database's default if a new
3436 * tablespace is chosen. Note that this check also happens in
3437 * ExecReindex(), but we do an extra check here as this runs across
3438 * multiple transactions.
3439 */
3440 if (OidIsValid(params->tablespaceOid) &&
3442 {
3443 AclResult aclresult;
3444
3445 aclresult = object_aclcheck(TableSpaceRelationId, params->tablespaceOid,
3447 if (aclresult != ACLCHECK_OK)
3450 }
3451
3452 relkind = get_rel_relkind(relid);
3453 relpersistence = get_rel_persistence(relid);
3454
3455 /*
3456 * Partitioned tables and indexes can never be processed directly, and
3457 * a list of their leaves should be built first.
3458 */
3459 Assert(!RELKIND_HAS_PARTITIONS(relkind));
3460
3461 if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3462 relpersistence != RELPERSISTENCE_TEMP)
3463 {
3464 ReindexParams newparams = *params;
3465
3466 newparams.options |= REINDEXOPT_MISSING_OK;
3467 (void) ReindexRelationConcurrently(stmt, relid, &newparams);
3468 if (ActiveSnapshotSet())
3470 /* ReindexRelationConcurrently() does the verbose output */
3471 }
3472 else if (relkind == RELKIND_INDEX)
3473 {
3474 ReindexParams newparams = *params;
3475
3476 newparams.options |=
3478 reindex_index(stmt, relid, false, relpersistence, &newparams);
3480 /* reindex_index() does the verbose output */
3481 }
3482 else
3483 {
3484 bool result;
3485 ReindexParams newparams = *params;
3486
3487 newparams.options |=
3489 result = reindex_relation(stmt, relid,
3492 &newparams);
3493
3494 if (result && (params->options & REINDEXOPT_VERBOSE) != 0)
3495 ereport(INFO,
3496 (errmsg("table \"%s.%s\" was reindexed",
3498 get_rel_name(relid))));
3499
3501 }
3502
3504 }
3505
3507}
#define INFO
Definition: elog.h:34
bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params)
Definition: index.c:3948
#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:2068
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:2092
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:799
#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 3074 of file indexcmds.c.

3075{
3076
3077 Oid objectOid;
3078 Relation relationRelation;
3079 TableScanDesc scan;
3080 ScanKeyData scan_keys[1];
3081 HeapTuple tuple;
3082 MemoryContext private_context;
3083 MemoryContext old;
3084 List *relids = NIL;
3085 int num_keys;
3086 bool concurrent_warning = false;
3087 bool tablespace_warning = false;
3088 const char *objectName = stmt->name;
3089 const ReindexObjectType objectKind = stmt->kind;
3090
3091 Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
3092 objectKind == REINDEX_OBJECT_SYSTEM ||
3093 objectKind == REINDEX_OBJECT_DATABASE);
3094
3095 /*
3096 * This matches the options enforced by the grammar, where the object name
3097 * is optional for DATABASE and SYSTEM.
3098 */
3099 Assert(objectName || objectKind != REINDEX_OBJECT_SCHEMA);
3100
3101 if (objectKind == REINDEX_OBJECT_SYSTEM &&
3102 (params->options & REINDEXOPT_CONCURRENTLY) != 0)
3103 ereport(ERROR,
3104 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3105 errmsg("cannot reindex system catalogs concurrently")));
3106
3107 /*
3108 * Get OID of object to reindex, being the database currently being used
3109 * by session for a database or for system catalogs, or the schema defined
3110 * by caller. At the same time do permission checks that need different
3111 * processing depending on the object type.
3112 */
3113 if (objectKind == REINDEX_OBJECT_SCHEMA)
3114 {
3115 objectOid = get_namespace_oid(objectName, false);
3116
3117 if (!object_ownercheck(NamespaceRelationId, objectOid, GetUserId()) &&
3118 !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
3120 objectName);
3121 }
3122 else
3123 {
3124 objectOid = MyDatabaseId;
3125
3126 if (objectName && strcmp(objectName, get_database_name(objectOid)) != 0)
3127 ereport(ERROR,
3128 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3129 errmsg("can only reindex the currently open database")));
3130 if (!object_ownercheck(DatabaseRelationId, objectOid, GetUserId()) &&
3131 !has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN))
3133 get_database_name(objectOid));
3134 }
3135
3136 /*
3137 * Create a memory context that will survive forced transaction commits we
3138 * do below. Since it is a child of PortalContext, it will go away
3139 * eventually even if we suffer an error; there's no need for special
3140 * abort cleanup logic.
3141 */
3142 private_context = AllocSetContextCreate(PortalContext,
3143 "ReindexMultipleTables",
3145
3146 /*
3147 * Define the search keys to find the objects to reindex. For a schema, we
3148 * select target relations using relnamespace, something not necessary for
3149 * a database-wide operation.
3150 */
3151 if (objectKind == REINDEX_OBJECT_SCHEMA)
3152 {
3153 num_keys = 1;
3154 ScanKeyInit(&scan_keys[0],
3155 Anum_pg_class_relnamespace,
3156 BTEqualStrategyNumber, F_OIDEQ,
3157 ObjectIdGetDatum(objectOid));
3158 }
3159 else
3160 num_keys = 0;
3161
3162 /*
3163 * Scan pg_class to build a list of the relations we need to reindex.
3164 *
3165 * We only consider plain relations and materialized views here (toast
3166 * rels will be processed indirectly by reindex_relation).
3167 */
3168 relationRelation = table_open(RelationRelationId, AccessShareLock);
3169 scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
3170 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3171 {
3172 Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
3173 Oid relid = classtuple->oid;
3174
3175 /*
3176 * Only regular tables and matviews can have indexes, so ignore any
3177 * other kind of relation.
3178 *
3179 * Partitioned tables/indexes are skipped but matching leaf partitions
3180 * are processed.
3181 */
3182 if (classtuple->relkind != RELKIND_RELATION &&
3183 classtuple->relkind != RELKIND_MATVIEW)
3184 continue;
3185
3186 /* Skip temp tables of other backends; we can't reindex them at all */
3187 if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
3188 !isTempNamespace(classtuple->relnamespace))
3189 continue;
3190
3191 /*
3192 * Check user/system classification. SYSTEM processes all the
3193 * catalogs, and DATABASE processes everything that's not a catalog.
3194 */
3195 if (objectKind == REINDEX_OBJECT_SYSTEM &&
3196 !IsCatalogRelationOid(relid))
3197 continue;
3198 else if (objectKind == REINDEX_OBJECT_DATABASE &&
3199 IsCatalogRelationOid(relid))
3200 continue;
3201
3202 /*
3203 * We already checked privileges on the database or schema, but we
3204 * further restrict reindexing shared catalogs to roles with the
3205 * MAINTAIN privilege on the relation.
3206 */
3207 if (classtuple->relisshared &&
3209 continue;
3210
3211 /*
3212 * Skip system tables, since index_create() would reject indexing them
3213 * concurrently (and it would likely fail if we tried).
3214 */
3215 if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3216 IsCatalogRelationOid(relid))
3217 {
3218 if (!concurrent_warning)
3220 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3221 errmsg("cannot reindex system catalogs concurrently, skipping all")));
3222 concurrent_warning = true;
3223 continue;
3224 }
3225
3226 /*
3227 * If a new tablespace is set, check if this relation has to be
3228 * skipped.
3229 */
3230 if (OidIsValid(params->tablespaceOid))
3231 {
3232 bool skip_rel = false;
3233
3234 /*
3235 * Mapped relations cannot be moved to different tablespaces (in
3236 * particular this eliminates all shared catalogs.).
3237 */
3238 if (RELKIND_HAS_STORAGE(classtuple->relkind) &&
3239 !RelFileNumberIsValid(classtuple->relfilenode))
3240 skip_rel = true;
3241
3242 /*
3243 * A system relation is always skipped, even with
3244 * allow_system_table_mods enabled.
3245 */
3246 if (IsSystemClass(relid, classtuple))
3247 skip_rel = true;
3248
3249 if (skip_rel)
3250 {
3251 if (!tablespace_warning)
3253 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3254 errmsg("cannot move system relations, skipping all")));
3255 tablespace_warning = true;
3256 continue;
3257 }
3258 }
3259
3260 /* Save the list of relation OIDs in private context */
3261 old = MemoryContextSwitchTo(private_context);
3262
3263 /*
3264 * We always want to reindex pg_class first if it's selected to be
3265 * reindexed. This ensures that if there is any corruption in
3266 * pg_class' indexes, they will be fixed before we process any other
3267 * tables. This is critical because reindexing itself will try to
3268 * update pg_class.
3269 */
3270 if (relid == RelationRelationId)
3271 relids = lcons_oid(relid, relids);
3272 else
3273 relids = lappend_oid(relids, relid);
3274
3276 }
3277 table_endscan(scan);
3278 table_close(relationRelation, AccessShareLock);
3279
3280 /*
3281 * Process each relation listed in a separate transaction. Note that this
3282 * commits and then starts a new transaction immediately.
3283 */
3284 ReindexMultipleInternal(stmt, relids, params);
3285
3286 MemoryContextDelete(private_context);
3287}
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5268
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4075
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:121
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:86
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3188
#define WARNING
Definition: elog.h:36
Oid MyDatabaseId
Definition: globals.c:95
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1314
static void ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids, const ReindexParams *params)
Definition: indexcmds.c:3408
List * lcons_oid(Oid datum, List *list)
Definition: list.c:531
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:485
MemoryContext PortalContext
Definition: mcxt.c:174
#define AllocSetContextCreate
Definition: memutils.h:149
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:190
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3649
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3535
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
@ OBJECT_DATABASE
Definition: parsenodes.h:2326
ReindexObjectType
Definition: parsenodes.h:4062
FormData_pg_class * Form_pg_class
Definition: pg_class.h:156
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:979

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 3314 of file indexcmds.c.

3315{
3316 List *partitions = NIL;
3317 char relkind = get_rel_relkind(relid);
3318 char *relname = get_rel_name(relid);
3319 char *relnamespace = get_namespace_name(get_rel_namespace(relid));
3320 MemoryContext reindex_context;
3321 List *inhoids;
3322 ListCell *lc;
3323 ErrorContextCallback errcallback;
3324 ReindexErrorInfo errinfo;
3325
3326 Assert(RELKIND_HAS_PARTITIONS(relkind));
3327
3328 /*
3329 * Check if this runs in a transaction block, with an error callback to
3330 * provide more context under which a problem happens.
3331 */
3332 errinfo.relname = pstrdup(relname);
3333 errinfo.relnamespace = pstrdup(relnamespace);
3334 errinfo.relkind = relkind;
3335 errcallback.callback = reindex_error_callback;
3336 errcallback.arg = &errinfo;
3337 errcallback.previous = error_context_stack;
3338 error_context_stack = &errcallback;
3339
3340 PreventInTransactionBlock(isTopLevel,
3341 relkind == RELKIND_PARTITIONED_TABLE ?
3342 "REINDEX TABLE" : "REINDEX INDEX");
3343
3344 /* Pop the error context stack */
3345 error_context_stack = errcallback.previous;
3346
3347 /*
3348 * Create special memory context for cross-transaction storage.
3349 *
3350 * Since it is a child of PortalContext, it will go away eventually even
3351 * if we suffer an error so there is no need for special abort cleanup
3352 * logic.
3353 */
3354 reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
3356
3357 /* ShareLock is enough to prevent schema modifications */
3358 inhoids = find_all_inheritors(relid, ShareLock, NULL);
3359
3360 /*
3361 * The list of relations to reindex are the physical partitions of the
3362 * tree so discard any partitioned table or index.
3363 */
3364 foreach(lc, inhoids)
3365 {
3366 Oid partoid = lfirst_oid(lc);
3367 char partkind = get_rel_relkind(partoid);
3368 MemoryContext old_context;
3369
3370 /*
3371 * This discards partitioned tables, partitioned indexes and foreign
3372 * tables.
3373 */
3374 if (!RELKIND_HAS_STORAGE(partkind))
3375 continue;
3376
3377 Assert(partkind == RELKIND_INDEX ||
3378 partkind == RELKIND_RELATION);
3379
3380 /* Save partition OID */
3381 old_context = MemoryContextSwitchTo(reindex_context);
3382 partitions = lappend_oid(partitions, partoid);
3383 MemoryContextSwitchTo(old_context);
3384 }
3385
3386 /*
3387 * Process each partition listed in a separate transaction. Note that
3388 * this commits and then starts a new transaction immediately.
3389 */
3391
3392 /*
3393 * Clean up working storage --- note we must do this after
3394 * StartTransactionCommand, else we might be trying to delete the active
3395 * context!
3396 */
3397 MemoryContextDelete(reindex_context);
3398}
ErrorContextCallback * error_context_stack
Definition: elog.c:95
static void reindex_error_callback(void *arg)
Definition: indexcmds.c:3293
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:180
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 3534 of file indexcmds.c.

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

3016{
3017 Oid heapOid;
3018 bool result;
3019 const RangeVar *relation = stmt->relation;
3020
3021 /*
3022 * The lock level used here should match reindex_relation().
3023 *
3024 * If it's a temporary table, we will perform a non-concurrent reindex,
3025 * even if CONCURRENTLY was requested. In that case, reindex_relation()
3026 * will upgrade the lock, but that's OK, because other sessions can't hold
3027 * locks on our temporary table.
3028 */
3029 heapOid = RangeVarGetRelidExtended(relation,
3030 (params->options & REINDEXOPT_CONCURRENTLY) != 0 ?
3032 0,
3034
3035 if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
3036 ReindexPartitions(stmt, heapOid, params, isTopLevel);
3037 else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3038 get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
3039 {
3040 result = ReindexRelationConcurrently(stmt, heapOid, params);
3041
3042 if (!result)
3044 (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
3045 relation->relname)));
3046 }
3047 else
3048 {
3049 ReindexParams newparams = *params;
3050
3052 result = reindex_relation(stmt, heapOid,
3055 &newparams);
3056 if (!result)
3058 (errmsg("table \"%s\" has no indexes to reindex",
3059 relation->relname)));
3060 }
3061
3062 return heapOid;
3063}
void RangeVarCallbackMaintainsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:19417

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 2260 of file indexcmds.c.

2262{
2263 char *schemaname;
2264 char *opcname;
2265 HeapTuple tuple;
2266 Form_pg_opclass opform;
2267 Oid opClassId,
2268 opInputType;
2269
2270 if (opclass == NIL)
2271 {
2272 /* no operator class specified, so find the default */
2273 opClassId = GetDefaultOpClass(attrType, accessMethodId);
2274 if (!OidIsValid(opClassId))
2275 ereport(ERROR,
2276 (errcode(ERRCODE_UNDEFINED_OBJECT),
2277 errmsg("data type %s has no default operator class for access method \"%s\"",
2278 format_type_be(attrType), accessMethodName),
2279 errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
2280 return opClassId;
2281 }
2282
2283 /*
2284 * Specific opclass name given, so look up the opclass.
2285 */
2286
2287 /* deconstruct the name list */
2288 DeconstructQualifiedName(opclass, &schemaname, &opcname);
2289
2290 if (schemaname)
2291 {
2292 /* Look in specific schema only */
2293 Oid namespaceId;
2294
2295 namespaceId = LookupExplicitNamespace(schemaname, false);
2296 tuple = SearchSysCache3(CLAAMNAMENSP,
2297 ObjectIdGetDatum(accessMethodId),
2298 PointerGetDatum(opcname),
2299 ObjectIdGetDatum(namespaceId));
2300 }
2301 else
2302 {
2303 /* Unqualified opclass name, so search the search path */
2304 opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
2305 if (!OidIsValid(opClassId))
2306 ereport(ERROR,
2307 (errcode(ERRCODE_UNDEFINED_OBJECT),
2308 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2309 opcname, accessMethodName)));
2310 tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
2311 }
2312
2313 if (!HeapTupleIsValid(tuple))
2314 ereport(ERROR,
2315 (errcode(ERRCODE_UNDEFINED_OBJECT),
2316 errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2317 NameListToString(opclass), accessMethodName)));
2318
2319 /*
2320 * Verify that the index operator class accepts this datatype. Note we
2321 * will accept binary compatibility.
2322 */
2323 opform = (Form_pg_opclass) GETSTRUCT(tuple);
2324 opClassId = opform->oid;
2325 opInputType = opform->opcintype;
2326
2327 if (!IsBinaryCoercible(attrType, opInputType))
2328 ereport(ERROR,
2329 (errcode(ERRCODE_DATATYPE_MISMATCH),
2330 errmsg("operator class \"%s\" does not accept data type %s",
2331 NameListToString(opclass), format_type_be(attrType))));
2332
2333 ReleaseSysCache(tuple);
2334
2335 return opClassId;
2336}
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2345
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:2121
char * NameListToString(const List *names)
Definition: namespace.c:3594
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:3385
void DeconstructQualifiedName(const List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:3301
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:243

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 4579 of file indexcmds.c.

4580{
4581 /*
4582 * This should only be called before installing xid or xmin in MyProc;
4583 * otherwise, concurrent processes could see an Xmin that moves backwards.
4584 */
4587
4588 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
4591 LWLockRelease(ProcArrayLock);
4592}
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1182
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1902
@ LW_EXCLUSIVE
Definition: lwlock.h:114
#define PROC_IN_SAFE_IC
Definition: proc.h:59
PROC_HDR * ProcGlobal
Definition: proc.c:79
uint8 statusFlags
Definition: proc.h:243
int pgxactoff
Definition: proc.h:185
TransactionId xid
Definition: proc.h:173
uint8 * statusFlags
Definition: proc.h:387

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 4541 of file indexcmds.c.

4542{
4543 HeapTuple tup;
4544 Relation classRel;
4545 ItemPointerData otid;
4546
4547 classRel = table_open(RelationRelationId, RowExclusiveLock);
4548 tup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relationId));
4549 if (!HeapTupleIsValid(tup))
4550 elog(ERROR, "cache lookup failed for relation %u", relationId);
4551 otid = tup->t_self;
4552 Assert(((Form_pg_class) GETSTRUCT(tup))->relispartition != newval);
4553 ((Form_pg_class) GETSTRUCT(tup))->relispartition = newval;
4554 CatalogTupleUpdate(classRel, &otid, tup);
4555 UnlockTuple(classRel, &otid, InplaceUpdateTupleLock);
4556 heap_freetuple(tup);
4557 table_close(classRel, RowExclusiveLock);
4558}
#define newval
void UnlockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
Definition: lmgr.c:601
#define InplaceUpdateTupleLock
Definition: lockdefs.h:48
HeapTuple SearchSysCacheLockedCopy1(int cacheId, Datum key1)
Definition: syscache.c:404

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:4710
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:68
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:72
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:75
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:3324
PGPROC * ProcNumberGetProc(ProcNumber procNumber)
Definition: procarray.c:3138
#define PROGRESS_WAITFOR_DONE
Definition: progress.h:120
#define PROGRESS_WAITFOR_TOTAL
Definition: progress.h:119
#define PROGRESS_WAITFOR_CURRENT_PID
Definition: progress.h:121
Definition: proc.h:163
int pid
Definition: proc.h:183

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().