PostgreSQL Source Code  git master
indexcmds.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * indexcmds.c
4  * POSTGRES define and remove index code.
5  *
6  * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/commands/indexcmds.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include "access/amapi.h"
19 #include "access/htup_details.h"
20 #include "access/reloptions.h"
21 #include "access/sysattr.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/index.h"
25 #include "catalog/indexing.h"
26 #include "catalog/pg_am.h"
27 #include "catalog/pg_opclass.h"
28 #include "catalog/pg_opfamily.h"
29 #include "catalog/pg_tablespace.h"
30 #include "catalog/pg_type.h"
31 #include "commands/comment.h"
32 #include "commands/dbcommands.h"
33 #include "commands/defrem.h"
34 #include "commands/tablecmds.h"
35 #include "commands/tablespace.h"
36 #include "mb/pg_wchar.h"
37 #include "miscadmin.h"
38 #include "nodes/nodeFuncs.h"
39 #include "optimizer/clauses.h"
40 #include "optimizer/planner.h"
41 #include "optimizer/var.h"
42 #include "parser/parse_coerce.h"
43 #include "parser/parse_func.h"
44 #include "parser/parse_oper.h"
45 #include "storage/lmgr.h"
46 #include "storage/proc.h"
47 #include "storage/procarray.h"
48 #include "utils/acl.h"
49 #include "utils/builtins.h"
50 #include "utils/fmgroids.h"
51 #include "utils/inval.h"
52 #include "utils/lsyscache.h"
53 #include "utils/memutils.h"
54 #include "utils/regproc.h"
55 #include "utils/snapmgr.h"
56 #include "utils/syscache.h"
57 #include "utils/tqual.h"
58 
59 
60 /* non-export function prototypes */
61 static void CheckPredicate(Expr *predicate);
62 static void ComputeIndexAttrs(IndexInfo *indexInfo,
63  Oid *typeOidP,
64  Oid *collationOidP,
65  Oid *classOidP,
66  int16 *colOptionP,
67  List *attList,
68  List *exclusionOpNames,
69  Oid relId,
70  const char *accessMethodName, Oid accessMethodId,
71  bool amcanorder,
72  bool isconstraint);
73 static char *ChooseIndexName(const char *tabname, Oid namespaceId,
74  List *colnames, List *exclusionOpNames,
75  bool primary, bool isconstraint);
76 static char *ChooseIndexNameAddition(List *colnames);
77 static List *ChooseIndexColumnNames(List *indexElems);
78 static void RangeVarCallbackForReindexIndex(const RangeVar *relation,
79  Oid relId, Oid oldRelId, void *arg);
80 
81 /*
82  * CheckIndexCompatible
83  * Determine whether an existing index definition is compatible with a
84  * prospective index definition, such that the existing index storage
85  * could become the storage of the new index, avoiding a rebuild.
86  *
87  * 'heapRelation': the relation the index would apply to.
88  * 'accessMethodName': name of the AM to use.
89  * 'attributeList': a list of IndexElem specifying columns and expressions
90  * to index on.
91  * 'exclusionOpNames': list of names of exclusion-constraint operators,
92  * or NIL if not an exclusion constraint.
93  *
94  * This is tailored to the needs of ALTER TABLE ALTER TYPE, which recreates
95  * any indexes that depended on a changing column from their pg_get_indexdef
96  * or pg_get_constraintdef definitions. We omit some of the sanity checks of
97  * DefineIndex. We assume that the old and new indexes have the same number
98  * of columns and that if one has an expression column or predicate, both do.
99  * Errors arising from the attribute list still apply.
100  *
101  * Most column type changes that can skip a table rewrite do not invalidate
102  * indexes. We acknowledge this when all operator classes, collations and
103  * exclusion operators match. Though we could further permit intra-opfamily
104  * changes for btree and hash indexes, that adds subtle complexity with no
105  * concrete benefit for core types.
106 
107  * When a comparison or exclusion operator has a polymorphic input type, the
108  * actual input types must also match. This defends against the possibility
109  * that operators could vary behavior in response to get_fn_expr_argtype().
110  * At present, this hazard is theoretical: check_exclusion_constraint() and
111  * all core index access methods decline to set fn_expr for such calls.
112  *
113  * We do not yet implement a test to verify compatibility of expression
114  * columns or predicates, so assume any such index is incompatible.
115  */
116 bool
118  const char *accessMethodName,
119  List *attributeList,
120  List *exclusionOpNames)
121 {
122  bool isconstraint;
123  Oid *typeObjectId;
124  Oid *collationObjectId;
125  Oid *classObjectId;
126  Oid accessMethodId;
127  Oid relationId;
128  HeapTuple tuple;
129  Form_pg_index indexForm;
130  Form_pg_am accessMethodForm;
131  IndexAmRoutine *amRoutine;
132  bool amcanorder;
133  int16 *coloptions;
134  IndexInfo *indexInfo;
135  int numberOfAttributes;
136  int old_natts;
137  bool isnull;
138  bool ret = true;
139  oidvector *old_indclass;
140  oidvector *old_indcollation;
141  Relation irel;
142  int i;
143  Datum d;
144 
145  /* Caller should already have the relation locked in some way. */
146  relationId = IndexGetRelation(oldId, false);
147 
148  /*
149  * We can pretend isconstraint = false unconditionally. It only serves to
150  * decide the text of an error message that should never happen for us.
151  */
152  isconstraint = false;
153 
154  numberOfAttributes = list_length(attributeList);
155  Assert(numberOfAttributes > 0);
156  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
157 
158  /* look up the access method */
159  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
160  if (!HeapTupleIsValid(tuple))
161  ereport(ERROR,
162  (errcode(ERRCODE_UNDEFINED_OBJECT),
163  errmsg("access method \"%s\" does not exist",
164  accessMethodName)));
165  accessMethodId = HeapTupleGetOid(tuple);
166  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
167  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
168  ReleaseSysCache(tuple);
169 
170  amcanorder = amRoutine->amcanorder;
171 
172  /*
173  * Compute the operator classes, collations, and exclusion operators for
174  * the new index, so we can test whether it's compatible with the existing
175  * one. Note that ComputeIndexAttrs might fail here, but that's OK:
176  * DefineIndex would have called this function with the same arguments
177  * later on, and it would have failed then anyway.
178  */
179  indexInfo = makeNode(IndexInfo);
180  indexInfo->ii_Expressions = NIL;
181  indexInfo->ii_ExpressionsState = NIL;
182  indexInfo->ii_PredicateState = NULL;
183  indexInfo->ii_ExclusionOps = NULL;
184  indexInfo->ii_ExclusionProcs = NULL;
185  indexInfo->ii_ExclusionStrats = NULL;
186  indexInfo->ii_AmCache = NULL;
187  indexInfo->ii_Context = CurrentMemoryContext;
188  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
189  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
190  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
191  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
192  ComputeIndexAttrs(indexInfo,
193  typeObjectId, collationObjectId, classObjectId,
194  coloptions, attributeList,
195  exclusionOpNames, relationId,
196  accessMethodName, accessMethodId,
197  amcanorder, isconstraint);
198 
199 
200  /* Get the soon-obsolete pg_index tuple. */
202  if (!HeapTupleIsValid(tuple))
203  elog(ERROR, "cache lookup failed for index %u", oldId);
204  indexForm = (Form_pg_index) GETSTRUCT(tuple);
205 
206  /*
207  * We don't assess expressions or predicates; assume incompatibility.
208  * Also, if the index is invalid for any reason, treat it as incompatible.
209  */
210  if (!(heap_attisnull(tuple, Anum_pg_index_indpred) &&
212  IndexIsValid(indexForm)))
213  {
214  ReleaseSysCache(tuple);
215  return false;
216  }
217 
218  /* Any change in operator class or collation breaks compatibility. */
219  old_natts = indexForm->indnatts;
220  Assert(old_natts == numberOfAttributes);
221 
223  Assert(!isnull);
224  old_indcollation = (oidvector *) DatumGetPointer(d);
225 
226  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
227  Assert(!isnull);
228  old_indclass = (oidvector *) DatumGetPointer(d);
229 
230  ret = (memcmp(old_indclass->values, classObjectId,
231  old_natts * sizeof(Oid)) == 0 &&
232  memcmp(old_indcollation->values, collationObjectId,
233  old_natts * sizeof(Oid)) == 0);
234 
235  ReleaseSysCache(tuple);
236 
237  if (!ret)
238  return false;
239 
240  /* For polymorphic opcintype, column type changes break compatibility. */
241  irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
242  for (i = 0; i < old_natts; i++)
243  {
244  if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
245  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
246  {
247  ret = false;
248  break;
249  }
250  }
251 
252  /* Any change in exclusion operator selections breaks compatibility. */
253  if (ret && indexInfo->ii_ExclusionOps != NULL)
254  {
255  Oid *old_operators,
256  *old_procs;
257  uint16 *old_strats;
258 
259  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
260  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
261  old_natts * sizeof(Oid)) == 0;
262 
263  /* Require an exact input type match for polymorphic operators. */
264  if (ret)
265  {
266  for (i = 0; i < old_natts && ret; i++)
267  {
268  Oid left,
269  right;
270 
271  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
272  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
273  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
274  {
275  ret = false;
276  break;
277  }
278  }
279  }
280  }
281 
282  index_close(irel, NoLock);
283  return ret;
284 }
285 
286 /*
287  * DefineIndex
288  * Creates a new index.
289  *
290  * 'relationId': the OID of the heap relation on which the index is to be
291  * created
292  * 'stmt': IndexStmt describing the properties of the new index.
293  * 'indexRelationId': normally InvalidOid, but during bootstrap can be
294  * nonzero to specify a preselected OID for the index.
295  * 'is_alter_table': this is due to an ALTER rather than a CREATE operation.
296  * 'check_rights': check for CREATE rights in namespace and tablespace. (This
297  * should be true except when ALTER is deleting/recreating an index.)
298  * 'check_not_in_use': check for table not already in use in current session.
299  * This should be true unless caller is holding the table open, in which
300  * case the caller had better have checked it earlier.
301  * 'skip_build': make the catalog entries but leave the index file empty;
302  * it will be filled later.
303  * 'quiet': suppress the NOTICE chatter ordinarily provided for constraints.
304  *
305  * Returns the object address of the created index.
306  */
308 DefineIndex(Oid relationId,
309  IndexStmt *stmt,
310  Oid indexRelationId,
311  bool is_alter_table,
312  bool check_rights,
313  bool check_not_in_use,
314  bool skip_build,
315  bool quiet)
316 {
317  char *indexRelationName;
318  char *accessMethodName;
319  Oid *typeObjectId;
320  Oid *collationObjectId;
321  Oid *classObjectId;
322  Oid accessMethodId;
323  Oid namespaceId;
324  Oid tablespaceId;
325  List *indexColNames;
326  Relation rel;
327  Relation indexRelation;
328  HeapTuple tuple;
329  Form_pg_am accessMethodForm;
330  IndexAmRoutine *amRoutine;
331  bool amcanorder;
332  amoptions_function amoptions;
333  Datum reloptions;
334  int16 *coloptions;
335  IndexInfo *indexInfo;
336  bits16 flags;
337  bits16 constr_flags;
338  int numberOfAttributes;
339  TransactionId limitXmin;
340  VirtualTransactionId *old_snapshots;
341  ObjectAddress address;
342  int n_old_snapshots;
343  LockRelId heaprelid;
344  LOCKTAG heaplocktag;
345  LOCKMODE lockmode;
346  Snapshot snapshot;
347  int i;
348 
349  /*
350  * count attributes in index
351  */
352  numberOfAttributes = list_length(stmt->indexParams);
353  if (numberOfAttributes <= 0)
354  ereport(ERROR,
355  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
356  errmsg("must specify at least one column")));
357  if (numberOfAttributes > INDEX_MAX_KEYS)
358  ereport(ERROR,
359  (errcode(ERRCODE_TOO_MANY_COLUMNS),
360  errmsg("cannot use more than %d columns in an index",
361  INDEX_MAX_KEYS)));
362 
363  /*
364  * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
365  * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
366  * (but not VACUUM).
367  *
368  * NB: Caller is responsible for making sure that relationId refers to the
369  * relation on which the index should be built; except in bootstrap mode,
370  * this will typically require the caller to have already locked the
371  * relation. To avoid lock upgrade hazards, that lock should be at least
372  * as strong as the one we take here.
373  */
374  lockmode = stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock;
375  rel = heap_open(relationId, lockmode);
376 
377  relationId = RelationGetRelid(rel);
378  namespaceId = RelationGetNamespace(rel);
379 
380  /* Ensure that it makes sense to index this kind of relation */
381  switch (rel->rd_rel->relkind)
382  {
383  case RELKIND_RELATION:
384  case RELKIND_MATVIEW:
385  /* OK */
386  break;
388  ereport(ERROR,
389  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
390  errmsg("cannot create index on foreign table \"%s\"",
391  RelationGetRelationName(rel))));
393  ereport(ERROR,
394  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
395  errmsg("cannot create index on partitioned table \"%s\"",
396  RelationGetRelationName(rel))));
397  default:
398  ereport(ERROR,
399  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
400  errmsg("\"%s\" is not a table or materialized view",
401  RelationGetRelationName(rel))));
402  }
403 
404  /*
405  * Don't try to CREATE INDEX on temp tables of other backends.
406  */
407  if (RELATION_IS_OTHER_TEMP(rel))
408  ereport(ERROR,
409  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
410  errmsg("cannot create indexes on temporary tables of other sessions")));
411 
412  /*
413  * Unless our caller vouches for having checked this already, insist that
414  * the table not be in use by our own session, either. Otherwise we might
415  * fail to make entries in the new index (for instance, if an INSERT or
416  * UPDATE is in progress and has already made its list of target indexes).
417  */
418  if (check_not_in_use)
419  CheckTableNotInUse(rel, "CREATE INDEX");
420 
421  /*
422  * Verify we (still) have CREATE rights in the rel's namespace.
423  * (Presumably we did when the rel was created, but maybe not anymore.)
424  * Skip check if caller doesn't want it. Also skip check if
425  * bootstrapping, since permissions machinery may not be working yet.
426  */
427  if (check_rights && !IsBootstrapProcessingMode())
428  {
429  AclResult aclresult;
430 
431  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
432  ACL_CREATE);
433  if (aclresult != ACLCHECK_OK)
435  get_namespace_name(namespaceId));
436  }
437 
438  /*
439  * Select tablespace to use. If not specified, use default tablespace
440  * (which may in turn default to database's default).
441  */
442  if (stmt->tableSpace)
443  {
444  tablespaceId = get_tablespace_oid(stmt->tableSpace, false);
445  }
446  else
447  {
448  tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence);
449  /* note InvalidOid is OK in this case */
450  }
451 
452  /* Check tablespace permissions */
453  if (check_rights &&
454  OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
455  {
456  AclResult aclresult;
457 
458  aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
459  ACL_CREATE);
460  if (aclresult != ACLCHECK_OK)
462  get_tablespace_name(tablespaceId));
463  }
464 
465  /*
466  * Force shared indexes into the pg_global tablespace. This is a bit of a
467  * hack but seems simpler than marking them in the BKI commands. On the
468  * other hand, if it's not shared, don't allow it to be placed there.
469  */
470  if (rel->rd_rel->relisshared)
471  tablespaceId = GLOBALTABLESPACE_OID;
472  else if (tablespaceId == GLOBALTABLESPACE_OID)
473  ereport(ERROR,
474  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
475  errmsg("only shared relations can be placed in pg_global tablespace")));
476 
477  /*
478  * Choose the index column names.
479  */
480  indexColNames = ChooseIndexColumnNames(stmt->indexParams);
481 
482  /*
483  * Select name for index if caller didn't specify
484  */
485  indexRelationName = stmt->idxname;
486  if (indexRelationName == NULL)
487  indexRelationName = ChooseIndexName(RelationGetRelationName(rel),
488  namespaceId,
489  indexColNames,
490  stmt->excludeOpNames,
491  stmt->primary,
492  stmt->isconstraint);
493 
494  /*
495  * look up the access method, verify it can handle the requested features
496  */
497  accessMethodName = stmt->accessMethod;
498  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
499  if (!HeapTupleIsValid(tuple))
500  {
501  /*
502  * Hack to provide more-or-less-transparent updating of old RTREE
503  * indexes to GiST: if RTREE is requested and not found, use GIST.
504  */
505  if (strcmp(accessMethodName, "rtree") == 0)
506  {
507  ereport(NOTICE,
508  (errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
509  accessMethodName = "gist";
510  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
511  }
512 
513  if (!HeapTupleIsValid(tuple))
514  ereport(ERROR,
515  (errcode(ERRCODE_UNDEFINED_OBJECT),
516  errmsg("access method \"%s\" does not exist",
517  accessMethodName)));
518  }
519  accessMethodId = HeapTupleGetOid(tuple);
520  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
521  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
522 
523  if (stmt->unique && !amRoutine->amcanunique)
524  ereport(ERROR,
525  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
526  errmsg("access method \"%s\" does not support unique indexes",
527  accessMethodName)));
528  if (numberOfAttributes > 1 && !amRoutine->amcanmulticol)
529  ereport(ERROR,
530  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
531  errmsg("access method \"%s\" does not support multicolumn indexes",
532  accessMethodName)));
533  if (stmt->excludeOpNames && amRoutine->amgettuple == NULL)
534  ereport(ERROR,
535  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
536  errmsg("access method \"%s\" does not support exclusion constraints",
537  accessMethodName)));
538 
539  amcanorder = amRoutine->amcanorder;
540  amoptions = amRoutine->amoptions;
541 
542  pfree(amRoutine);
543  ReleaseSysCache(tuple);
544 
545  /*
546  * Validate predicate, if given
547  */
548  if (stmt->whereClause)
549  CheckPredicate((Expr *) stmt->whereClause);
550 
551  /*
552  * Parse AM-specific options, convert to text array form, validate.
553  */
554  reloptions = transformRelOptions((Datum) 0, stmt->options,
555  NULL, NULL, false, false);
556 
557  (void) index_reloptions(amoptions, reloptions, true);
558 
559  /*
560  * Prepare arguments for index_create, primarily an IndexInfo structure.
561  * Note that ii_Predicate must be in implicit-AND format.
562  */
563  indexInfo = makeNode(IndexInfo);
564  indexInfo->ii_NumIndexAttrs = numberOfAttributes;
565  indexInfo->ii_Expressions = NIL; /* for now */
566  indexInfo->ii_ExpressionsState = NIL;
567  indexInfo->ii_Predicate = make_ands_implicit((Expr *) stmt->whereClause);
568  indexInfo->ii_PredicateState = NULL;
569  indexInfo->ii_ExclusionOps = NULL;
570  indexInfo->ii_ExclusionProcs = NULL;
571  indexInfo->ii_ExclusionStrats = NULL;
572  indexInfo->ii_Unique = stmt->unique;
573  /* In a concurrent build, mark it not-ready-for-inserts */
574  indexInfo->ii_ReadyForInserts = !stmt->concurrent;
575  indexInfo->ii_Concurrent = stmt->concurrent;
576  indexInfo->ii_BrokenHotChain = false;
577  indexInfo->ii_AmCache = NULL;
578  indexInfo->ii_Context = CurrentMemoryContext;
579 
580  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
581  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
582  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
583  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
584  ComputeIndexAttrs(indexInfo,
585  typeObjectId, collationObjectId, classObjectId,
586  coloptions, stmt->indexParams,
587  stmt->excludeOpNames, relationId,
588  accessMethodName, accessMethodId,
589  amcanorder, stmt->isconstraint);
590 
591  /*
592  * Extra checks when creating a PRIMARY KEY index.
593  */
594  if (stmt->primary)
595  index_check_primary_key(rel, indexInfo, is_alter_table);
596 
597  /*
598  * We disallow indexes on system columns other than OID. They would not
599  * necessarily get updated correctly, and they don't seem useful anyway.
600  */
601  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
602  {
603  AttrNumber attno = indexInfo->ii_KeyAttrNumbers[i];
604 
605  if (attno < 0 && attno != ObjectIdAttributeNumber)
606  ereport(ERROR,
607  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
608  errmsg("index creation on system columns is not supported")));
609  }
610 
611  /*
612  * Also check for system columns used in expressions or predicates.
613  */
614  if (indexInfo->ii_Expressions || indexInfo->ii_Predicate)
615  {
616  Bitmapset *indexattrs = NULL;
617 
618  pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs);
619  pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs);
620 
621  for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
622  {
623  if (i != ObjectIdAttributeNumber &&
625  indexattrs))
626  ereport(ERROR,
627  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
628  errmsg("index creation on system columns is not supported")));
629  }
630  }
631 
632  /*
633  * Report index creation if appropriate (delay this till after most of the
634  * error checks)
635  */
636  if (stmt->isconstraint && !quiet)
637  {
638  const char *constraint_type;
639 
640  if (stmt->primary)
641  constraint_type = "PRIMARY KEY";
642  else if (stmt->unique)
643  constraint_type = "UNIQUE";
644  else if (stmt->excludeOpNames != NIL)
645  constraint_type = "EXCLUDE";
646  else
647  {
648  elog(ERROR, "unknown constraint type");
649  constraint_type = NULL; /* keep compiler quiet */
650  }
651 
652  ereport(DEBUG1,
653  (errmsg("%s %s will create implicit index \"%s\" for table \"%s\"",
654  is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
655  constraint_type,
656  indexRelationName, RelationGetRelationName(rel))));
657  }
658 
659  /*
660  * A valid stmt->oldNode implies that we already have a built form of the
661  * index. The caller should also decline any index build.
662  */
663  Assert(!OidIsValid(stmt->oldNode) || (skip_build && !stmt->concurrent));
664 
665  /*
666  * Make the catalog entries for the index, including constraints. This
667  * step also actually builds the index, except if caller requested not to
668  * or in concurrent mode, in which case it'll be done later.
669  */
670  flags = constr_flags = 0;
671  if (stmt->isconstraint)
673  if (skip_build || stmt->concurrent)
674  flags |= INDEX_CREATE_SKIP_BUILD;
675  if (stmt->if_not_exists)
677  if (stmt->concurrent)
678  flags |= INDEX_CREATE_CONCURRENT;
679  if (stmt->primary)
680  flags |= INDEX_CREATE_IS_PRIMARY;
681 
682  if (stmt->deferrable)
683  constr_flags |= INDEX_CONSTR_CREATE_DEFERRABLE;
684  if (stmt->initdeferred)
685  constr_flags |= INDEX_CONSTR_CREATE_INIT_DEFERRED;
686 
687  indexRelationId =
688  index_create(rel, indexRelationName, indexRelationId, stmt->oldNode,
689  indexInfo, indexColNames,
690  accessMethodId, tablespaceId,
691  collationObjectId, classObjectId,
692  coloptions, reloptions,
693  flags, constr_flags,
694  allowSystemTableMods, !check_rights);
695 
696  ObjectAddressSet(address, RelationRelationId, indexRelationId);
697 
698  if (!OidIsValid(indexRelationId))
699  {
700  heap_close(rel, NoLock);
701  return address;
702  }
703 
704  /* Add any requested comment */
705  if (stmt->idxcomment != NULL)
706  CreateComments(indexRelationId, RelationRelationId, 0,
707  stmt->idxcomment);
708 
709  if (!stmt->concurrent)
710  {
711  /* Close the heap and we're done, in the non-concurrent case */
712  heap_close(rel, NoLock);
713  return address;
714  }
715 
716  /* save lockrelid and locktag for below, then close rel */
717  heaprelid = rel->rd_lockInfo.lockRelId;
718  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
719  heap_close(rel, NoLock);
720 
721  /*
722  * For a concurrent build, it's important to make the catalog entries
723  * visible to other transactions before we start to build the index. That
724  * will prevent them from making incompatible HOT updates. The new index
725  * will be marked not indisready and not indisvalid, so that no one else
726  * tries to either insert into it or use it for queries.
727  *
728  * We must commit our current transaction so that the index becomes
729  * visible; then start another. Note that all the data structures we just
730  * built are lost in the commit. The only data we keep past here are the
731  * relation IDs.
732  *
733  * Before committing, get a session-level lock on the table, to ensure
734  * that neither it nor the index can be dropped before we finish. This
735  * cannot block, even if someone else is waiting for access, because we
736  * already have the same lock within our transaction.
737  *
738  * Note: we don't currently bother with a session lock on the index,
739  * because there are no operations that could change its state while we
740  * hold lock on the parent table. This might need to change later.
741  */
743 
747 
748  /*
749  * Phase 2 of concurrent index build (see comments for validate_index()
750  * for an overview of how this works)
751  *
752  * Now we must wait until no running transaction could have the table open
753  * with the old list of indexes. Use ShareLock to consider running
754  * transactions that hold locks that permit writing to the table. Note we
755  * do not need to worry about xacts that open the table for writing after
756  * this point; they will see the new index when they open it.
757  *
758  * Note: the reason we use actual lock acquisition here, rather than just
759  * checking the ProcArray and sleeping, is that deadlock is possible if
760  * one of the transactions in question is blocked trying to acquire an
761  * exclusive lock on our table. The lock code will detect deadlock and
762  * error out properly.
763  */
764  WaitForLockers(heaplocktag, ShareLock);
765 
766  /*
767  * At this moment we are sure that there are no transactions with the
768  * table open for write that don't have this new index in their list of
769  * indexes. We have waited out all the existing transactions and any new
770  * transaction will have the new index in its list, but the index is still
771  * marked as "not-ready-for-inserts". The index is consulted while
772  * deciding HOT-safety though. This arrangement ensures that no new HOT
773  * chains can be created where the new tuple and the old tuple in the
774  * chain have different index keys.
775  *
776  * We now take a new snapshot, and build the index using all tuples that
777  * are visible in this snapshot. We can be sure that any HOT updates to
778  * these tuples will be compatible with the index, since any updates made
779  * by transactions that didn't know about the index are now committed or
780  * rolled back. Thus, each visible tuple is either the end of its
781  * HOT-chain or the extension of the chain is HOT-safe for this index.
782  */
783 
784  /* Open and lock the parent heap relation */
786 
787  /* And the target index relation */
788  indexRelation = index_open(indexRelationId, RowExclusiveLock);
789 
790  /* Set ActiveSnapshot since functions in the indexes may need it */
792 
793  /* We have to re-build the IndexInfo struct, since it was lost in commit */
794  indexInfo = BuildIndexInfo(indexRelation);
795  Assert(!indexInfo->ii_ReadyForInserts);
796  indexInfo->ii_Concurrent = true;
797  indexInfo->ii_BrokenHotChain = false;
798 
799  /* Now build the index */
800  index_build(rel, indexRelation, indexInfo, stmt->primary, false);
801 
802  /* Close both the relations, but keep the locks */
803  heap_close(rel, NoLock);
804  index_close(indexRelation, NoLock);
805 
806  /*
807  * Update the pg_index row to mark the index as ready for inserts. Once we
808  * commit this transaction, any new transactions that open the table must
809  * insert new entries into the index for insertions and non-HOT updates.
810  */
812 
813  /* we can do away with our snapshot */
815 
816  /*
817  * Commit this transaction to make the indisready update visible.
818  */
821 
822  /*
823  * Phase 3 of concurrent index build
824  *
825  * We once again wait until no transaction can have the table open with
826  * the index marked as read-only for updates.
827  */
828  WaitForLockers(heaplocktag, ShareLock);
829 
830  /*
831  * Now take the "reference snapshot" that will be used by validate_index()
832  * to filter candidate tuples. Beware! There might still be snapshots in
833  * use that treat some transaction as in-progress that our reference
834  * snapshot treats as committed. If such a recently-committed transaction
835  * deleted tuples in the table, we will not include them in the index; yet
836  * those transactions which see the deleting one as still-in-progress will
837  * expect such tuples to be there once we mark the index as valid.
838  *
839  * We solve this by waiting for all endangered transactions to exit before
840  * we mark the index as valid.
841  *
842  * We also set ActiveSnapshot to this snap, since functions in indexes may
843  * need a snapshot.
844  */
846  PushActiveSnapshot(snapshot);
847 
848  /*
849  * Scan the index and the heap, insert any missing index entries.
850  */
851  validate_index(relationId, indexRelationId, snapshot);
852 
853  /*
854  * Drop the reference snapshot. We must do this before waiting out other
855  * snapshot holders, else we will deadlock against other processes also
856  * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
857  * they must wait for. But first, save the snapshot's xmin to use as
858  * limitXmin for GetCurrentVirtualXIDs().
859  *
860  * Our catalog snapshot could have the same effect, so drop that one too.
861  */
862  limitXmin = snapshot->xmin;
863 
865  UnregisterSnapshot(snapshot);
867 
868  /*
869  * The index is now valid in the sense that it contains all currently
870  * interesting tuples. But since it might not contain tuples deleted just
871  * before the reference snap was taken, we have to wait out any
872  * transactions that might have older snapshots. Obtain a list of VXIDs
873  * of such transactions, and wait for them individually.
874  *
875  * We can exclude any running transactions that have xmin > the xmin of
876  * our reference snapshot; their oldest snapshot must be newer than ours.
877  * We can also exclude any transactions that have xmin = zero, since they
878  * evidently have no live snapshot at all (and any one they might be in
879  * process of taking is certainly newer than ours). Transactions in other
880  * DBs can be ignored too, since they'll never even be able to see this
881  * index.
882  *
883  * We can also exclude autovacuum processes and processes running manual
884  * lazy VACUUMs, because they won't be fazed by missing index entries
885  * either. (Manual ANALYZEs, however, can't be excluded because they
886  * might be within transactions that are going to do arbitrary operations
887  * later.)
888  *
889  * Also, GetCurrentVirtualXIDs never reports our own vxid, so we need not
890  * check for that.
891  *
892  * If a process goes idle-in-transaction with xmin zero, we do not need to
893  * wait for it anymore, per the above argument. We do not have the
894  * infrastructure right now to stop waiting if that happens, but we can at
895  * least avoid the folly of waiting when it is idle at the time we would
896  * begin to wait. We do this by repeatedly rechecking the output of
897  * GetCurrentVirtualXIDs. If, during any iteration, a particular vxid
898  * doesn't show up in the output, we know we can forget about it.
899  */
900  old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
902  &n_old_snapshots);
903 
904  for (i = 0; i < n_old_snapshots; i++)
905  {
906  if (!VirtualTransactionIdIsValid(old_snapshots[i]))
907  continue; /* found uninteresting in previous cycle */
908 
909  if (i > 0)
910  {
911  /* see if anything's changed ... */
912  VirtualTransactionId *newer_snapshots;
913  int n_newer_snapshots;
914  int j;
915  int k;
916 
917  newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
918  true, false,
920  &n_newer_snapshots);
921  for (j = i; j < n_old_snapshots; j++)
922  {
923  if (!VirtualTransactionIdIsValid(old_snapshots[j]))
924  continue; /* found uninteresting in previous cycle */
925  for (k = 0; k < n_newer_snapshots; k++)
926  {
927  if (VirtualTransactionIdEquals(old_snapshots[j],
928  newer_snapshots[k]))
929  break;
930  }
931  if (k >= n_newer_snapshots) /* not there anymore */
932  SetInvalidVirtualTransactionId(old_snapshots[j]);
933  }
934  pfree(newer_snapshots);
935  }
936 
937  if (VirtualTransactionIdIsValid(old_snapshots[i]))
938  VirtualXactLock(old_snapshots[i], true);
939  }
940 
941  /*
942  * Index can now be marked valid -- update its pg_index entry
943  */
945 
946  /*
947  * The pg_index update will cause backends (including this one) to update
948  * relcache entries for the index itself, but we should also send a
949  * relcache inval on the parent table to force replanning of cached plans.
950  * Otherwise existing sessions might fail to use the new index where it
951  * would be useful. (Note that our earlier commits did not create reasons
952  * to replan; so relcache flush on the index itself was sufficient.)
953  */
955 
956  /*
957  * Last thing to do is release the session-level lock on the parent table.
958  */
960 
961  return address;
962 }
963 
964 
965 /*
966  * CheckMutability
967  * Test whether given expression is mutable
968  */
969 static bool
971 {
972  /*
973  * First run the expression through the planner. This has a couple of
974  * important consequences. First, function default arguments will get
975  * inserted, which may affect volatility (consider "default now()").
976  * Second, inline-able functions will get inlined, which may allow us to
977  * conclude that the function is really less volatile than it's marked. As
978  * an example, polymorphic functions must be marked with the most volatile
979  * behavior that they have for any input type, but once we inline the
980  * function we may be able to conclude that it's not so volatile for the
981  * particular input type we're dealing with.
982  *
983  * We assume here that expression_planner() won't scribble on its input.
984  */
985  expr = expression_planner(expr);
986 
987  /* Now we can search for non-immutable functions */
988  return contain_mutable_functions((Node *) expr);
989 }
990 
991 
992 /*
993  * CheckPredicate
994  * Checks that the given partial-index predicate is valid.
995  *
996  * This used to also constrain the form of the predicate to forms that
997  * indxpath.c could do something with. However, that seems overly
998  * restrictive. One useful application of partial indexes is to apply
999  * a UNIQUE constraint across a subset of a table, and in that scenario
1000  * any evaluable predicate will work. So accept any predicate here
1001  * (except ones requiring a plan), and let indxpath.c fend for itself.
1002  */
1003 static void
1005 {
1006  /*
1007  * transformExpr() should have already rejected subqueries, aggregates,
1008  * and window functions, based on the EXPR_KIND_ for a predicate.
1009  */
1010 
1011  /*
1012  * A predicate using mutable functions is probably wrong, for the same
1013  * reasons that we don't allow an index expression to use one.
1014  */
1015  if (CheckMutability(predicate))
1016  ereport(ERROR,
1017  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1018  errmsg("functions in index predicate must be marked IMMUTABLE")));
1019 }
1020 
1021 /*
1022  * Compute per-index-column information, including indexed column numbers
1023  * or index expressions, opclasses, and indoptions.
1024  */
1025 static void
1027  Oid *typeOidP,
1028  Oid *collationOidP,
1029  Oid *classOidP,
1030  int16 *colOptionP,
1031  List *attList, /* list of IndexElem's */
1032  List *exclusionOpNames,
1033  Oid relId,
1034  const char *accessMethodName,
1035  Oid accessMethodId,
1036  bool amcanorder,
1037  bool isconstraint)
1038 {
1039  ListCell *nextExclOp;
1040  ListCell *lc;
1041  int attn;
1042 
1043  /* Allocate space for exclusion operator info, if needed */
1044  if (exclusionOpNames)
1045  {
1046  int ncols = list_length(attList);
1047 
1048  Assert(list_length(exclusionOpNames) == ncols);
1049  indexInfo->ii_ExclusionOps = (Oid *) palloc(sizeof(Oid) * ncols);
1050  indexInfo->ii_ExclusionProcs = (Oid *) palloc(sizeof(Oid) * ncols);
1051  indexInfo->ii_ExclusionStrats = (uint16 *) palloc(sizeof(uint16) * ncols);
1052  nextExclOp = list_head(exclusionOpNames);
1053  }
1054  else
1055  nextExclOp = NULL;
1056 
1057  /*
1058  * process attributeList
1059  */
1060  attn = 0;
1061  foreach(lc, attList)
1062  {
1063  IndexElem *attribute = (IndexElem *) lfirst(lc);
1064  Oid atttype;
1065  Oid attcollation;
1066 
1067  /*
1068  * Process the column-or-expression to be indexed.
1069  */
1070  if (attribute->name != NULL)
1071  {
1072  /* Simple index attribute */
1073  HeapTuple atttuple;
1074  Form_pg_attribute attform;
1075 
1076  Assert(attribute->expr == NULL);
1077  atttuple = SearchSysCacheAttName(relId, attribute->name);
1078  if (!HeapTupleIsValid(atttuple))
1079  {
1080  /* difference in error message spellings is historical */
1081  if (isconstraint)
1082  ereport(ERROR,
1083  (errcode(ERRCODE_UNDEFINED_COLUMN),
1084  errmsg("column \"%s\" named in key does not exist",
1085  attribute->name)));
1086  else
1087  ereport(ERROR,
1088  (errcode(ERRCODE_UNDEFINED_COLUMN),
1089  errmsg("column \"%s\" does not exist",
1090  attribute->name)));
1091  }
1092  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1093  indexInfo->ii_KeyAttrNumbers[attn] = attform->attnum;
1094  atttype = attform->atttypid;
1095  attcollation = attform->attcollation;
1096  ReleaseSysCache(atttuple);
1097  }
1098  else
1099  {
1100  /* Index expression */
1101  Node *expr = attribute->expr;
1102 
1103  Assert(expr != NULL);
1104  atttype = exprType(expr);
1105  attcollation = exprCollation(expr);
1106 
1107  /*
1108  * Strip any top-level COLLATE clause. This ensures that we treat
1109  * "x COLLATE y" and "(x COLLATE y)" alike.
1110  */
1111  while (IsA(expr, CollateExpr))
1112  expr = (Node *) ((CollateExpr *) expr)->arg;
1113 
1114  if (IsA(expr, Var) &&
1115  ((Var *) expr)->varattno != InvalidAttrNumber)
1116  {
1117  /*
1118  * User wrote "(column)" or "(column COLLATE something)".
1119  * Treat it like simple attribute anyway.
1120  */
1121  indexInfo->ii_KeyAttrNumbers[attn] = ((Var *) expr)->varattno;
1122  }
1123  else
1124  {
1125  indexInfo->ii_KeyAttrNumbers[attn] = 0; /* marks expression */
1126  indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
1127  expr);
1128 
1129  /*
1130  * transformExpr() should have already rejected subqueries,
1131  * aggregates, and window functions, based on the EXPR_KIND_
1132  * for an index expression.
1133  */
1134 
1135  /*
1136  * An expression using mutable functions is probably wrong,
1137  * since if you aren't going to get the same result for the
1138  * same data every time, it's not clear what the index entries
1139  * mean at all.
1140  */
1141  if (CheckMutability((Expr *) expr))
1142  ereport(ERROR,
1143  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1144  errmsg("functions in index expression must be marked IMMUTABLE")));
1145  }
1146  }
1147 
1148  typeOidP[attn] = atttype;
1149 
1150  /*
1151  * Apply collation override if any
1152  */
1153  if (attribute->collation)
1154  attcollation = get_collation_oid(attribute->collation, false);
1155 
1156  /*
1157  * Check we have a collation iff it's a collatable type. The only
1158  * expected failures here are (1) COLLATE applied to a noncollatable
1159  * type, or (2) index expression had an unresolved collation. But we
1160  * might as well code this to be a complete consistency check.
1161  */
1162  if (type_is_collatable(atttype))
1163  {
1164  if (!OidIsValid(attcollation))
1165  ereport(ERROR,
1166  (errcode(ERRCODE_INDETERMINATE_COLLATION),
1167  errmsg("could not determine which collation to use for index expression"),
1168  errhint("Use the COLLATE clause to set the collation explicitly.")));
1169  }
1170  else
1171  {
1172  if (OidIsValid(attcollation))
1173  ereport(ERROR,
1174  (errcode(ERRCODE_DATATYPE_MISMATCH),
1175  errmsg("collations are not supported by type %s",
1176  format_type_be(atttype))));
1177  }
1178 
1179  collationOidP[attn] = attcollation;
1180 
1181  /*
1182  * Identify the opclass to use.
1183  */
1184  classOidP[attn] = ResolveOpClass(attribute->opclass,
1185  atttype,
1186  accessMethodName,
1187  accessMethodId);
1188 
1189  /*
1190  * Identify the exclusion operator, if any.
1191  */
1192  if (nextExclOp)
1193  {
1194  List *opname = (List *) lfirst(nextExclOp);
1195  Oid opid;
1196  Oid opfamily;
1197  int strat;
1198 
1199  /*
1200  * Find the operator --- it must accept the column datatype
1201  * without runtime coercion (but binary compatibility is OK)
1202  */
1203  opid = compatible_oper_opid(opname, atttype, atttype, false);
1204 
1205  /*
1206  * Only allow commutative operators to be used in exclusion
1207  * constraints. If X conflicts with Y, but Y does not conflict
1208  * with X, bad things will happen.
1209  */
1210  if (get_commutator(opid) != opid)
1211  ereport(ERROR,
1212  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1213  errmsg("operator %s is not commutative",
1214  format_operator(opid)),
1215  errdetail("Only commutative operators can be used in exclusion constraints.")));
1216 
1217  /*
1218  * Operator must be a member of the right opfamily, too
1219  */
1220  opfamily = get_opclass_family(classOidP[attn]);
1221  strat = get_op_opfamily_strategy(opid, opfamily);
1222  if (strat == 0)
1223  {
1224  HeapTuple opftuple;
1225  Form_pg_opfamily opfform;
1226 
1227  /*
1228  * attribute->opclass might not explicitly name the opfamily,
1229  * so fetch the name of the selected opfamily for use in the
1230  * error message.
1231  */
1232  opftuple = SearchSysCache1(OPFAMILYOID,
1233  ObjectIdGetDatum(opfamily));
1234  if (!HeapTupleIsValid(opftuple))
1235  elog(ERROR, "cache lookup failed for opfamily %u",
1236  opfamily);
1237  opfform = (Form_pg_opfamily) GETSTRUCT(opftuple);
1238 
1239  ereport(ERROR,
1240  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1241  errmsg("operator %s is not a member of operator family \"%s\"",
1242  format_operator(opid),
1243  NameStr(opfform->opfname)),
1244  errdetail("The exclusion operator must be related to the index operator class for the constraint.")));
1245  }
1246 
1247  indexInfo->ii_ExclusionOps[attn] = opid;
1248  indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
1249  indexInfo->ii_ExclusionStrats[attn] = strat;
1250  nextExclOp = lnext(nextExclOp);
1251  }
1252 
1253  /*
1254  * Set up the per-column options (indoption field). For now, this is
1255  * zero for any un-ordered index, while ordered indexes have DESC and
1256  * NULLS FIRST/LAST options.
1257  */
1258  colOptionP[attn] = 0;
1259  if (amcanorder)
1260  {
1261  /* default ordering is ASC */
1262  if (attribute->ordering == SORTBY_DESC)
1263  colOptionP[attn] |= INDOPTION_DESC;
1264  /* default null ordering is LAST for ASC, FIRST for DESC */
1265  if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
1266  {
1267  if (attribute->ordering == SORTBY_DESC)
1268  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1269  }
1270  else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
1271  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
1272  }
1273  else
1274  {
1275  /* index AM does not support ordering */
1276  if (attribute->ordering != SORTBY_DEFAULT)
1277  ereport(ERROR,
1278  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1279  errmsg("access method \"%s\" does not support ASC/DESC options",
1280  accessMethodName)));
1281  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1282  ereport(ERROR,
1283  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1284  errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
1285  accessMethodName)));
1286  }
1287 
1288  attn++;
1289  }
1290 }
1291 
1292 /*
1293  * Resolve possibly-defaulted operator class specification
1294  *
1295  * Note: This is used to resolve operator class specification in index and
1296  * partition key definitions.
1297  */
1298 Oid
1299 ResolveOpClass(List *opclass, Oid attrType,
1300  const char *accessMethodName, Oid accessMethodId)
1301 {
1302  char *schemaname;
1303  char *opcname;
1304  HeapTuple tuple;
1305  Oid opClassId,
1306  opInputType;
1307 
1308  /*
1309  * Release 7.0 removed network_ops, timespan_ops, and datetime_ops, so we
1310  * ignore those opclass names so the default *_ops is used. This can be
1311  * removed in some later release. bjm 2000/02/07
1312  *
1313  * Release 7.1 removes lztext_ops, so suppress that too for a while. tgl
1314  * 2000/07/30
1315  *
1316  * Release 7.2 renames timestamp_ops to timestamptz_ops, so suppress that
1317  * too for awhile. I'm starting to think we need a better approach. tgl
1318  * 2000/10/01
1319  *
1320  * Release 8.0 removes bigbox_ops (which was dead code for a long while
1321  * anyway). tgl 2003/11/11
1322  */
1323  if (list_length(opclass) == 1)
1324  {
1325  char *claname = strVal(linitial(opclass));
1326 
1327  if (strcmp(claname, "network_ops") == 0 ||
1328  strcmp(claname, "timespan_ops") == 0 ||
1329  strcmp(claname, "datetime_ops") == 0 ||
1330  strcmp(claname, "lztext_ops") == 0 ||
1331  strcmp(claname, "timestamp_ops") == 0 ||
1332  strcmp(claname, "bigbox_ops") == 0)
1333  opclass = NIL;
1334  }
1335 
1336  if (opclass == NIL)
1337  {
1338  /* no operator class specified, so find the default */
1339  opClassId = GetDefaultOpClass(attrType, accessMethodId);
1340  if (!OidIsValid(opClassId))
1341  ereport(ERROR,
1342  (errcode(ERRCODE_UNDEFINED_OBJECT),
1343  errmsg("data type %s has no default operator class for access method \"%s\"",
1344  format_type_be(attrType), accessMethodName),
1345  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
1346  return opClassId;
1347  }
1348 
1349  /*
1350  * Specific opclass name given, so look up the opclass.
1351  */
1352 
1353  /* deconstruct the name list */
1354  DeconstructQualifiedName(opclass, &schemaname, &opcname);
1355 
1356  if (schemaname)
1357  {
1358  /* Look in specific schema only */
1359  Oid namespaceId;
1360 
1361  namespaceId = LookupExplicitNamespace(schemaname, false);
1362  tuple = SearchSysCache3(CLAAMNAMENSP,
1363  ObjectIdGetDatum(accessMethodId),
1364  PointerGetDatum(opcname),
1365  ObjectIdGetDatum(namespaceId));
1366  }
1367  else
1368  {
1369  /* Unqualified opclass name, so search the search path */
1370  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
1371  if (!OidIsValid(opClassId))
1372  ereport(ERROR,
1373  (errcode(ERRCODE_UNDEFINED_OBJECT),
1374  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1375  opcname, accessMethodName)));
1376  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
1377  }
1378 
1379  if (!HeapTupleIsValid(tuple))
1380  ereport(ERROR,
1381  (errcode(ERRCODE_UNDEFINED_OBJECT),
1382  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
1383  NameListToString(opclass), accessMethodName)));
1384 
1385  /*
1386  * Verify that the index operator class accepts this datatype. Note we
1387  * will accept binary compatibility.
1388  */
1389  opClassId = HeapTupleGetOid(tuple);
1390  opInputType = ((Form_pg_opclass) GETSTRUCT(tuple))->opcintype;
1391 
1392  if (!IsBinaryCoercible(attrType, opInputType))
1393  ereport(ERROR,
1394  (errcode(ERRCODE_DATATYPE_MISMATCH),
1395  errmsg("operator class \"%s\" does not accept data type %s",
1396  NameListToString(opclass), format_type_be(attrType))));
1397 
1398  ReleaseSysCache(tuple);
1399 
1400  return opClassId;
1401 }
1402 
1403 /*
1404  * GetDefaultOpClass
1405  *
1406  * Given the OIDs of a datatype and an access method, find the default
1407  * operator class, if any. Returns InvalidOid if there is none.
1408  */
1409 Oid
1410 GetDefaultOpClass(Oid type_id, Oid am_id)
1411 {
1412  Oid result = InvalidOid;
1413  int nexact = 0;
1414  int ncompatible = 0;
1415  int ncompatiblepreferred = 0;
1416  Relation rel;
1417  ScanKeyData skey[1];
1418  SysScanDesc scan;
1419  HeapTuple tup;
1420  TYPCATEGORY tcategory;
1421 
1422  /* If it's a domain, look at the base type instead */
1423  type_id = getBaseType(type_id);
1424 
1425  tcategory = TypeCategory(type_id);
1426 
1427  /*
1428  * We scan through all the opclasses available for the access method,
1429  * looking for one that is marked default and matches the target type
1430  * (either exactly or binary-compatibly, but prefer an exact match).
1431  *
1432  * We could find more than one binary-compatible match. If just one is
1433  * for a preferred type, use that one; otherwise we fail, forcing the user
1434  * to specify which one he wants. (The preferred-type special case is a
1435  * kluge for varchar: it's binary-compatible to both text and bpchar, so
1436  * we need a tiebreaker.) If we find more than one exact match, then
1437  * someone put bogus entries in pg_opclass.
1438  */
1440 
1441  ScanKeyInit(&skey[0],
1443  BTEqualStrategyNumber, F_OIDEQ,
1444  ObjectIdGetDatum(am_id));
1445 
1446  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
1447  NULL, 1, skey);
1448 
1449  while (HeapTupleIsValid(tup = systable_getnext(scan)))
1450  {
1451  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
1452 
1453  /* ignore altogether if not a default opclass */
1454  if (!opclass->opcdefault)
1455  continue;
1456  if (opclass->opcintype == type_id)
1457  {
1458  nexact++;
1459  result = HeapTupleGetOid(tup);
1460  }
1461  else if (nexact == 0 &&
1462  IsBinaryCoercible(type_id, opclass->opcintype))
1463  {
1464  if (IsPreferredType(tcategory, opclass->opcintype))
1465  {
1466  ncompatiblepreferred++;
1467  result = HeapTupleGetOid(tup);
1468  }
1469  else if (ncompatiblepreferred == 0)
1470  {
1471  ncompatible++;
1472  result = HeapTupleGetOid(tup);
1473  }
1474  }
1475  }
1476 
1477  systable_endscan(scan);
1478 
1480 
1481  /* raise error if pg_opclass contains inconsistent data */
1482  if (nexact > 1)
1483  ereport(ERROR,
1485  errmsg("there are multiple default operator classes for data type %s",
1486  format_type_be(type_id))));
1487 
1488  if (nexact == 1 ||
1489  ncompatiblepreferred == 1 ||
1490  (ncompatiblepreferred == 0 && ncompatible == 1))
1491  return result;
1492 
1493  return InvalidOid;
1494 }
1495 
1496 /*
1497  * makeObjectName()
1498  *
1499  * Create a name for an implicitly created index, sequence, constraint, etc.
1500  *
1501  * The parameters are typically: the original table name, the original field
1502  * name, and a "type" string (such as "seq" or "pkey"). The field name
1503  * and/or type can be NULL if not relevant.
1504  *
1505  * The result is a palloc'd string.
1506  *
1507  * The basic result we want is "name1_name2_label", omitting "_name2" or
1508  * "_label" when those parameters are NULL. However, we must generate
1509  * a name with less than NAMEDATALEN characters! So, we truncate one or
1510  * both names if necessary to make a short-enough string. The label part
1511  * is never truncated (so it had better be reasonably short).
1512  *
1513  * The caller is responsible for checking uniqueness of the generated
1514  * name and retrying as needed; retrying will be done by altering the
1515  * "label" string (which is why we never truncate that part).
1516  */
1517 char *
1518 makeObjectName(const char *name1, const char *name2, const char *label)
1519 {
1520  char *name;
1521  int overhead = 0; /* chars needed for label and underscores */
1522  int availchars; /* chars available for name(s) */
1523  int name1chars; /* chars allocated to name1 */
1524  int name2chars; /* chars allocated to name2 */
1525  int ndx;
1526 
1527  name1chars = strlen(name1);
1528  if (name2)
1529  {
1530  name2chars = strlen(name2);
1531  overhead++; /* allow for separating underscore */
1532  }
1533  else
1534  name2chars = 0;
1535  if (label)
1536  overhead += strlen(label) + 1;
1537 
1538  availchars = NAMEDATALEN - 1 - overhead;
1539  Assert(availchars > 0); /* else caller chose a bad label */
1540 
1541  /*
1542  * If we must truncate, preferentially truncate the longer name. This
1543  * logic could be expressed without a loop, but it's simple and obvious as
1544  * a loop.
1545  */
1546  while (name1chars + name2chars > availchars)
1547  {
1548  if (name1chars > name2chars)
1549  name1chars--;
1550  else
1551  name2chars--;
1552  }
1553 
1554  name1chars = pg_mbcliplen(name1, name1chars, name1chars);
1555  if (name2)
1556  name2chars = pg_mbcliplen(name2, name2chars, name2chars);
1557 
1558  /* Now construct the string using the chosen lengths */
1559  name = palloc(name1chars + name2chars + overhead + 1);
1560  memcpy(name, name1, name1chars);
1561  ndx = name1chars;
1562  if (name2)
1563  {
1564  name[ndx++] = '_';
1565  memcpy(name + ndx, name2, name2chars);
1566  ndx += name2chars;
1567  }
1568  if (label)
1569  {
1570  name[ndx++] = '_';
1571  strcpy(name + ndx, label);
1572  }
1573  else
1574  name[ndx] = '\0';
1575 
1576  return name;
1577 }
1578 
1579 /*
1580  * Select a nonconflicting name for a new relation. This is ordinarily
1581  * used to choose index names (which is why it's here) but it can also
1582  * be used for sequences, or any autogenerated relation kind.
1583  *
1584  * name1, name2, and label are used the same way as for makeObjectName(),
1585  * except that the label can't be NULL; digits will be appended to the label
1586  * if needed to create a name that is unique within the specified namespace.
1587  *
1588  * Note: it is theoretically possible to get a collision anyway, if someone
1589  * else chooses the same name concurrently. This is fairly unlikely to be
1590  * a problem in practice, especially if one is holding an exclusive lock on
1591  * the relation identified by name1. However, if choosing multiple names
1592  * within a single command, you'd better create the new object and do
1593  * CommandCounterIncrement before choosing the next one!
1594  *
1595  * Returns a palloc'd string.
1596  */
1597 char *
1598 ChooseRelationName(const char *name1, const char *name2,
1599  const char *label, Oid namespaceid)
1600 {
1601  int pass = 0;
1602  char *relname = NULL;
1603  char modlabel[NAMEDATALEN];
1604 
1605  /* try the unmodified label first */
1606  StrNCpy(modlabel, label, sizeof(modlabel));
1607 
1608  for (;;)
1609  {
1610  relname = makeObjectName(name1, name2, modlabel);
1611 
1612  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
1613  break;
1614 
1615  /* found a conflict, so try a new name component */
1616  pfree(relname);
1617  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
1618  }
1619 
1620  return relname;
1621 }
1622 
1623 /*
1624  * Select the name to be used for an index.
1625  *
1626  * The argument list is pretty ad-hoc :-(
1627  */
1628 static char *
1629 ChooseIndexName(const char *tabname, Oid namespaceId,
1630  List *colnames, List *exclusionOpNames,
1631  bool primary, bool isconstraint)
1632 {
1633  char *indexname;
1634 
1635  if (primary)
1636  {
1637  /* the primary key's name does not depend on the specific column(s) */
1638  indexname = ChooseRelationName(tabname,
1639  NULL,
1640  "pkey",
1641  namespaceId);
1642  }
1643  else if (exclusionOpNames != NIL)
1644  {
1645  indexname = ChooseRelationName(tabname,
1646  ChooseIndexNameAddition(colnames),
1647  "excl",
1648  namespaceId);
1649  }
1650  else if (isconstraint)
1651  {
1652  indexname = ChooseRelationName(tabname,
1653  ChooseIndexNameAddition(colnames),
1654  "key",
1655  namespaceId);
1656  }
1657  else
1658  {
1659  indexname = ChooseRelationName(tabname,
1660  ChooseIndexNameAddition(colnames),
1661  "idx",
1662  namespaceId);
1663  }
1664 
1665  return indexname;
1666 }
1667 
1668 /*
1669  * Generate "name2" for a new index given the list of column names for it
1670  * (as produced by ChooseIndexColumnNames). This will be passed to
1671  * ChooseRelationName along with the parent table name and a suitable label.
1672  *
1673  * We know that less than NAMEDATALEN characters will actually be used,
1674  * so we can truncate the result once we've generated that many.
1675  */
1676 static char *
1678 {
1679  char buf[NAMEDATALEN * 2];
1680  int buflen = 0;
1681  ListCell *lc;
1682 
1683  buf[0] = '\0';
1684  foreach(lc, colnames)
1685  {
1686  const char *name = (const char *) lfirst(lc);
1687 
1688  if (buflen > 0)
1689  buf[buflen++] = '_'; /* insert _ between names */
1690 
1691  /*
1692  * At this point we have buflen <= NAMEDATALEN. name should be less
1693  * than NAMEDATALEN already, but use strlcpy for paranoia.
1694  */
1695  strlcpy(buf + buflen, name, NAMEDATALEN);
1696  buflen += strlen(buf + buflen);
1697  if (buflen >= NAMEDATALEN)
1698  break;
1699  }
1700  return pstrdup(buf);
1701 }
1702 
1703 /*
1704  * Select the actual names to be used for the columns of an index, given the
1705  * list of IndexElems for the columns. This is mostly about ensuring the
1706  * names are unique so we don't get a conflicting-attribute-names error.
1707  *
1708  * Returns a List of plain strings (char *, not String nodes).
1709  */
1710 static List *
1712 {
1713  List *result = NIL;
1714  ListCell *lc;
1715 
1716  foreach(lc, indexElems)
1717  {
1718  IndexElem *ielem = (IndexElem *) lfirst(lc);
1719  const char *origname;
1720  const char *curname;
1721  int i;
1722  char buf[NAMEDATALEN];
1723 
1724  /* Get the preliminary name from the IndexElem */
1725  if (ielem->indexcolname)
1726  origname = ielem->indexcolname; /* caller-specified name */
1727  else if (ielem->name)
1728  origname = ielem->name; /* simple column reference */
1729  else
1730  origname = "expr"; /* default name for expression */
1731 
1732  /* If it conflicts with any previous column, tweak it */
1733  curname = origname;
1734  for (i = 1;; i++)
1735  {
1736  ListCell *lc2;
1737  char nbuf[32];
1738  int nlen;
1739 
1740  foreach(lc2, result)
1741  {
1742  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
1743  break;
1744  }
1745  if (lc2 == NULL)
1746  break; /* found nonconflicting name */
1747 
1748  sprintf(nbuf, "%d", i);
1749 
1750  /* Ensure generated names are shorter than NAMEDATALEN */
1751  nlen = pg_mbcliplen(origname, strlen(origname),
1752  NAMEDATALEN - 1 - strlen(nbuf));
1753  memcpy(buf, origname, nlen);
1754  strcpy(buf + nlen, nbuf);
1755  curname = buf;
1756  }
1757 
1758  /* And attach to the result list */
1759  result = lappend(result, pstrdup(curname));
1760  }
1761  return result;
1762 }
1763 
1764 /*
1765  * ReindexIndex
1766  * Recreate a specific index.
1767  */
1768 Oid
1769 ReindexIndex(RangeVar *indexRelation, int options)
1770 {
1771  Oid indOid;
1772  Oid heapOid = InvalidOid;
1773  Relation irel;
1774  char persistence;
1775 
1776  /*
1777  * Find and lock index, and check permissions on table; use callback to
1778  * obtain lock on table first, to avoid deadlock hazard. The lock level
1779  * used here must match the index lock obtained in reindex_index().
1780  */
1781  indOid = RangeVarGetRelidExtended(indexRelation, AccessExclusiveLock,
1782  false, false,
1784  (void *) &heapOid);
1785 
1786  /*
1787  * Obtain the current persistence of the existing index. We already hold
1788  * lock on the index.
1789  */
1790  irel = index_open(indOid, NoLock);
1791  persistence = irel->rd_rel->relpersistence;
1792  index_close(irel, NoLock);
1793 
1794  reindex_index(indOid, false, persistence, options);
1795 
1796  return indOid;
1797 }
1798 
1799 /*
1800  * Check permissions on table before acquiring relation lock; also lock
1801  * the heap before the RangeVarGetRelidExtended takes the index lock, to avoid
1802  * deadlocks.
1803  */
1804 static void
1806  Oid relId, Oid oldRelId, void *arg)
1807 {
1808  char relkind;
1809  Oid *heapOid = (Oid *) arg;
1810 
1811  /*
1812  * If we previously locked some other index's heap, and the name we're
1813  * looking up no longer refers to that relation, release the now-useless
1814  * lock.
1815  */
1816  if (relId != oldRelId && OidIsValid(oldRelId))
1817  {
1818  /* lock level here should match reindex_index() heap lock */
1819  UnlockRelationOid(*heapOid, ShareLock);
1820  *heapOid = InvalidOid;
1821  }
1822 
1823  /* If the relation does not exist, there's nothing more to do. */
1824  if (!OidIsValid(relId))
1825  return;
1826 
1827  /*
1828  * If the relation does exist, check whether it's an index. But note that
1829  * the relation might have been dropped between the time we did the name
1830  * lookup and now. In that case, there's nothing to do.
1831  */
1832  relkind = get_rel_relkind(relId);
1833  if (!relkind)
1834  return;
1835  if (relkind != RELKIND_INDEX)
1836  ereport(ERROR,
1837  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1838  errmsg("\"%s\" is not an index", relation->relname)));
1839 
1840  /* Check permissions */
1841  if (!pg_class_ownercheck(relId, GetUserId()))
1843 
1844  /* Lock heap before index to avoid deadlock. */
1845  if (relId != oldRelId)
1846  {
1847  /*
1848  * Lock level here should match reindex_index() heap lock. If the OID
1849  * isn't valid, it means the index as concurrently dropped, which is
1850  * not a problem for us; just return normally.
1851  */
1852  *heapOid = IndexGetRelation(relId, true);
1853  if (OidIsValid(*heapOid))
1854  LockRelationOid(*heapOid, ShareLock);
1855  }
1856 }
1857 
1858 /*
1859  * ReindexTable
1860  * Recreate all indexes of a table (and of its toast table, if any)
1861  */
1862 Oid
1864 {
1865  Oid heapOid;
1866 
1867  /* The lock level used here should match reindex_relation(). */
1868  heapOid = RangeVarGetRelidExtended(relation, ShareLock, false, false,
1870 
1871  if (!reindex_relation(heapOid,
1874  options))
1875  ereport(NOTICE,
1876  (errmsg("table \"%s\" has no indexes",
1877  relation->relname)));
1878 
1879  return heapOid;
1880 }
1881 
1882 /*
1883  * ReindexMultipleTables
1884  * Recreate indexes of tables selected by objectName/objectKind.
1885  *
1886  * To reduce the probability of deadlocks, each table is reindexed in a
1887  * separate transaction, so we can release the lock on it right away.
1888  * That means this must not be called within a user transaction block!
1889  */
1890 void
1891 ReindexMultipleTables(const char *objectName, ReindexObjectType objectKind,
1892  int options)
1893 {
1894  Oid objectOid;
1895  Relation relationRelation;
1896  HeapScanDesc scan;
1897  ScanKeyData scan_keys[1];
1898  HeapTuple tuple;
1899  MemoryContext private_context;
1900  MemoryContext old;
1901  List *relids = NIL;
1902  ListCell *l;
1903  int num_keys;
1904 
1905  AssertArg(objectName);
1906  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
1907  objectKind == REINDEX_OBJECT_SYSTEM ||
1908  objectKind == REINDEX_OBJECT_DATABASE);
1909 
1910  /*
1911  * Get OID of object to reindex, being the database currently being used
1912  * by session for a database or for system catalogs, or the schema defined
1913  * by caller. At the same time do permission checks that need different
1914  * processing depending on the object type.
1915  */
1916  if (objectKind == REINDEX_OBJECT_SCHEMA)
1917  {
1918  objectOid = get_namespace_oid(objectName, false);
1919 
1920  if (!pg_namespace_ownercheck(objectOid, GetUserId()))
1922  objectName);
1923  }
1924  else
1925  {
1926  objectOid = MyDatabaseId;
1927 
1928  if (strcmp(objectName, get_database_name(objectOid)) != 0)
1929  ereport(ERROR,
1930  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1931  errmsg("can only reindex the currently open database")));
1932  if (!pg_database_ownercheck(objectOid, GetUserId()))
1934  objectName);
1935  }
1936 
1937  /*
1938  * Create a memory context that will survive forced transaction commits we
1939  * do below. Since it is a child of PortalContext, it will go away
1940  * eventually even if we suffer an error; there's no need for special
1941  * abort cleanup logic.
1942  */
1943  private_context = AllocSetContextCreate(PortalContext,
1944  "ReindexMultipleTables",
1946 
1947  /*
1948  * Define the search keys to find the objects to reindex. For a schema, we
1949  * select target relations using relnamespace, something not necessary for
1950  * a database-wide operation.
1951  */
1952  if (objectKind == REINDEX_OBJECT_SCHEMA)
1953  {
1954  num_keys = 1;
1955  ScanKeyInit(&scan_keys[0],
1957  BTEqualStrategyNumber, F_OIDEQ,
1958  ObjectIdGetDatum(objectOid));
1959  }
1960  else
1961  num_keys = 0;
1962 
1963  /*
1964  * Scan pg_class to build a list of the relations we need to reindex.
1965  *
1966  * We only consider plain relations and materialized views here (toast
1967  * rels will be processed indirectly by reindex_relation).
1968  */
1969  relationRelation = heap_open(RelationRelationId, AccessShareLock);
1970  scan = heap_beginscan_catalog(relationRelation, num_keys, scan_keys);
1971  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1972  {
1973  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
1974  Oid relid = HeapTupleGetOid(tuple);
1975 
1976  /*
1977  * Only regular tables and matviews can have indexes, so ignore any
1978  * other kind of relation.
1979  */
1980  if (classtuple->relkind != RELKIND_RELATION &&
1981  classtuple->relkind != RELKIND_MATVIEW)
1982  continue;
1983 
1984  /* Skip temp tables of other backends; we can't reindex them at all */
1985  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
1986  !isTempNamespace(classtuple->relnamespace))
1987  continue;
1988 
1989  /* Check user/system classification, and optionally skip */
1990  if (objectKind == REINDEX_OBJECT_SYSTEM &&
1991  !IsSystemClass(relid, classtuple))
1992  continue;
1993 
1994  /* Save the list of relation OIDs in private context */
1995  old = MemoryContextSwitchTo(private_context);
1996 
1997  /*
1998  * We always want to reindex pg_class first if it's selected to be
1999  * reindexed. This ensures that if there is any corruption in
2000  * pg_class' indexes, they will be fixed before we process any other
2001  * tables. This is critical because reindexing itself will try to
2002  * update pg_class.
2003  */
2004  if (relid == RelationRelationId)
2005  relids = lcons_oid(relid, relids);
2006  else
2007  relids = lappend_oid(relids, relid);
2008 
2009  MemoryContextSwitchTo(old);
2010  }
2011  heap_endscan(scan);
2012  heap_close(relationRelation, AccessShareLock);
2013 
2014  /* Now reindex each rel in a separate transaction */
2017  foreach(l, relids)
2018  {
2019  Oid relid = lfirst_oid(l);
2020 
2022  /* functions in indexes may want a snapshot set */
2024  if (reindex_relation(relid,
2027  options))
2028 
2029  if (options & REINDEXOPT_VERBOSE)
2030  ereport(INFO,
2031  (errmsg("table \"%s.%s\" was reindexed",
2033  get_rel_name(relid))));
2036  }
2038 
2039  MemoryContextDelete(private_context);
2040 }
bool deferrable
Definition: parsenodes.h:2724
signed short int16
Definition: c.h:293
#define NIL
Definition: pg_list.h:69
Definition: c.h:536
bool primary
Definition: parsenodes.h:2722
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:2474
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1380
#define INDOPTION_NULLS_FIRST
Definition: pg_index.h:100
MemoryContext ii_Context
Definition: execnodes.h:162
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3284
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5024
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:142
bool CheckIndexCompatible(Oid oldId, const char *accessMethodName, List *attributeList, List *exclusionOpNames)
Definition: indexcmds.c:117
LockRelId lockRelId
Definition: rel.h:44
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:13079
bool amcanmulticol
Definition: amapi.h:179
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:970
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4554
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:198
#define Anum_pg_opclass_opcmethod
Definition: pg_opclass.h:75
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3005
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:1677
#define DEBUG1
Definition: elog.h:25
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2853
int errhint(const char *fmt,...)
Definition: elog.c:987
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1410
SortByDir ordering
Definition: parsenodes.h:693
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
List * ii_Predicate
Definition: execnodes.h:149
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1565
List * options
Definition: parsenodes.h:2715
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
uint32 TransactionId
Definition: c.h:455
#define INDEX_CREATE_IF_NOT_EXISTS
Definition: index.h:49
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:863
amgettuple_function amgettuple
Definition: amapi.h:210
Oid ReindexTable(RangeVar *relation, int options)
Definition: indexcmds.c:1863
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:284
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3205
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:182
uint16 bits16
Definition: c.h:314
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:218
#define PointerGetDatum(X)
Definition: postgres.h:562
char * tableSpace
Definition: parsenodes.h:2713
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1820
ExprState * ii_PredicateState
Definition: execnodes.h:150
char * pstrdup(const char *in)
Definition: mcxt.c:1063
void CommitTransactionCommand(void)
Definition: xact.c:2745
#define RelationRelationId
Definition: pg_class.h:29
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:207
Oid dbId
Definition: rel.h:39
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1769
Expr * expression_planner(Expr *expr)
Definition: planner.c:6026
#define RELKIND_MATVIEW
Definition: pg_class.h:165
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Node * whereClause
Definition: parsenodes.h:2716
#define Anum_pg_index_indclass
Definition: pg_index.h:89
Definition: lock.h:178
#define AccessShareLock
Definition: lockdefs.h:36
#define OperatorClassRelationId
Definition: pg_opclass.h:49
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table)
Definition: index.c:195
Definition: nodes.h:512
Oid * ii_ExclusionProcs
Definition: execnodes.h:152
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
#define INFO
Definition: elog.h:33
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
Oid ReindexIndex(RangeVar *indexRelation, int options)
Definition: indexcmds.c:1769
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
char * format_operator(Oid operator_oid)
Definition: regproc.c:820
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2769
bool pg_namespace_ownercheck(Oid nsp_oid, Oid roleid)
Definition: aclchk.c:4780
List * lcons_oid(Oid datum, List *list)
Definition: list.c:295
#define heap_close(r, l)
Definition: heapam.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1645
static List * ChooseIndexColumnNames(List *indexElems)
Definition: indexcmds.c:1711
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:1760
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define OidIsValid(objectId)
Definition: c.h:586
ReindexObjectType
Definition: parsenodes.h:3255
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4542
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
#define OpclassAmNameNspIndexId
Definition: indexing.h:198
bool IsPreferredType(TYPCATEGORY category, Oid type)
#define Anum_pg_class_relnamespace
Definition: pg_class.h:104
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
#define REINDEXOPT_VERBOSE
Definition: parsenodes.h:3253
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:755
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1111
Oid MyDatabaseTableSpace
Definition: globals.c:79
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:75
MemoryContext PortalContext
Definition: mcxt.c:52
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:70
bool VirtualXactLock(VirtualTransactionId vxid, bool wait)
Definition: lock.c:4291
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:1518
#define NAMEDATALEN
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:74
char * relname
Definition: primnodes.h:68
Node * expr
Definition: parsenodes.h:689
char TYPCATEGORY
Definition: parse_coerce.h:21
RangeVar * relation
Definition: parsenodes.h:2711
List * ii_ExpressionsState
Definition: execnodes.h:148
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
unsigned short uint16
Definition: c.h:305
void pfree(void *pointer)
Definition: mcxt.c:936
#define PROC_IN_VACUUM
Definition: proc.h:54
#define linitial(l)
Definition: pg_list.h:111
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:381
SortByNulls nulls_ordering
Definition: parsenodes.h:694
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:312
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Definition: rel.h:36
#define ACL_CREATE
Definition: parsenodes.h:82
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:299
amoptions_function amoptions
Definition: amapi.h:205
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:820
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1702
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
bool amcanunique
Definition: amapi.h:177
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:193
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3066
#define NoLock
Definition: lockdefs.h:34
LockInfoData rd_lockInfo
Definition: rel.h:117
static char * buf
Definition: pg_test_fsync.c:67
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:544
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:296
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3457
Oid ResolveOpClass(List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
Definition: indexcmds.c:1299
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * indexcolname
Definition: parsenodes.h:690
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1292
#define RelationGetRelationName(relation)
Definition: rel.h:445
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
bool ii_BrokenHotChain
Definition: execnodes.h:160
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3118
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1167
TransactionId xmin
Definition: snapshot.h:68
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1405
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:3062
#define lnext(lc)
Definition: pg_list.h:105
bool ii_ReadyForInserts
Definition: execnodes.h:158
#define ereport(elevel, rest)
Definition: elog.h:122
#define AssertArg(condition)
Definition: c.h:682
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5022
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:510
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:905
bool IsBinaryCoercible(Oid srctype, Oid targettype)
void ReindexMultipleTables(const char *objectName, ReindexObjectType objectKind, int options)
Definition: indexcmds.c:1891
List * lappend(List *list, void *datum)
Definition: list.c:128
void * ii_AmCache
Definition: execnodes.h:161
char * idxname
Definition: parsenodes.h:2710
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
void index_build(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool isprimary, bool isreindex)
Definition: index.c:2009
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:71
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:2808
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:1805
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
char * NameListToString(List *names)
Definition: namespace.c:3063
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:44
bool if_not_exists
Definition: parsenodes.h:2728
AclResult
Definition: acl.h:178
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
int ii_NumIndexAttrs
Definition: execnodes.h:145
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
static char * label
Definition: pg_basebackup.c:82
Oid MyDatabaseId
Definition: globals.c:77
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1808
bool unique
Definition: parsenodes.h:2721
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
TupleDesc rd_att
Definition: rel.h:115
char * accessMethod
Definition: parsenodes.h:2712
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:45
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode)
Definition: lmgr.c:837
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
bool allowSystemTableMods
Definition: globals.c:112
#define InvalidOid
Definition: postgres_ext.h:36
#define INDEX_CREATE_CONCURRENT
Definition: index.h:48
TYPCATEGORY TypeCategory(Oid type)
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
bytea * index_reloptions(amoptions_function amoptions, Datum reloptions, bool validate)
Definition: reloptions.c:1459
List * opclass
Definition: parsenodes.h:692
#define NOTICE
Definition: elog.h:37
#define Anum_pg_index_indpred
Definition: pg_index.h:92
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
bool ii_Unique
Definition: execnodes.h:157
#define makeNode(_type_)
Definition: nodes.h:560
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
List * ii_Expressions
Definition: execnodes.h:147
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
#define StrNCpy(dst, src, len)
Definition: c.h:850
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal)
Definition: index.c:706
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:542
#define INDOPTION_DESC
Definition: pg_index.h:99
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4604
void StartTransactionCommand(void)
Definition: xact.c:2674
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:77
List * indexParams
Definition: parsenodes.h:2714
static void CheckPredicate(Expr *predicate)
Definition: indexcmds.c:1004
#define INDEX_MAX_KEYS
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
List * excludeOpNames
Definition: parsenodes.h:2717
static int list_length(const List *l)
Definition: pg_list.h:89
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:127
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:146
bool initdeferred
Definition: parsenodes.h:2725
bool amcanorder
Definition: amapi.h:171
char * name
Definition: parsenodes.h:688
char * idxcomment
Definition: parsenodes.h:2718
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1248
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1047
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, int options)
Definition: index.c:3309
bool ii_Concurrent
Definition: execnodes.h:159
const char * name
Definition: encode.c:521
#define InvalidAttrNumber
Definition: attnum.h:23
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
#define DatumGetPointer(X)
Definition: postgres.h:555
#define Anum_pg_index_indcollation
Definition: pg_index.h:88
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:367
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define INDEX_CREATE_SKIP_BUILD
Definition: index.h:47
bool concurrent
Definition: parsenodes.h:2727
#define AccessExclusiveLock
Definition: lockdefs.h:45
bool isconstraint
Definition: parsenodes.h:2723
Oid * ii_ExclusionOps
Definition: execnodes.h:151
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
void * palloc(Size size)
Definition: mcxt.c:835
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:494
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:308
#define ShareLock
Definition: lockdefs.h:41
int i
#define NameStr(name)
Definition: c.h:557
#define RELKIND_INDEX
Definition: pg_class.h:161
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
Definition: indexcmds.c:1026
void * arg
List * collation
Definition: parsenodes.h:691
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:125
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:881
static char * ChooseIndexName(const char *tabname, Oid namespaceId, List *colnames, List *exclusionOpNames, bool primary, bool isconstraint)
Definition: indexcmds.c:1629
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: indexcmds.c:1598
bytea *(* amoptions_function)(Datum reloptions, bool validate)
Definition: amapi.h:102
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
uint16 * ii_ExclusionStrats
Definition: execnodes.h:153
#define INDEX_CREATE_ADD_CONSTRAINT
Definition: index.h:46
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2290
#define RELKIND_RELATION
Definition: pg_class.h:160
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:2839
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
bool reindex_relation(Oid relid, int flags, int options)
Definition: index.c:3518
Oid get_collation_oid(List *name, bool missing_ok)
Definition: namespace.c:3493
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1745
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:464
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:425
#define INDEX_CONSTR_CREATE_DEFERRABLE
Definition: index.h:69
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define PROC_IS_AUTOVACUUM
Definition: proc.h:53
#define lfirst_oid(lc)
Definition: pg_list.h:108
#define Anum_pg_index_indexprs
Definition: pg_index.h:91
Oid relId
Definition: rel.h:38
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1069
#define RelationGetNamespace(relation)
Definition: rel.h:452