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-2022, 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/heapam.h"
20 #include "access/htup_details.h"
21 #include "access/reloptions.h"
22 #include "access/sysattr.h"
23 #include "access/tableam.h"
24 #include "access/xact.h"
25 #include "catalog/catalog.h"
26 #include "catalog/index.h"
27 #include "catalog/indexing.h"
28 #include "catalog/pg_am.h"
29 #include "catalog/pg_constraint.h"
30 #include "catalog/pg_database.h"
31 #include "catalog/pg_inherits.h"
32 #include "catalog/pg_namespace.h"
33 #include "catalog/pg_opclass.h"
34 #include "catalog/pg_opfamily.h"
35 #include "catalog/pg_tablespace.h"
36 #include "catalog/pg_type.h"
37 #include "commands/comment.h"
38 #include "commands/dbcommands.h"
39 #include "commands/defrem.h"
40 #include "commands/event_trigger.h"
41 #include "commands/progress.h"
42 #include "commands/tablecmds.h"
43 #include "commands/tablespace.h"
44 #include "mb/pg_wchar.h"
45 #include "miscadmin.h"
46 #include "nodes/makefuncs.h"
47 #include "nodes/nodeFuncs.h"
48 #include "optimizer/optimizer.h"
49 #include "parser/parse_coerce.h"
50 #include "parser/parse_func.h"
51 #include "parser/parse_oper.h"
52 #include "partitioning/partdesc.h"
53 #include "pgstat.h"
54 #include "rewrite/rewriteManip.h"
55 #include "storage/lmgr.h"
56 #include "storage/proc.h"
57 #include "storage/procarray.h"
58 #include "storage/sinvaladt.h"
59 #include "utils/acl.h"
60 #include "utils/builtins.h"
61 #include "utils/fmgroids.h"
62 #include "utils/guc.h"
63 #include "utils/inval.h"
64 #include "utils/lsyscache.h"
65 #include "utils/memutils.h"
66 #include "utils/partcache.h"
67 #include "utils/pg_rusage.h"
68 #include "utils/regproc.h"
69 #include "utils/snapmgr.h"
70 #include "utils/syscache.h"
71 
72 
73 /* non-export function prototypes */
74 static bool CompareOpclassOptions(Datum *opts1, Datum *opts2, int natts);
75 static void CheckPredicate(Expr *predicate);
76 static void ComputeIndexAttrs(IndexInfo *indexInfo,
77  Oid *typeOidP,
78  Oid *collationOidP,
79  Oid *classOidP,
80  int16 *colOptionP,
81  List *attList,
82  List *exclusionOpNames,
83  Oid relId,
84  const char *accessMethodName, Oid accessMethodId,
85  bool amcanorder,
86  bool isconstraint,
87  Oid ddl_userid,
88  int ddl_sec_context,
89  int *ddl_save_nestlevel);
90 static char *ChooseIndexName(const char *tabname, Oid namespaceId,
91  List *colnames, List *exclusionOpNames,
92  bool primary, bool isconstraint);
93 static char *ChooseIndexNameAddition(List *colnames);
94 static List *ChooseIndexColumnNames(List *indexElems);
95 static void ReindexIndex(RangeVar *indexRelation, ReindexParams *params,
96  bool isTopLevel);
97 static void RangeVarCallbackForReindexIndex(const RangeVar *relation,
98  Oid relId, Oid oldRelId, void *arg);
99 static Oid ReindexTable(RangeVar *relation, ReindexParams *params,
100  bool isTopLevel);
101 static void ReindexMultipleTables(const char *objectName,
102  ReindexObjectType objectKind, ReindexParams *params);
103 static void reindex_error_callback(void *arg);
104 static void ReindexPartitions(Oid relid, ReindexParams *params,
105  bool isTopLevel);
106 static void ReindexMultipleInternal(List *relids,
107  ReindexParams *params);
108 static bool ReindexRelationConcurrently(Oid relationOid,
109  ReindexParams *params);
110 static void update_relispartition(Oid relationId, bool newval);
111 static inline void set_indexsafe_procflags(void);
112 
113 /*
114  * callback argument type for RangeVarCallbackForReindexIndex()
115  */
117 {
118  ReindexParams params; /* options from statement */
119  Oid locked_table_oid; /* tracks previously locked table */
120 };
121 
122 /*
123  * callback arguments for reindex_error_callback()
124  */
125 typedef struct ReindexErrorInfo
126 {
127  char *relname;
129  char relkind;
131 
132 /*
133  * CheckIndexCompatible
134  * Determine whether an existing index definition is compatible with a
135  * prospective index definition, such that the existing index storage
136  * could become the storage of the new index, avoiding a rebuild.
137  *
138  * 'oldId': the OID of the existing index
139  * 'accessMethodName': name of the AM to use.
140  * 'attributeList': a list of IndexElem specifying columns and expressions
141  * to index on.
142  * 'exclusionOpNames': list of names of exclusion-constraint operators,
143  * or NIL if not an exclusion constraint.
144  *
145  * This is tailored to the needs of ALTER TABLE ALTER TYPE, which recreates
146  * any indexes that depended on a changing column from their pg_get_indexdef
147  * or pg_get_constraintdef definitions. We omit some of the sanity checks of
148  * DefineIndex. We assume that the old and new indexes have the same number
149  * of columns and that if one has an expression column or predicate, both do.
150  * Errors arising from the attribute list still apply.
151  *
152  * Most column type changes that can skip a table rewrite do not invalidate
153  * indexes. We acknowledge this when all operator classes, collations and
154  * exclusion operators match. Though we could further permit intra-opfamily
155  * changes for btree and hash indexes, that adds subtle complexity with no
156  * concrete benefit for core types. Note, that INCLUDE columns aren't
157  * checked by this function, for them it's enough that table rewrite is
158  * skipped.
159  *
160  * When a comparison or exclusion operator has a polymorphic input type, the
161  * actual input types must also match. This defends against the possibility
162  * that operators could vary behavior in response to get_fn_expr_argtype().
163  * At present, this hazard is theoretical: check_exclusion_constraint() and
164  * all core index access methods decline to set fn_expr for such calls.
165  *
166  * We do not yet implement a test to verify compatibility of expression
167  * columns or predicates, so assume any such index is incompatible.
168  */
169 bool
171  const char *accessMethodName,
172  List *attributeList,
173  List *exclusionOpNames)
174 {
175  bool isconstraint;
176  Oid *typeObjectId;
177  Oid *collationObjectId;
178  Oid *classObjectId;
179  Oid accessMethodId;
180  Oid relationId;
181  HeapTuple tuple;
182  Form_pg_index indexForm;
183  Form_pg_am accessMethodForm;
184  IndexAmRoutine *amRoutine;
185  bool amcanorder;
186  int16 *coloptions;
187  IndexInfo *indexInfo;
188  int numberOfAttributes;
189  int old_natts;
190  bool isnull;
191  bool ret = true;
192  oidvector *old_indclass;
193  oidvector *old_indcollation;
194  Relation irel;
195  int i;
196  Datum d;
197 
198  /* Caller should already have the relation locked in some way. */
199  relationId = IndexGetRelation(oldId, false);
200 
201  /*
202  * We can pretend isconstraint = false unconditionally. It only serves to
203  * decide the text of an error message that should never happen for us.
204  */
205  isconstraint = false;
206 
207  numberOfAttributes = list_length(attributeList);
208  Assert(numberOfAttributes > 0);
209  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
210 
211  /* look up the access method */
212  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
213  if (!HeapTupleIsValid(tuple))
214  ereport(ERROR,
215  (errcode(ERRCODE_UNDEFINED_OBJECT),
216  errmsg("access method \"%s\" does not exist",
217  accessMethodName)));
218  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
219  accessMethodId = accessMethodForm->oid;
220  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
221  ReleaseSysCache(tuple);
222 
223  amcanorder = amRoutine->amcanorder;
224 
225  /*
226  * Compute the operator classes, collations, and exclusion operators for
227  * the new index, so we can test whether it's compatible with the existing
228  * one. Note that ComputeIndexAttrs might fail here, but that's OK:
229  * DefineIndex would have failed later. Our attributeList contains only
230  * key attributes, thus we're filling ii_NumIndexAttrs and
231  * ii_NumIndexKeyAttrs with same value.
232  */
233  indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
234  accessMethodId, NIL, NIL, false, false, false, false);
235  typeObjectId = palloc_array(Oid, numberOfAttributes);
236  collationObjectId = palloc_array(Oid, numberOfAttributes);
237  classObjectId = palloc_array(Oid, numberOfAttributes);
238  coloptions = palloc_array(int16, numberOfAttributes);
239  ComputeIndexAttrs(indexInfo,
240  typeObjectId, collationObjectId, classObjectId,
241  coloptions, attributeList,
242  exclusionOpNames, relationId,
243  accessMethodName, accessMethodId,
244  amcanorder, isconstraint, InvalidOid, 0, NULL);
245 
246 
247  /* Get the soon-obsolete pg_index tuple. */
249  if (!HeapTupleIsValid(tuple))
250  elog(ERROR, "cache lookup failed for index %u", oldId);
251  indexForm = (Form_pg_index) GETSTRUCT(tuple);
252 
253  /*
254  * We don't assess expressions or predicates; assume incompatibility.
255  * Also, if the index is invalid for any reason, treat it as incompatible.
256  */
257  if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) &&
258  heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) &&
259  indexForm->indisvalid))
260  {
261  ReleaseSysCache(tuple);
262  return false;
263  }
264 
265  /* Any change in operator class or collation breaks compatibility. */
266  old_natts = indexForm->indnkeyatts;
267  Assert(old_natts == numberOfAttributes);
268 
269  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indcollation, &isnull);
270  Assert(!isnull);
271  old_indcollation = (oidvector *) DatumGetPointer(d);
272 
273  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
274  Assert(!isnull);
275  old_indclass = (oidvector *) DatumGetPointer(d);
276 
277  ret = (memcmp(old_indclass->values, classObjectId,
278  old_natts * sizeof(Oid)) == 0 &&
279  memcmp(old_indcollation->values, collationObjectId,
280  old_natts * sizeof(Oid)) == 0);
281 
282  ReleaseSysCache(tuple);
283 
284  if (!ret)
285  return false;
286 
287  /* For polymorphic opcintype, column type changes break compatibility. */
288  irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
289  for (i = 0; i < old_natts; i++)
290  {
291  if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
292  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
293  {
294  ret = false;
295  break;
296  }
297  }
298 
299  /* Any change in opclass options break compatibility. */
300  if (ret)
301  {
302  Datum *opclassOptions = RelationGetIndexRawAttOptions(irel);
303 
304  ret = CompareOpclassOptions(opclassOptions,
305  indexInfo->ii_OpclassOptions, old_natts);
306 
307  if (opclassOptions)
308  pfree(opclassOptions);
309  }
310 
311  /* Any change in exclusion operator selections breaks compatibility. */
312  if (ret && indexInfo->ii_ExclusionOps != NULL)
313  {
314  Oid *old_operators,
315  *old_procs;
316  uint16 *old_strats;
317 
318  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
319  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
320  old_natts * sizeof(Oid)) == 0;
321 
322  /* Require an exact input type match for polymorphic operators. */
323  if (ret)
324  {
325  for (i = 0; i < old_natts && ret; i++)
326  {
327  Oid left,
328  right;
329 
330  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
331  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
332  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
333  {
334  ret = false;
335  break;
336  }
337  }
338  }
339  }
340 
341  index_close(irel, NoLock);
342  return ret;
343 }
344 
345 /*
346  * CompareOpclassOptions
347  *
348  * Compare per-column opclass options which are represented by arrays of text[]
349  * datums. Both elements of arrays and array themselves can be NULL.
350  */
351 static bool
352 CompareOpclassOptions(Datum *opts1, Datum *opts2, int natts)
353 {
354  int i;
355 
356  if (!opts1 && !opts2)
357  return true;
358 
359  for (i = 0; i < natts; i++)
360  {
361  Datum opt1 = opts1 ? opts1[i] : (Datum) 0;
362  Datum opt2 = opts2 ? opts2[i] : (Datum) 0;
363 
364  if (opt1 == (Datum) 0)
365  {
366  if (opt2 == (Datum) 0)
367  continue;
368  else
369  return false;
370  }
371  else if (opt2 == (Datum) 0)
372  return false;
373 
374  /* Compare non-NULL text[] datums. */
375  if (!DatumGetBool(DirectFunctionCall2(array_eq, opt1, opt2)))
376  return false;
377  }
378 
379  return true;
380 }
381 
382 /*
383  * WaitForOlderSnapshots
384  *
385  * Wait for transactions that might have an older snapshot than the given xmin
386  * limit, because it might not contain tuples deleted just before it has
387  * been taken. Obtain a list of VXIDs of such transactions, and wait for them
388  * individually. This is used when building an index concurrently.
389  *
390  * We can exclude any running transactions that have xmin > the xmin given;
391  * their oldest snapshot must be newer than our xmin limit.
392  * We can also exclude any transactions that have xmin = zero, since they
393  * evidently have no live snapshot at all (and any one they might be in
394  * process of taking is certainly newer than ours). Transactions in other
395  * DBs can be ignored too, since they'll never even be able to see the
396  * index being worked on.
397  *
398  * We can also exclude autovacuum processes and processes running manual
399  * lazy VACUUMs, because they won't be fazed by missing index entries
400  * either. (Manual ANALYZEs, however, can't be excluded because they
401  * might be within transactions that are going to do arbitrary operations
402  * later.) Processes running CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY
403  * on indexes that are neither expressional nor partial are also safe to
404  * ignore, since we know that those processes won't examine any data
405  * outside the table they're indexing.
406  *
407  * Also, GetCurrentVirtualXIDs never reports our own vxid, so we need not
408  * check for that.
409  *
410  * If a process goes idle-in-transaction with xmin zero, we do not need to
411  * wait for it anymore, per the above argument. We do not have the
412  * infrastructure right now to stop waiting if that happens, but we can at
413  * least avoid the folly of waiting when it is idle at the time we would
414  * begin to wait. We do this by repeatedly rechecking the output of
415  * GetCurrentVirtualXIDs. If, during any iteration, a particular vxid
416  * doesn't show up in the output, we know we can forget about it.
417  */
418 void
420 {
421  int n_old_snapshots;
422  int i;
423  VirtualTransactionId *old_snapshots;
424 
425  old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false,
427  | PROC_IN_SAFE_IC,
428  &n_old_snapshots);
429  if (progress)
431 
432  for (i = 0; i < n_old_snapshots; i++)
433  {
434  if (!VirtualTransactionIdIsValid(old_snapshots[i]))
435  continue; /* found uninteresting in previous cycle */
436 
437  if (i > 0)
438  {
439  /* see if anything's changed ... */
440  VirtualTransactionId *newer_snapshots;
441  int n_newer_snapshots;
442  int j;
443  int k;
444 
445  newer_snapshots = GetCurrentVirtualXIDs(limitXmin,
446  true, false,
448  | PROC_IN_SAFE_IC,
449  &n_newer_snapshots);
450  for (j = i; j < n_old_snapshots; j++)
451  {
452  if (!VirtualTransactionIdIsValid(old_snapshots[j]))
453  continue; /* found uninteresting in previous cycle */
454  for (k = 0; k < n_newer_snapshots; k++)
455  {
456  if (VirtualTransactionIdEquals(old_snapshots[j],
457  newer_snapshots[k]))
458  break;
459  }
460  if (k >= n_newer_snapshots) /* not there anymore */
461  SetInvalidVirtualTransactionId(old_snapshots[j]);
462  }
463  pfree(newer_snapshots);
464  }
465 
466  if (VirtualTransactionIdIsValid(old_snapshots[i]))
467  {
468  /* If requested, publish who we're going to wait for. */
469  if (progress)
470  {
471  PGPROC *holder = BackendIdGetProc(old_snapshots[i].backendId);
472 
473  if (holder)
475  holder->pid);
476  }
477  VirtualXactLock(old_snapshots[i], true);
478  }
479 
480  if (progress)
482  }
483 }
484 
485 
486 /*
487  * DefineIndex
488  * Creates a new index.
489  *
490  * This function manages the current userid according to the needs of pg_dump.
491  * Recreating old-database catalog entries in new-database is fine, regardless
492  * of which users would have permission to recreate those entries now. That's
493  * just preservation of state. Running opaque expressions, like calling a
494  * function named in a catalog entry or evaluating a pg_node_tree in a catalog
495  * entry, as anyone other than the object owner, is not fine. To adhere to
496  * those principles and to remain fail-safe, use the table owner userid for
497  * most ACL checks. Use the original userid for ACL checks reached without
498  * traversing opaque expressions. (pg_dump can predict such ACL checks from
499  * catalogs.) Overall, this is a mess. Future DDL development should
500  * consider offering one DDL command for catalog setup and a separate DDL
501  * command for steps that run opaque expressions.
502  *
503  * 'relationId': the OID of the heap relation on which the index is to be
504  * created
505  * 'stmt': IndexStmt describing the properties of the new index.
506  * 'indexRelationId': normally InvalidOid, but during bootstrap can be
507  * nonzero to specify a preselected OID for the index.
508  * 'parentIndexId': the OID of the parent index; InvalidOid if not the child
509  * of a partitioned index.
510  * 'parentConstraintId': the OID of the parent constraint; InvalidOid if not
511  * the child of a constraint (only used when recursing)
512  * 'is_alter_table': this is due to an ALTER rather than a CREATE operation.
513  * 'check_rights': check for CREATE rights in namespace and tablespace. (This
514  * should be true except when ALTER is deleting/recreating an index.)
515  * 'check_not_in_use': check for table not already in use in current session.
516  * This should be true unless caller is holding the table open, in which
517  * case the caller had better have checked it earlier.
518  * 'skip_build': make the catalog entries but don't create the index files
519  * 'quiet': suppress the NOTICE chatter ordinarily provided for constraints.
520  *
521  * Returns the object address of the created index.
522  */
524 DefineIndex(Oid relationId,
525  IndexStmt *stmt,
526  Oid indexRelationId,
527  Oid parentIndexId,
528  Oid parentConstraintId,
529  bool is_alter_table,
530  bool check_rights,
531  bool check_not_in_use,
532  bool skip_build,
533  bool quiet)
534 {
535  bool concurrent;
536  char *indexRelationName;
537  char *accessMethodName;
538  Oid *typeObjectId;
539  Oid *collationObjectId;
540  Oid *classObjectId;
541  Oid accessMethodId;
542  Oid namespaceId;
543  Oid tablespaceId;
544  Oid createdConstraintId = InvalidOid;
545  List *indexColNames;
546  List *allIndexParams;
547  Relation rel;
548  HeapTuple tuple;
549  Form_pg_am accessMethodForm;
550  IndexAmRoutine *amRoutine;
551  bool amcanorder;
552  amoptions_function amoptions;
553  bool partitioned;
554  bool safe_index;
555  Datum reloptions;
556  int16 *coloptions;
557  IndexInfo *indexInfo;
558  bits16 flags;
559  bits16 constr_flags;
560  int numberOfAttributes;
561  int numberOfKeyAttributes;
562  TransactionId limitXmin;
563  ObjectAddress address;
564  LockRelId heaprelid;
565  LOCKTAG heaplocktag;
566  LOCKMODE lockmode;
567  Snapshot snapshot;
568  Oid root_save_userid;
569  int root_save_sec_context;
570  int root_save_nestlevel;
571 
572  root_save_nestlevel = NewGUCNestLevel();
573 
574  /*
575  * Some callers need us to run with an empty default_tablespace; this is a
576  * necessary hack to be able to reproduce catalog state accurately when
577  * recreating indexes after table-rewriting ALTER TABLE.
578  */
579  if (stmt->reset_default_tblspc)
580  (void) set_config_option("default_tablespace", "",
582  GUC_ACTION_SAVE, true, 0, false);
583 
584  /*
585  * Force non-concurrent build on temporary relations, even if CONCURRENTLY
586  * was requested. Other backends can't access a temporary relation, so
587  * there's no harm in grabbing a stronger lock, and a non-concurrent DROP
588  * is more efficient. Do this before any use of the concurrent option is
589  * done.
590  */
591  if (stmt->concurrent && get_rel_persistence(relationId) != RELPERSISTENCE_TEMP)
592  concurrent = true;
593  else
594  concurrent = false;
595 
596  /*
597  * Start progress report. If we're building a partition, this was already
598  * done.
599  */
600  if (!OidIsValid(parentIndexId))
601  {
603  relationId);
605  concurrent ?
608  }
609 
610  /*
611  * No index OID to report yet
612  */
614  InvalidOid);
615 
616  /*
617  * count key attributes in index
618  */
619  numberOfKeyAttributes = list_length(stmt->indexParams);
620 
621  /*
622  * Calculate the new list of index columns including both key columns and
623  * INCLUDE columns. Later we can determine which of these are key
624  * columns, and which are just part of the INCLUDE list by checking the
625  * list position. A list item in a position less than ii_NumIndexKeyAttrs
626  * is part of the key columns, and anything equal to and over is part of
627  * the INCLUDE columns.
628  */
629  allIndexParams = list_concat_copy(stmt->indexParams,
630  stmt->indexIncludingParams);
631  numberOfAttributes = list_length(allIndexParams);
632 
633  if (numberOfKeyAttributes <= 0)
634  ereport(ERROR,
635  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
636  errmsg("must specify at least one column")));
637  if (numberOfAttributes > INDEX_MAX_KEYS)
638  ereport(ERROR,
639  (errcode(ERRCODE_TOO_MANY_COLUMNS),
640  errmsg("cannot use more than %d columns in an index",
641  INDEX_MAX_KEYS)));
642 
643  /*
644  * Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
645  * index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
646  * (but not VACUUM).
647  *
648  * NB: Caller is responsible for making sure that relationId refers to the
649  * relation on which the index should be built; except in bootstrap mode,
650  * this will typically require the caller to have already locked the
651  * relation. To avoid lock upgrade hazards, that lock should be at least
652  * as strong as the one we take here.
653  *
654  * NB: If the lock strength here ever changes, code that is run by
655  * parallel workers under the control of certain particular ambuild
656  * functions will need to be updated, too.
657  */
658  lockmode = concurrent ? ShareUpdateExclusiveLock : ShareLock;
659  rel = table_open(relationId, lockmode);
660 
661  /*
662  * Switch to the table owner's userid, so that any index functions are run
663  * as that user. Also lock down security-restricted operations. We
664  * already arranged to make GUC variable changes local to this command.
665  */
666  GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context);
667  SetUserIdAndSecContext(rel->rd_rel->relowner,
668  root_save_sec_context | SECURITY_RESTRICTED_OPERATION);
669 
670  namespaceId = RelationGetNamespace(rel);
671 
672  /* Ensure that it makes sense to index this kind of relation */
673  switch (rel->rd_rel->relkind)
674  {
675  case RELKIND_RELATION:
676  case RELKIND_MATVIEW:
677  case RELKIND_PARTITIONED_TABLE:
678  /* OK */
679  break;
680  default:
681  ereport(ERROR,
682  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
683  errmsg("cannot create index on relation \"%s\"",
685  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
686  break;
687  }
688 
689  /*
690  * Establish behavior for partitioned tables, and verify sanity of
691  * parameters.
692  *
693  * We do not build an actual index in this case; we only create a few
694  * catalog entries. The actual indexes are built by recursing for each
695  * partition.
696  */
697  partitioned = rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
698  if (partitioned)
699  {
700  /*
701  * Note: we check 'stmt->concurrent' rather than 'concurrent', so that
702  * the error is thrown also for temporary tables. Seems better to be
703  * consistent, even though we could do it on temporary table because
704  * we're not actually doing it concurrently.
705  */
706  if (stmt->concurrent)
707  ereport(ERROR,
708  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
709  errmsg("cannot create index on partitioned table \"%s\" concurrently",
710  RelationGetRelationName(rel))));
711  if (stmt->excludeOpNames)
712  ereport(ERROR,
713  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
714  errmsg("cannot create exclusion constraints on partitioned table \"%s\"",
715  RelationGetRelationName(rel))));
716  }
717 
718  /*
719  * Don't try to CREATE INDEX on temp tables of other backends.
720  */
721  if (RELATION_IS_OTHER_TEMP(rel))
722  ereport(ERROR,
723  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
724  errmsg("cannot create indexes on temporary tables of other sessions")));
725 
726  /*
727  * Unless our caller vouches for having checked this already, insist that
728  * the table not be in use by our own session, either. Otherwise we might
729  * fail to make entries in the new index (for instance, if an INSERT or
730  * UPDATE is in progress and has already made its list of target indexes).
731  */
732  if (check_not_in_use)
733  CheckTableNotInUse(rel, "CREATE INDEX");
734 
735  /*
736  * Verify we (still) have CREATE rights in the rel's namespace.
737  * (Presumably we did when the rel was created, but maybe not anymore.)
738  * Skip check if caller doesn't want it. Also skip check if
739  * bootstrapping, since permissions machinery may not be working yet.
740  */
741  if (check_rights && !IsBootstrapProcessingMode())
742  {
743  AclResult aclresult;
744 
745  aclresult = object_aclcheck(NamespaceRelationId, namespaceId, root_save_userid,
746  ACL_CREATE);
747  if (aclresult != ACLCHECK_OK)
748  aclcheck_error(aclresult, OBJECT_SCHEMA,
749  get_namespace_name(namespaceId));
750  }
751 
752  /*
753  * Select tablespace to use. If not specified, use default tablespace
754  * (which may in turn default to database's default).
755  */
756  if (stmt->tableSpace)
757  {
758  tablespaceId = get_tablespace_oid(stmt->tableSpace, false);
759  if (partitioned && tablespaceId == MyDatabaseTableSpace)
760  ereport(ERROR,
761  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
762  errmsg("cannot specify default tablespace for partitioned relations")));
763  }
764  else
765  {
766  tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence,
767  partitioned);
768  /* note InvalidOid is OK in this case */
769  }
770 
771  /* Check tablespace permissions */
772  if (check_rights &&
773  OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
774  {
775  AclResult aclresult;
776 
777  aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, root_save_userid,
778  ACL_CREATE);
779  if (aclresult != ACLCHECK_OK)
781  get_tablespace_name(tablespaceId));
782  }
783 
784  /*
785  * Force shared indexes into the pg_global tablespace. This is a bit of a
786  * hack but seems simpler than marking them in the BKI commands. On the
787  * other hand, if it's not shared, don't allow it to be placed there.
788  */
789  if (rel->rd_rel->relisshared)
790  tablespaceId = GLOBALTABLESPACE_OID;
791  else if (tablespaceId == GLOBALTABLESPACE_OID)
792  ereport(ERROR,
793  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
794  errmsg("only shared relations can be placed in pg_global tablespace")));
795 
796  /*
797  * Choose the index column names.
798  */
799  indexColNames = ChooseIndexColumnNames(allIndexParams);
800 
801  /*
802  * Select name for index if caller didn't specify
803  */
804  indexRelationName = stmt->idxname;
805  if (indexRelationName == NULL)
806  indexRelationName = ChooseIndexName(RelationGetRelationName(rel),
807  namespaceId,
808  indexColNames,
809  stmt->excludeOpNames,
810  stmt->primary,
811  stmt->isconstraint);
812 
813  /*
814  * look up the access method, verify it can handle the requested features
815  */
816  accessMethodName = stmt->accessMethod;
817  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
818  if (!HeapTupleIsValid(tuple))
819  {
820  /*
821  * Hack to provide more-or-less-transparent updating of old RTREE
822  * indexes to GiST: if RTREE is requested and not found, use GIST.
823  */
824  if (strcmp(accessMethodName, "rtree") == 0)
825  {
826  ereport(NOTICE,
827  (errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
828  accessMethodName = "gist";
829  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
830  }
831 
832  if (!HeapTupleIsValid(tuple))
833  ereport(ERROR,
834  (errcode(ERRCODE_UNDEFINED_OBJECT),
835  errmsg("access method \"%s\" does not exist",
836  accessMethodName)));
837  }
838  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
839  accessMethodId = accessMethodForm->oid;
840  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
841 
843  accessMethodId);
844 
845  if (stmt->unique && !amRoutine->amcanunique)
846  ereport(ERROR,
847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
848  errmsg("access method \"%s\" does not support unique indexes",
849  accessMethodName)));
850  if (stmt->indexIncludingParams != NIL && !amRoutine->amcaninclude)
851  ereport(ERROR,
852  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
853  errmsg("access method \"%s\" does not support included columns",
854  accessMethodName)));
855  if (numberOfKeyAttributes > 1 && !amRoutine->amcanmulticol)
856  ereport(ERROR,
857  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
858  errmsg("access method \"%s\" does not support multicolumn indexes",
859  accessMethodName)));
860  if (stmt->excludeOpNames && amRoutine->amgettuple == NULL)
861  ereport(ERROR,
862  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
863  errmsg("access method \"%s\" does not support exclusion constraints",
864  accessMethodName)));
865 
866  amcanorder = amRoutine->amcanorder;
867  amoptions = amRoutine->amoptions;
868 
869  pfree(amRoutine);
870  ReleaseSysCache(tuple);
871 
872  /*
873  * Validate predicate, if given
874  */
875  if (stmt->whereClause)
876  CheckPredicate((Expr *) stmt->whereClause);
877 
878  /*
879  * Parse AM-specific options, convert to text array form, validate.
880  */
881  reloptions = transformRelOptions((Datum) 0, stmt->options,
882  NULL, NULL, false, false);
883 
884  (void) index_reloptions(amoptions, reloptions, true);
885 
886  /*
887  * Prepare arguments for index_create, primarily an IndexInfo structure.
888  * Note that predicates must be in implicit-AND format. In a concurrent
889  * build, mark it not-ready-for-inserts.
890  */
891  indexInfo = makeIndexInfo(numberOfAttributes,
892  numberOfKeyAttributes,
893  accessMethodId,
894  NIL, /* expressions, NIL for now */
896  stmt->unique,
897  stmt->nulls_not_distinct,
898  !concurrent,
899  concurrent);
900 
901  typeObjectId = palloc_array(Oid, numberOfAttributes);
902  collationObjectId = palloc_array(Oid, numberOfAttributes);
903  classObjectId = palloc_array(Oid, numberOfAttributes);
904  coloptions = palloc_array(int16, numberOfAttributes);
905  ComputeIndexAttrs(indexInfo,
906  typeObjectId, collationObjectId, classObjectId,
907  coloptions, allIndexParams,
908  stmt->excludeOpNames, relationId,
909  accessMethodName, accessMethodId,
910  amcanorder, stmt->isconstraint, root_save_userid,
911  root_save_sec_context, &root_save_nestlevel);
912 
913  /*
914  * Extra checks when creating a PRIMARY KEY index.
915  */
916  if (stmt->primary)
917  index_check_primary_key(rel, indexInfo, is_alter_table, stmt);
918 
919  /*
920  * If this table is partitioned and we're creating a unique index or a
921  * primary key, make sure that the partition key is a subset of the
922  * index's columns. Otherwise it would be possible to violate uniqueness
923  * by putting values that ought to be unique in different partitions.
924  *
925  * We could lift this limitation if we had global indexes, but those have
926  * their own problems, so this is a useful feature combination.
927  */
928  if (partitioned && (stmt->unique || stmt->primary))
929  {
931  const char *constraint_type;
932  int i;
933 
934  if (stmt->primary)
935  constraint_type = "PRIMARY KEY";
936  else if (stmt->unique)
937  constraint_type = "UNIQUE";
938  else if (stmt->excludeOpNames != NIL)
939  constraint_type = "EXCLUDE";
940  else
941  {
942  elog(ERROR, "unknown constraint type");
943  constraint_type = NULL; /* keep compiler quiet */
944  }
945 
946  /*
947  * Verify that all the columns in the partition key appear in the
948  * unique key definition, with the same notion of equality.
949  */
950  for (i = 0; i < key->partnatts; i++)
951  {
952  bool found = false;
953  int eq_strategy;
954  Oid ptkey_eqop;
955  int j;
956 
957  /*
958  * Identify the equality operator associated with this partkey
959  * column. For list and range partitioning, partkeys use btree
960  * operator classes; hash partitioning uses hash operator classes.
961  * (Keep this in sync with ComputePartitionAttrs!)
962  */
963  if (key->strategy == PARTITION_STRATEGY_HASH)
964  eq_strategy = HTEqualStrategyNumber;
965  else
966  eq_strategy = BTEqualStrategyNumber;
967 
968  ptkey_eqop = get_opfamily_member(key->partopfamily[i],
969  key->partopcintype[i],
970  key->partopcintype[i],
971  eq_strategy);
972  if (!OidIsValid(ptkey_eqop))
973  elog(ERROR, "missing operator %d(%u,%u) in partition opfamily %u",
974  eq_strategy, key->partopcintype[i], key->partopcintype[i],
975  key->partopfamily[i]);
976 
977  /*
978  * We'll need to be able to identify the equality operators
979  * associated with index columns, too. We know what to do with
980  * btree opclasses; if there are ever any other index types that
981  * support unique indexes, this logic will need extension.
982  */
983  if (accessMethodId == BTREE_AM_OID)
984  eq_strategy = BTEqualStrategyNumber;
985  else
986  ereport(ERROR,
987  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
988  errmsg("cannot match partition key to an index using access method \"%s\"",
989  accessMethodName)));
990 
991  /*
992  * It may be possible to support UNIQUE constraints when partition
993  * keys are expressions, but is it worth it? Give up for now.
994  */
995  if (key->partattrs[i] == 0)
996  ereport(ERROR,
997  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
998  errmsg("unsupported %s constraint with partition key definition",
999  constraint_type),
1000  errdetail("%s constraints cannot be used when partition keys include expressions.",
1001  constraint_type)));
1002 
1003  /* Search the index column(s) for a match */
1004  for (j = 0; j < indexInfo->ii_NumIndexKeyAttrs; j++)
1005  {
1006  if (key->partattrs[i] == indexInfo->ii_IndexAttrNumbers[j])
1007  {
1008  /* Matched the column, now what about the equality op? */
1009  Oid idx_opfamily;
1010  Oid idx_opcintype;
1011 
1012  if (get_opclass_opfamily_and_input_type(classObjectId[j],
1013  &idx_opfamily,
1014  &idx_opcintype))
1015  {
1016  Oid idx_eqop;
1017 
1018  idx_eqop = get_opfamily_member(idx_opfamily,
1019  idx_opcintype,
1020  idx_opcintype,
1021  eq_strategy);
1022  if (ptkey_eqop == idx_eqop)
1023  {
1024  found = true;
1025  break;
1026  }
1027  }
1028  }
1029  }
1030 
1031  if (!found)
1032  {
1033  Form_pg_attribute att;
1034 
1035  att = TupleDescAttr(RelationGetDescr(rel),
1036  key->partattrs[i] - 1);
1037  ereport(ERROR,
1038  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1039  errmsg("unique constraint on partitioned table must include all partitioning columns"),
1040  errdetail("%s constraint on table \"%s\" lacks column \"%s\" which is part of the partition key.",
1041  constraint_type, RelationGetRelationName(rel),
1042  NameStr(att->attname))));
1043  }
1044  }
1045  }
1046 
1047 
1048  /*
1049  * We disallow indexes on system columns. They would not necessarily get
1050  * updated correctly, and they don't seem useful anyway.
1051  */
1052  for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1053  {
1054  AttrNumber attno = indexInfo->ii_IndexAttrNumbers[i];
1055 
1056  if (attno < 0)
1057  ereport(ERROR,
1058  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1059  errmsg("index creation on system columns is not supported")));
1060  }
1061 
1062  /*
1063  * Also check for system columns used in expressions or predicates.
1064  */
1065  if (indexInfo->ii_Expressions || indexInfo->ii_Predicate)
1066  {
1067  Bitmapset *indexattrs = NULL;
1068 
1069  pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs);
1070  pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs);
1071 
1072  for (int i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
1073  {
1075  indexattrs))
1076  ereport(ERROR,
1077  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1078  errmsg("index creation on system columns is not supported")));
1079  }
1080  }
1081 
1082  /* Is index safe for others to ignore? See set_indexsafe_procflags() */
1083  safe_index = indexInfo->ii_Expressions == NIL &&
1084  indexInfo->ii_Predicate == NIL;
1085 
1086  /*
1087  * Report index creation if appropriate (delay this till after most of the
1088  * error checks)
1089  */
1090  if (stmt->isconstraint && !quiet)
1091  {
1092  const char *constraint_type;
1093 
1094  if (stmt->primary)
1095  constraint_type = "PRIMARY KEY";
1096  else if (stmt->unique)
1097  constraint_type = "UNIQUE";
1098  else if (stmt->excludeOpNames != NIL)
1099  constraint_type = "EXCLUDE";
1100  else
1101  {
1102  elog(ERROR, "unknown constraint type");
1103  constraint_type = NULL; /* keep compiler quiet */
1104  }
1105 
1106  ereport(DEBUG1,
1107  (errmsg_internal("%s %s will create implicit index \"%s\" for table \"%s\"",
1108  is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
1109  constraint_type,
1110  indexRelationName, RelationGetRelationName(rel))));
1111  }
1112 
1113  /*
1114  * A valid stmt->oldNumber implies that we already have a built form of
1115  * the index. The caller should also decline any index build.
1116  */
1117  Assert(!RelFileNumberIsValid(stmt->oldNumber) || (skip_build && !concurrent));
1118 
1119  /*
1120  * Make the catalog entries for the index, including constraints. This
1121  * step also actually builds the index, except if caller requested not to
1122  * or in concurrent mode, in which case it'll be done later, or doing a
1123  * partitioned index (because those don't have storage).
1124  */
1125  flags = constr_flags = 0;
1126  if (stmt->isconstraint)
1127  flags |= INDEX_CREATE_ADD_CONSTRAINT;
1128  if (skip_build || concurrent || partitioned)
1129  flags |= INDEX_CREATE_SKIP_BUILD;
1130  if (stmt->if_not_exists)
1131  flags |= INDEX_CREATE_IF_NOT_EXISTS;
1132  if (concurrent)
1133  flags |= INDEX_CREATE_CONCURRENT;
1134  if (partitioned)
1135  flags |= INDEX_CREATE_PARTITIONED;
1136  if (stmt->primary)
1137  flags |= INDEX_CREATE_IS_PRIMARY;
1138 
1139  /*
1140  * If the table is partitioned, and recursion was declined but partitions
1141  * exist, mark the index as invalid.
1142  */
1143  if (partitioned && stmt->relation && !stmt->relation->inh)
1144  {
1145  PartitionDesc pd = RelationGetPartitionDesc(rel, true);
1146 
1147  if (pd->nparts != 0)
1148  flags |= INDEX_CREATE_INVALID;
1149  }
1150 
1151  if (stmt->deferrable)
1152  constr_flags |= INDEX_CONSTR_CREATE_DEFERRABLE;
1153  if (stmt->initdeferred)
1154  constr_flags |= INDEX_CONSTR_CREATE_INIT_DEFERRED;
1155 
1156  indexRelationId =
1157  index_create(rel, indexRelationName, indexRelationId, parentIndexId,
1158  parentConstraintId,
1159  stmt->oldNumber, indexInfo, indexColNames,
1160  accessMethodId, tablespaceId,
1161  collationObjectId, classObjectId,
1162  coloptions, reloptions,
1163  flags, constr_flags,
1164  allowSystemTableMods, !check_rights,
1165  &createdConstraintId);
1166 
1167  ObjectAddressSet(address, RelationRelationId, indexRelationId);
1168 
1169  if (!OidIsValid(indexRelationId))
1170  {
1171  /*
1172  * Roll back any GUC changes executed by index functions. Also revert
1173  * to original default_tablespace if we changed it above.
1174  */
1175  AtEOXact_GUC(false, root_save_nestlevel);
1176 
1177  /* Restore userid and security context */
1178  SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
1179 
1180  table_close(rel, NoLock);
1181 
1182  /* If this is the top-level index, we're done */
1183  if (!OidIsValid(parentIndexId))
1185 
1186  return address;
1187  }
1188 
1189  /*
1190  * Roll back any GUC changes executed by index functions, and keep
1191  * subsequent changes local to this command. This is essential if some
1192  * index function changed a behavior-affecting GUC, e.g. search_path.
1193  */
1194  AtEOXact_GUC(false, root_save_nestlevel);
1195  root_save_nestlevel = NewGUCNestLevel();
1196 
1197  /* Add any requested comment */
1198  if (stmt->idxcomment != NULL)
1199  CreateComments(indexRelationId, RelationRelationId, 0,
1200  stmt->idxcomment);
1201 
1202  if (partitioned)
1203  {
1204  PartitionDesc partdesc;
1205 
1206  /*
1207  * Unless caller specified to skip this step (via ONLY), process each
1208  * partition to make sure they all contain a corresponding index.
1209  *
1210  * If we're called internally (no stmt->relation), recurse always.
1211  */
1212  partdesc = RelationGetPartitionDesc(rel, true);
1213  if ((!stmt->relation || stmt->relation->inh) && partdesc->nparts > 0)
1214  {
1215  int nparts = partdesc->nparts;
1216  Oid *part_oids = palloc_array(Oid, nparts);
1217  bool invalidate_parent = false;
1218  Relation parentIndex;
1219  TupleDesc parentDesc;
1220 
1222  nparts);
1223 
1224  /* Make a local copy of partdesc->oids[], just for safety */
1225  memcpy(part_oids, partdesc->oids, sizeof(Oid) * nparts);
1226 
1227  /*
1228  * We'll need an IndexInfo describing the parent index. The one
1229  * built above is almost good enough, but not quite, because (for
1230  * example) its predicate expression if any hasn't been through
1231  * expression preprocessing. The most reliable way to get an
1232  * IndexInfo that will match those for child indexes is to build
1233  * it the same way, using BuildIndexInfo().
1234  */
1235  parentIndex = index_open(indexRelationId, lockmode);
1236  indexInfo = BuildIndexInfo(parentIndex);
1237 
1238  parentDesc = RelationGetDescr(rel);
1239 
1240  /*
1241  * For each partition, scan all existing indexes; if one matches
1242  * our index definition and is not already attached to some other
1243  * parent index, attach it to the one we just created.
1244  *
1245  * If none matches, build a new index by calling ourselves
1246  * recursively with the same options (except for the index name).
1247  */
1248  for (int i = 0; i < nparts; i++)
1249  {
1250  Oid childRelid = part_oids[i];
1251  Relation childrel;
1252  Oid child_save_userid;
1253  int child_save_sec_context;
1254  int child_save_nestlevel;
1255  List *childidxs;
1256  ListCell *cell;
1257  AttrMap *attmap;
1258  bool found = false;
1259 
1260  childrel = table_open(childRelid, lockmode);
1261 
1262  GetUserIdAndSecContext(&child_save_userid,
1263  &child_save_sec_context);
1264  SetUserIdAndSecContext(childrel->rd_rel->relowner,
1265  child_save_sec_context | SECURITY_RESTRICTED_OPERATION);
1266  child_save_nestlevel = NewGUCNestLevel();
1267 
1268  /*
1269  * Don't try to create indexes on foreign tables, though. Skip
1270  * those if a regular index, or fail if trying to create a
1271  * constraint index.
1272  */
1273  if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1274  {
1275  if (stmt->unique || stmt->primary)
1276  ereport(ERROR,
1277  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1278  errmsg("cannot create unique index on partitioned table \"%s\"",
1280  errdetail("Table \"%s\" contains partitions that are foreign tables.",
1281  RelationGetRelationName(rel))));
1282 
1283  AtEOXact_GUC(false, child_save_nestlevel);
1284  SetUserIdAndSecContext(child_save_userid,
1285  child_save_sec_context);
1286  table_close(childrel, lockmode);
1287  continue;
1288  }
1289 
1290  childidxs = RelationGetIndexList(childrel);
1291  attmap =
1293  parentDesc,
1294  false);
1295 
1296  foreach(cell, childidxs)
1297  {
1298  Oid cldidxid = lfirst_oid(cell);
1299  Relation cldidx;
1300  IndexInfo *cldIdxInfo;
1301 
1302  /* this index is already partition of another one */
1303  if (has_superclass(cldidxid))
1304  continue;
1305 
1306  cldidx = index_open(cldidxid, lockmode);
1307  cldIdxInfo = BuildIndexInfo(cldidx);
1308  if (CompareIndexInfo(cldIdxInfo, indexInfo,
1309  cldidx->rd_indcollation,
1310  parentIndex->rd_indcollation,
1311  cldidx->rd_opfamily,
1312  parentIndex->rd_opfamily,
1313  attmap))
1314  {
1315  Oid cldConstrOid = InvalidOid;
1316 
1317  /*
1318  * Found a match.
1319  *
1320  * If this index is being created in the parent
1321  * because of a constraint, then the child needs to
1322  * have a constraint also, so look for one. If there
1323  * is no such constraint, this index is no good, so
1324  * keep looking.
1325  */
1326  if (createdConstraintId != InvalidOid)
1327  {
1328  cldConstrOid =
1330  cldidxid);
1331  if (cldConstrOid == InvalidOid)
1332  {
1333  index_close(cldidx, lockmode);
1334  continue;
1335  }
1336  }
1337 
1338  /* Attach index to parent and we're done. */
1339  IndexSetParentIndex(cldidx, indexRelationId);
1340  if (createdConstraintId != InvalidOid)
1341  ConstraintSetParentConstraint(cldConstrOid,
1342  createdConstraintId,
1343  childRelid);
1344 
1345  if (!cldidx->rd_index->indisvalid)
1346  invalidate_parent = true;
1347 
1348  found = true;
1349  /* keep lock till commit */
1350  index_close(cldidx, NoLock);
1351  break;
1352  }
1353 
1354  index_close(cldidx, lockmode);
1355  }
1356 
1357  list_free(childidxs);
1358  AtEOXact_GUC(false, child_save_nestlevel);
1359  SetUserIdAndSecContext(child_save_userid,
1360  child_save_sec_context);
1361  table_close(childrel, NoLock);
1362 
1363  /*
1364  * If no matching index was found, create our own.
1365  */
1366  if (!found)
1367  {
1368  IndexStmt *childStmt = copyObject(stmt);
1369  bool found_whole_row;
1370  ListCell *lc;
1371 
1372  /*
1373  * We can't use the same index name for the child index,
1374  * so clear idxname to let the recursive invocation choose
1375  * a new name. Likewise, the existing target relation
1376  * field is wrong, and if indexOid or oldNumber are set,
1377  * they mustn't be applied to the child either.
1378  */
1379  childStmt->idxname = NULL;
1380  childStmt->relation = NULL;
1381  childStmt->indexOid = InvalidOid;
1382  childStmt->oldNumber = InvalidRelFileNumber;
1385 
1386  /*
1387  * Adjust any Vars (both in expressions and in the index's
1388  * WHERE clause) to match the partition's column numbering
1389  * in case it's different from the parent's.
1390  */
1391  foreach(lc, childStmt->indexParams)
1392  {
1393  IndexElem *ielem = lfirst(lc);
1394 
1395  /*
1396  * If the index parameter is an expression, we must
1397  * translate it to contain child Vars.
1398  */
1399  if (ielem->expr)
1400  {
1401  ielem->expr =
1402  map_variable_attnos((Node *) ielem->expr,
1403  1, 0, attmap,
1404  InvalidOid,
1405  &found_whole_row);
1406  if (found_whole_row)
1407  elog(ERROR, "cannot convert whole-row table reference");
1408  }
1409  }
1410  childStmt->whereClause =
1411  map_variable_attnos(stmt->whereClause, 1, 0,
1412  attmap,
1413  InvalidOid, &found_whole_row);
1414  if (found_whole_row)
1415  elog(ERROR, "cannot convert whole-row table reference");
1416 
1417  /*
1418  * Recurse as the starting user ID. Callee will use that
1419  * for permission checks, then switch again.
1420  */
1421  Assert(GetUserId() == child_save_userid);
1422  SetUserIdAndSecContext(root_save_userid,
1423  root_save_sec_context);
1424  DefineIndex(childRelid, childStmt,
1425  InvalidOid, /* no predefined OID */
1426  indexRelationId, /* this is our child */
1427  createdConstraintId,
1428  is_alter_table, check_rights, check_not_in_use,
1429  skip_build, quiet);
1430  SetUserIdAndSecContext(child_save_userid,
1431  child_save_sec_context);
1432  }
1433 
1435  i + 1);
1436  free_attrmap(attmap);
1437  }
1438 
1439  index_close(parentIndex, lockmode);
1440 
1441  /*
1442  * The pg_index row we inserted for this index was marked
1443  * indisvalid=true. But if we attached an existing index that is
1444  * invalid, this is incorrect, so update our row to invalid too.
1445  */
1446  if (invalidate_parent)
1447  {
1448  Relation pg_index = table_open(IndexRelationId, RowExclusiveLock);
1449  HeapTuple tup,
1450  newtup;
1451 
1453  ObjectIdGetDatum(indexRelationId));
1454  if (!HeapTupleIsValid(tup))
1455  elog(ERROR, "cache lookup failed for index %u",
1456  indexRelationId);
1457  newtup = heap_copytuple(tup);
1458  ((Form_pg_index) GETSTRUCT(newtup))->indisvalid = false;
1459  CatalogTupleUpdate(pg_index, &tup->t_self, newtup);
1460  ReleaseSysCache(tup);
1461  table_close(pg_index, RowExclusiveLock);
1462  heap_freetuple(newtup);
1463  }
1464  }
1465 
1466  /*
1467  * Indexes on partitioned tables are not themselves built, so we're
1468  * done here.
1469  */
1470  AtEOXact_GUC(false, root_save_nestlevel);
1471  SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
1472  table_close(rel, NoLock);
1473  if (!OidIsValid(parentIndexId))
1475  return address;
1476  }
1477 
1478  AtEOXact_GUC(false, root_save_nestlevel);
1479  SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
1480 
1481  if (!concurrent)
1482  {
1483  /* Close the heap and we're done, in the non-concurrent case */
1484  table_close(rel, NoLock);
1485 
1486  /* If this is the top-level index, we're done. */
1487  if (!OidIsValid(parentIndexId))
1489 
1490  return address;
1491  }
1492 
1493  /* save lockrelid and locktag for below, then close rel */
1494  heaprelid = rel->rd_lockInfo.lockRelId;
1495  SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
1496  table_close(rel, NoLock);
1497 
1498  /*
1499  * For a concurrent build, it's important to make the catalog entries
1500  * visible to other transactions before we start to build the index. That
1501  * will prevent them from making incompatible HOT updates. The new index
1502  * will be marked not indisready and not indisvalid, so that no one else
1503  * tries to either insert into it or use it for queries.
1504  *
1505  * We must commit our current transaction so that the index becomes
1506  * visible; then start another. Note that all the data structures we just
1507  * built are lost in the commit. The only data we keep past here are the
1508  * relation IDs.
1509  *
1510  * Before committing, get a session-level lock on the table, to ensure
1511  * that neither it nor the index can be dropped before we finish. This
1512  * cannot block, even if someone else is waiting for access, because we
1513  * already have the same lock within our transaction.
1514  *
1515  * Note: we don't currently bother with a session lock on the index,
1516  * because there are no operations that could change its state while we
1517  * hold lock on the parent table. This might need to change later.
1518  */
1520 
1524 
1525  /* Tell concurrent index builds to ignore us, if index qualifies */
1526  if (safe_index)
1528 
1529  /*
1530  * The index is now visible, so we can report the OID. While on it,
1531  * include the report for the beginning of phase 2.
1532  */
1533  {
1534  const int progress_cols[] = {
1537  };
1538  const int64 progress_vals[] = {
1539  indexRelationId,
1541  };
1542 
1543  pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
1544  }
1545 
1546  /*
1547  * Phase 2 of concurrent index build (see comments for validate_index()
1548  * for an overview of how this works)
1549  *
1550  * Now we must wait until no running transaction could have the table open
1551  * with the old list of indexes. Use ShareLock to consider running
1552  * transactions that hold locks that permit writing to the table. Note we
1553  * do not need to worry about xacts that open the table for writing after
1554  * this point; they will see the new index when they open it.
1555  *
1556  * Note: the reason we use actual lock acquisition here, rather than just
1557  * checking the ProcArray and sleeping, is that deadlock is possible if
1558  * one of the transactions in question is blocked trying to acquire an
1559  * exclusive lock on our table. The lock code will detect deadlock and
1560  * error out properly.
1561  */
1562  WaitForLockers(heaplocktag, ShareLock, true);
1563 
1564  /*
1565  * At this moment we are sure that there are no transactions with the
1566  * table open for write that don't have this new index in their list of
1567  * indexes. We have waited out all the existing transactions and any new
1568  * transaction will have the new index in its list, but the index is still
1569  * marked as "not-ready-for-inserts". The index is consulted while
1570  * deciding HOT-safety though. This arrangement ensures that no new HOT
1571  * chains can be created where the new tuple and the old tuple in the
1572  * chain have different index keys.
1573  *
1574  * We now take a new snapshot, and build the index using all tuples that
1575  * are visible in this snapshot. We can be sure that any HOT updates to
1576  * these tuples will be compatible with the index, since any updates made
1577  * by transactions that didn't know about the index are now committed or
1578  * rolled back. Thus, each visible tuple is either the end of its
1579  * HOT-chain or the extension of the chain is HOT-safe for this index.
1580  */
1581 
1582  /* Set ActiveSnapshot since functions in the indexes may need it */
1584 
1585  /* Perform concurrent build of index */
1586  index_concurrently_build(relationId, indexRelationId);
1587 
1588  /* we can do away with our snapshot */
1590 
1591  /*
1592  * Commit this transaction to make the indisready update visible.
1593  */
1596 
1597  /* Tell concurrent index builds to ignore us, if index qualifies */
1598  if (safe_index)
1600 
1601  /*
1602  * Phase 3 of concurrent index build
1603  *
1604  * We once again wait until no transaction can have the table open with
1605  * the index marked as read-only for updates.
1606  */
1609  WaitForLockers(heaplocktag, ShareLock, true);
1610 
1611  /*
1612  * Now take the "reference snapshot" that will be used by validate_index()
1613  * to filter candidate tuples. Beware! There might still be snapshots in
1614  * use that treat some transaction as in-progress that our reference
1615  * snapshot treats as committed. If such a recently-committed transaction
1616  * deleted tuples in the table, we will not include them in the index; yet
1617  * those transactions which see the deleting one as still-in-progress will
1618  * expect such tuples to be there once we mark the index as valid.
1619  *
1620  * We solve this by waiting for all endangered transactions to exit before
1621  * we mark the index as valid.
1622  *
1623  * We also set ActiveSnapshot to this snap, since functions in indexes may
1624  * need a snapshot.
1625  */
1627  PushActiveSnapshot(snapshot);
1628 
1629  /*
1630  * Scan the index and the heap, insert any missing index entries.
1631  */
1632  validate_index(relationId, indexRelationId, snapshot);
1633 
1634  /*
1635  * Drop the reference snapshot. We must do this before waiting out other
1636  * snapshot holders, else we will deadlock against other processes also
1637  * doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one
1638  * they must wait for. But first, save the snapshot's xmin to use as
1639  * limitXmin for GetCurrentVirtualXIDs().
1640  */
1641  limitXmin = snapshot->xmin;
1642 
1644  UnregisterSnapshot(snapshot);
1645 
1646  /*
1647  * The snapshot subsystem could still contain registered snapshots that
1648  * are holding back our process's advertised xmin; in particular, if
1649  * default_transaction_isolation = serializable, there is a transaction
1650  * snapshot that is still active. The CatalogSnapshot is likewise a
1651  * hazard. To ensure no deadlocks, we must commit and start yet another
1652  * transaction, and do our wait before any snapshot has been taken in it.
1653  */
1656 
1657  /* Tell concurrent index builds to ignore us, if index qualifies */
1658  if (safe_index)
1660 
1661  /* We should now definitely not be advertising any xmin. */
1663 
1664  /*
1665  * The index is now valid in the sense that it contains all currently
1666  * interesting tuples. But since it might not contain tuples deleted just
1667  * before the reference snap was taken, we have to wait out any
1668  * transactions that might have older snapshots.
1669  */
1672  WaitForOlderSnapshots(limitXmin, true);
1673 
1674  /*
1675  * Index can now be marked valid -- update its pg_index entry
1676  */
1678 
1679  /*
1680  * The pg_index update will cause backends (including this one) to update
1681  * relcache entries for the index itself, but we should also send a
1682  * relcache inval on the parent table to force replanning of cached plans.
1683  * Otherwise existing sessions might fail to use the new index where it
1684  * would be useful. (Note that our earlier commits did not create reasons
1685  * to replan; so relcache flush on the index itself was sufficient.)
1686  */
1688 
1689  /*
1690  * Last thing to do is release the session-level lock on the parent table.
1691  */
1693 
1695 
1696  return address;
1697 }
1698 
1699 
1700 /*
1701  * CheckMutability
1702  * Test whether given expression is mutable
1703  */
1704 static bool
1706 {
1707  /*
1708  * First run the expression through the planner. This has a couple of
1709  * important consequences. First, function default arguments will get
1710  * inserted, which may affect volatility (consider "default now()").
1711  * Second, inline-able functions will get inlined, which may allow us to
1712  * conclude that the function is really less volatile than it's marked. As
1713  * an example, polymorphic functions must be marked with the most volatile
1714  * behavior that they have for any input type, but once we inline the
1715  * function we may be able to conclude that it's not so volatile for the
1716  * particular input type we're dealing with.
1717  *
1718  * We assume here that expression_planner() won't scribble on its input.
1719  */
1720  expr = expression_planner(expr);
1721 
1722  /* Now we can search for non-immutable functions */
1723  return contain_mutable_functions((Node *) expr);
1724 }
1725 
1726 
1727 /*
1728  * CheckPredicate
1729  * Checks that the given partial-index predicate is valid.
1730  *
1731  * This used to also constrain the form of the predicate to forms that
1732  * indxpath.c could do something with. However, that seems overly
1733  * restrictive. One useful application of partial indexes is to apply
1734  * a UNIQUE constraint across a subset of a table, and in that scenario
1735  * any evaluable predicate will work. So accept any predicate here
1736  * (except ones requiring a plan), and let indxpath.c fend for itself.
1737  */
1738 static void
1740 {
1741  /*
1742  * transformExpr() should have already rejected subqueries, aggregates,
1743  * and window functions, based on the EXPR_KIND_ for a predicate.
1744  */
1745 
1746  /*
1747  * A predicate using mutable functions is probably wrong, for the same
1748  * reasons that we don't allow an index expression to use one.
1749  */
1750  if (CheckMutability(predicate))
1751  ereport(ERROR,
1752  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1753  errmsg("functions in index predicate must be marked IMMUTABLE")));
1754 }
1755 
1756 /*
1757  * Compute per-index-column information, including indexed column numbers
1758  * or index expressions, opclasses and their options. Note, all output vectors
1759  * should be allocated for all columns, including "including" ones.
1760  *
1761  * If the caller switched to the table owner, ddl_userid is the role for ACL
1762  * checks reached without traversing opaque expressions. Otherwise, it's
1763  * InvalidOid, and other ddl_* arguments are undefined.
1764  */
1765 static void
1767  Oid *typeOidP,
1768  Oid *collationOidP,
1769  Oid *classOidP,
1770  int16 *colOptionP,
1771  List *attList, /* list of IndexElem's */
1772  List *exclusionOpNames,
1773  Oid relId,
1774  const char *accessMethodName,
1775  Oid accessMethodId,
1776  bool amcanorder,
1777  bool isconstraint,
1778  Oid ddl_userid,
1779  int ddl_sec_context,
1780  int *ddl_save_nestlevel)
1781 {
1782  ListCell *nextExclOp;
1783  ListCell *lc;
1784  int attn;
1785  int nkeycols = indexInfo->ii_NumIndexKeyAttrs;
1786  Oid save_userid;
1787  int save_sec_context;
1788 
1789  /* Allocate space for exclusion operator info, if needed */
1790  if (exclusionOpNames)
1791  {
1792  Assert(list_length(exclusionOpNames) == nkeycols);
1793  indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols);
1794  indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols);
1795  indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols);
1796  nextExclOp = list_head(exclusionOpNames);
1797  }
1798  else
1799  nextExclOp = NULL;
1800 
1801  if (OidIsValid(ddl_userid))
1802  GetUserIdAndSecContext(&save_userid, &save_sec_context);
1803 
1804  /*
1805  * process attributeList
1806  */
1807  attn = 0;
1808  foreach(lc, attList)
1809  {
1810  IndexElem *attribute = (IndexElem *) lfirst(lc);
1811  Oid atttype;
1812  Oid attcollation;
1813 
1814  /*
1815  * Process the column-or-expression to be indexed.
1816  */
1817  if (attribute->name != NULL)
1818  {
1819  /* Simple index attribute */
1820  HeapTuple atttuple;
1821  Form_pg_attribute attform;
1822 
1823  Assert(attribute->expr == NULL);
1824  atttuple = SearchSysCacheAttName(relId, attribute->name);
1825  if (!HeapTupleIsValid(atttuple))
1826  {
1827  /* difference in error message spellings is historical */
1828  if (isconstraint)
1829  ereport(ERROR,
1830  (errcode(ERRCODE_UNDEFINED_COLUMN),
1831  errmsg("column \"%s\" named in key does not exist",
1832  attribute->name)));
1833  else
1834  ereport(ERROR,
1835  (errcode(ERRCODE_UNDEFINED_COLUMN),
1836  errmsg("column \"%s\" does not exist",
1837  attribute->name)));
1838  }
1839  attform = (Form_pg_attribute) GETSTRUCT(atttuple);
1840  indexInfo->ii_IndexAttrNumbers[attn] = attform->attnum;
1841  atttype = attform->atttypid;
1842  attcollation = attform->attcollation;
1843  ReleaseSysCache(atttuple);
1844  }
1845  else
1846  {
1847  /* Index expression */
1848  Node *expr = attribute->expr;
1849 
1850  Assert(expr != NULL);
1851 
1852  if (attn >= nkeycols)
1853  ereport(ERROR,
1854  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1855  errmsg("expressions are not supported in included columns")));
1856  atttype = exprType(expr);
1857  attcollation = exprCollation(expr);
1858 
1859  /*
1860  * Strip any top-level COLLATE clause. This ensures that we treat
1861  * "x COLLATE y" and "(x COLLATE y)" alike.
1862  */
1863  while (IsA(expr, CollateExpr))
1864  expr = (Node *) ((CollateExpr *) expr)->arg;
1865 
1866  if (IsA(expr, Var) &&
1867  ((Var *) expr)->varattno != InvalidAttrNumber)
1868  {
1869  /*
1870  * User wrote "(column)" or "(column COLLATE something)".
1871  * Treat it like simple attribute anyway.
1872  */
1873  indexInfo->ii_IndexAttrNumbers[attn] = ((Var *) expr)->varattno;
1874  }
1875  else
1876  {
1877  indexInfo->ii_IndexAttrNumbers[attn] = 0; /* marks expression */
1878  indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions,
1879  expr);
1880 
1881  /*
1882  * transformExpr() should have already rejected subqueries,
1883  * aggregates, and window functions, based on the EXPR_KIND_
1884  * for an index expression.
1885  */
1886 
1887  /*
1888  * An expression using mutable functions is probably wrong,
1889  * since if you aren't going to get the same result for the
1890  * same data every time, it's not clear what the index entries
1891  * mean at all.
1892  */
1893  if (CheckMutability((Expr *) expr))
1894  ereport(ERROR,
1895  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1896  errmsg("functions in index expression must be marked IMMUTABLE")));
1897  }
1898  }
1899 
1900  typeOidP[attn] = atttype;
1901 
1902  /*
1903  * Included columns have no collation, no opclass and no ordering
1904  * options.
1905  */
1906  if (attn >= nkeycols)
1907  {
1908  if (attribute->collation)
1909  ereport(ERROR,
1910  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1911  errmsg("including column does not support a collation")));
1912  if (attribute->opclass)
1913  ereport(ERROR,
1914  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1915  errmsg("including column does not support an operator class")));
1916  if (attribute->ordering != SORTBY_DEFAULT)
1917  ereport(ERROR,
1918  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1919  errmsg("including column does not support ASC/DESC options")));
1920  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
1921  ereport(ERROR,
1922  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1923  errmsg("including column does not support NULLS FIRST/LAST options")));
1924 
1925  classOidP[attn] = InvalidOid;
1926  colOptionP[attn] = 0;
1927  collationOidP[attn] = InvalidOid;
1928  attn++;
1929 
1930  continue;
1931  }
1932 
1933  /*
1934  * Apply collation override if any. Use of ddl_userid is necessary
1935  * due to ACL checks therein, and it's safe because collations don't
1936  * contain opaque expressions (or non-opaque expressions).
1937  */
1938  if (attribute->collation)
1939  {
1940  if (OidIsValid(ddl_userid))
1941  {
1942  AtEOXact_GUC(false, *ddl_save_nestlevel);
1943  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
1944  }
1945  attcollation = get_collation_oid(attribute->collation, false);
1946  if (OidIsValid(ddl_userid))
1947  {
1948  SetUserIdAndSecContext(save_userid, save_sec_context);
1949  *ddl_save_nestlevel = NewGUCNestLevel();
1950  }
1951  }
1952 
1953  /*
1954  * Check we have a collation iff it's a collatable type. The only
1955  * expected failures here are (1) COLLATE applied to a noncollatable
1956  * type, or (2) index expression had an unresolved collation. But we
1957  * might as well code this to be a complete consistency check.
1958  */
1959  if (type_is_collatable(atttype))
1960  {
1961  if (!OidIsValid(attcollation))
1962  ereport(ERROR,
1963  (errcode(ERRCODE_INDETERMINATE_COLLATION),
1964  errmsg("could not determine which collation to use for index expression"),
1965  errhint("Use the COLLATE clause to set the collation explicitly.")));
1966  }
1967  else
1968  {
1969  if (OidIsValid(attcollation))
1970  ereport(ERROR,
1971  (errcode(ERRCODE_DATATYPE_MISMATCH),
1972  errmsg("collations are not supported by type %s",
1973  format_type_be(atttype))));
1974  }
1975 
1976  collationOidP[attn] = attcollation;
1977 
1978  /*
1979  * Identify the opclass to use. Use of ddl_userid is necessary due to
1980  * ACL checks therein. This is safe despite opclasses containing
1981  * opaque expressions (specifically, functions), because only
1982  * superusers can define opclasses.
1983  */
1984  if (OidIsValid(ddl_userid))
1985  {
1986  AtEOXact_GUC(false, *ddl_save_nestlevel);
1987  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
1988  }
1989  classOidP[attn] = ResolveOpClass(attribute->opclass,
1990  atttype,
1991  accessMethodName,
1992  accessMethodId);
1993  if (OidIsValid(ddl_userid))
1994  {
1995  SetUserIdAndSecContext(save_userid, save_sec_context);
1996  *ddl_save_nestlevel = NewGUCNestLevel();
1997  }
1998 
1999  /*
2000  * Identify the exclusion operator, if any.
2001  */
2002  if (nextExclOp)
2003  {
2004  List *opname = (List *) lfirst(nextExclOp);
2005  Oid opid;
2006  Oid opfamily;
2007  int strat;
2008 
2009  /*
2010  * Find the operator --- it must accept the column datatype
2011  * without runtime coercion (but binary compatibility is OK).
2012  * Operators contain opaque expressions (specifically, functions).
2013  * compatible_oper_opid() boils down to oper() and
2014  * IsBinaryCoercible(). PostgreSQL would have security problems
2015  * elsewhere if oper() started calling opaque expressions.
2016  */
2017  if (OidIsValid(ddl_userid))
2018  {
2019  AtEOXact_GUC(false, *ddl_save_nestlevel);
2020  SetUserIdAndSecContext(ddl_userid, ddl_sec_context);
2021  }
2022  opid = compatible_oper_opid(opname, atttype, atttype, false);
2023  if (OidIsValid(ddl_userid))
2024  {
2025  SetUserIdAndSecContext(save_userid, save_sec_context);
2026  *ddl_save_nestlevel = NewGUCNestLevel();
2027  }
2028 
2029  /*
2030  * Only allow commutative operators to be used in exclusion
2031  * constraints. If X conflicts with Y, but Y does not conflict
2032  * with X, bad things will happen.
2033  */
2034  if (get_commutator(opid) != opid)
2035  ereport(ERROR,
2036  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2037  errmsg("operator %s is not commutative",
2038  format_operator(opid)),
2039  errdetail("Only commutative operators can be used in exclusion constraints.")));
2040 
2041  /*
2042  * Operator must be a member of the right opfamily, too
2043  */
2044  opfamily = get_opclass_family(classOidP[attn]);
2045  strat = get_op_opfamily_strategy(opid, opfamily);
2046  if (strat == 0)
2047  {
2048  HeapTuple opftuple;
2049  Form_pg_opfamily opfform;
2050 
2051  /*
2052  * attribute->opclass might not explicitly name the opfamily,
2053  * so fetch the name of the selected opfamily for use in the
2054  * error message.
2055  */
2056  opftuple = SearchSysCache1(OPFAMILYOID,
2057  ObjectIdGetDatum(opfamily));
2058  if (!HeapTupleIsValid(opftuple))
2059  elog(ERROR, "cache lookup failed for opfamily %u",
2060  opfamily);
2061  opfform = (Form_pg_opfamily) GETSTRUCT(opftuple);
2062 
2063  ereport(ERROR,
2064  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2065  errmsg("operator %s is not a member of operator family \"%s\"",
2066  format_operator(opid),
2067  NameStr(opfform->opfname)),
2068  errdetail("The exclusion operator must be related to the index operator class for the constraint.")));
2069  }
2070 
2071  indexInfo->ii_ExclusionOps[attn] = opid;
2072  indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid);
2073  indexInfo->ii_ExclusionStrats[attn] = strat;
2074  nextExclOp = lnext(exclusionOpNames, nextExclOp);
2075  }
2076 
2077  /*
2078  * Set up the per-column options (indoption field). For now, this is
2079  * zero for any un-ordered index, while ordered indexes have DESC and
2080  * NULLS FIRST/LAST options.
2081  */
2082  colOptionP[attn] = 0;
2083  if (amcanorder)
2084  {
2085  /* default ordering is ASC */
2086  if (attribute->ordering == SORTBY_DESC)
2087  colOptionP[attn] |= INDOPTION_DESC;
2088  /* default null ordering is LAST for ASC, FIRST for DESC */
2089  if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
2090  {
2091  if (attribute->ordering == SORTBY_DESC)
2092  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
2093  }
2094  else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
2095  colOptionP[attn] |= INDOPTION_NULLS_FIRST;
2096  }
2097  else
2098  {
2099  /* index AM does not support ordering */
2100  if (attribute->ordering != SORTBY_DEFAULT)
2101  ereport(ERROR,
2102  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2103  errmsg("access method \"%s\" does not support ASC/DESC options",
2104  accessMethodName)));
2105  if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
2106  ereport(ERROR,
2107  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2108  errmsg("access method \"%s\" does not support NULLS FIRST/LAST options",
2109  accessMethodName)));
2110  }
2111 
2112  /* Set up the per-column opclass options (attoptions field). */
2113  if (attribute->opclassopts)
2114  {
2115  Assert(attn < nkeycols);
2116 
2117  if (!indexInfo->ii_OpclassOptions)
2118  indexInfo->ii_OpclassOptions =
2119  palloc0_array(Datum, indexInfo->ii_NumIndexAttrs);
2120 
2121  indexInfo->ii_OpclassOptions[attn] =
2122  transformRelOptions((Datum) 0, attribute->opclassopts,
2123  NULL, NULL, false, false);
2124  }
2125 
2126  attn++;
2127  }
2128 }
2129 
2130 /*
2131  * Resolve possibly-defaulted operator class specification
2132  *
2133  * Note: This is used to resolve operator class specifications in index and
2134  * partition key definitions.
2135  */
2136 Oid
2137 ResolveOpClass(List *opclass, Oid attrType,
2138  const char *accessMethodName, Oid accessMethodId)
2139 {
2140  char *schemaname;
2141  char *opcname;
2142  HeapTuple tuple;
2143  Form_pg_opclass opform;
2144  Oid opClassId,
2145  opInputType;
2146 
2147  if (opclass == NIL)
2148  {
2149  /* no operator class specified, so find the default */
2150  opClassId = GetDefaultOpClass(attrType, accessMethodId);
2151  if (!OidIsValid(opClassId))
2152  ereport(ERROR,
2153  (errcode(ERRCODE_UNDEFINED_OBJECT),
2154  errmsg("data type %s has no default operator class for access method \"%s\"",
2155  format_type_be(attrType), accessMethodName),
2156  errhint("You must specify an operator class for the index or define a default operator class for the data type.")));
2157  return opClassId;
2158  }
2159 
2160  /*
2161  * Specific opclass name given, so look up the opclass.
2162  */
2163 
2164  /* deconstruct the name list */
2165  DeconstructQualifiedName(opclass, &schemaname, &opcname);
2166 
2167  if (schemaname)
2168  {
2169  /* Look in specific schema only */
2170  Oid namespaceId;
2171 
2172  namespaceId = LookupExplicitNamespace(schemaname, false);
2173  tuple = SearchSysCache3(CLAAMNAMENSP,
2174  ObjectIdGetDatum(accessMethodId),
2175  PointerGetDatum(opcname),
2176  ObjectIdGetDatum(namespaceId));
2177  }
2178  else
2179  {
2180  /* Unqualified opclass name, so search the search path */
2181  opClassId = OpclassnameGetOpcid(accessMethodId, opcname);
2182  if (!OidIsValid(opClassId))
2183  ereport(ERROR,
2184  (errcode(ERRCODE_UNDEFINED_OBJECT),
2185  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2186  opcname, accessMethodName)));
2187  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId));
2188  }
2189 
2190  if (!HeapTupleIsValid(tuple))
2191  ereport(ERROR,
2192  (errcode(ERRCODE_UNDEFINED_OBJECT),
2193  errmsg("operator class \"%s\" does not exist for access method \"%s\"",
2194  NameListToString(opclass), accessMethodName)));
2195 
2196  /*
2197  * Verify that the index operator class accepts this datatype. Note we
2198  * will accept binary compatibility.
2199  */
2200  opform = (Form_pg_opclass) GETSTRUCT(tuple);
2201  opClassId = opform->oid;
2202  opInputType = opform->opcintype;
2203 
2204  if (!IsBinaryCoercible(attrType, opInputType))
2205  ereport(ERROR,
2206  (errcode(ERRCODE_DATATYPE_MISMATCH),
2207  errmsg("operator class \"%s\" does not accept data type %s",
2208  NameListToString(opclass), format_type_be(attrType))));
2209 
2210  ReleaseSysCache(tuple);
2211 
2212  return opClassId;
2213 }
2214 
2215 /*
2216  * GetDefaultOpClass
2217  *
2218  * Given the OIDs of a datatype and an access method, find the default
2219  * operator class, if any. Returns InvalidOid if there is none.
2220  */
2221 Oid
2222 GetDefaultOpClass(Oid type_id, Oid am_id)
2223 {
2224  Oid result = InvalidOid;
2225  int nexact = 0;
2226  int ncompatible = 0;
2227  int ncompatiblepreferred = 0;
2228  Relation rel;
2229  ScanKeyData skey[1];
2230  SysScanDesc scan;
2231  HeapTuple tup;
2232  TYPCATEGORY tcategory;
2233 
2234  /* If it's a domain, look at the base type instead */
2235  type_id = getBaseType(type_id);
2236 
2237  tcategory = TypeCategory(type_id);
2238 
2239  /*
2240  * We scan through all the opclasses available for the access method,
2241  * looking for one that is marked default and matches the target type
2242  * (either exactly or binary-compatibly, but prefer an exact match).
2243  *
2244  * We could find more than one binary-compatible match. If just one is
2245  * for a preferred type, use that one; otherwise we fail, forcing the user
2246  * to specify which one he wants. (The preferred-type special case is a
2247  * kluge for varchar: it's binary-compatible to both text and bpchar, so
2248  * we need a tiebreaker.) If we find more than one exact match, then
2249  * someone put bogus entries in pg_opclass.
2250  */
2251  rel = table_open(OperatorClassRelationId, AccessShareLock);
2252 
2253  ScanKeyInit(&skey[0],
2254  Anum_pg_opclass_opcmethod,
2255  BTEqualStrategyNumber, F_OIDEQ,
2256  ObjectIdGetDatum(am_id));
2257 
2258  scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true,
2259  NULL, 1, skey);
2260 
2261  while (HeapTupleIsValid(tup = systable_getnext(scan)))
2262  {
2263  Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup);
2264 
2265  /* ignore altogether if not a default opclass */
2266  if (!opclass->opcdefault)
2267  continue;
2268  if (opclass->opcintype == type_id)
2269  {
2270  nexact++;
2271  result = opclass->oid;
2272  }
2273  else if (nexact == 0 &&
2274  IsBinaryCoercible(type_id, opclass->opcintype))
2275  {
2276  if (IsPreferredType(tcategory, opclass->opcintype))
2277  {
2278  ncompatiblepreferred++;
2279  result = opclass->oid;
2280  }
2281  else if (ncompatiblepreferred == 0)
2282  {
2283  ncompatible++;
2284  result = opclass->oid;
2285  }
2286  }
2287  }
2288 
2289  systable_endscan(scan);
2290 
2292 
2293  /* raise error if pg_opclass contains inconsistent data */
2294  if (nexact > 1)
2295  ereport(ERROR,
2297  errmsg("there are multiple default operator classes for data type %s",
2298  format_type_be(type_id))));
2299 
2300  if (nexact == 1 ||
2301  ncompatiblepreferred == 1 ||
2302  (ncompatiblepreferred == 0 && ncompatible == 1))
2303  return result;
2304 
2305  return InvalidOid;
2306 }
2307 
2308 /*
2309  * makeObjectName()
2310  *
2311  * Create a name for an implicitly created index, sequence, constraint,
2312  * extended statistics, etc.
2313  *
2314  * The parameters are typically: the original table name, the original field
2315  * name, and a "type" string (such as "seq" or "pkey"). The field name
2316  * and/or type can be NULL if not relevant.
2317  *
2318  * The result is a palloc'd string.
2319  *
2320  * The basic result we want is "name1_name2_label", omitting "_name2" or
2321  * "_label" when those parameters are NULL. However, we must generate
2322  * a name with less than NAMEDATALEN characters! So, we truncate one or
2323  * both names if necessary to make a short-enough string. The label part
2324  * is never truncated (so it had better be reasonably short).
2325  *
2326  * The caller is responsible for checking uniqueness of the generated
2327  * name and retrying as needed; retrying will be done by altering the
2328  * "label" string (which is why we never truncate that part).
2329  */
2330 char *
2331 makeObjectName(const char *name1, const char *name2, const char *label)
2332 {
2333  char *name;
2334  int overhead = 0; /* chars needed for label and underscores */
2335  int availchars; /* chars available for name(s) */
2336  int name1chars; /* chars allocated to name1 */
2337  int name2chars; /* chars allocated to name2 */
2338  int ndx;
2339 
2340  name1chars = strlen(name1);
2341  if (name2)
2342  {
2343  name2chars = strlen(name2);
2344  overhead++; /* allow for separating underscore */
2345  }
2346  else
2347  name2chars = 0;
2348  if (label)
2349  overhead += strlen(label) + 1;
2350 
2351  availchars = NAMEDATALEN - 1 - overhead;
2352  Assert(availchars > 0); /* else caller chose a bad label */
2353 
2354  /*
2355  * If we must truncate, preferentially truncate the longer name. This
2356  * logic could be expressed without a loop, but it's simple and obvious as
2357  * a loop.
2358  */
2359  while (name1chars + name2chars > availchars)
2360  {
2361  if (name1chars > name2chars)
2362  name1chars--;
2363  else
2364  name2chars--;
2365  }
2366 
2367  name1chars = pg_mbcliplen(name1, name1chars, name1chars);
2368  if (name2)
2369  name2chars = pg_mbcliplen(name2, name2chars, name2chars);
2370 
2371  /* Now construct the string using the chosen lengths */
2372  name = palloc(name1chars + name2chars + overhead + 1);
2373  memcpy(name, name1, name1chars);
2374  ndx = name1chars;
2375  if (name2)
2376  {
2377  name[ndx++] = '_';
2378  memcpy(name + ndx, name2, name2chars);
2379  ndx += name2chars;
2380  }
2381  if (label)
2382  {
2383  name[ndx++] = '_';
2384  strcpy(name + ndx, label);
2385  }
2386  else
2387  name[ndx] = '\0';
2388 
2389  return name;
2390 }
2391 
2392 /*
2393  * Select a nonconflicting name for a new relation. This is ordinarily
2394  * used to choose index names (which is why it's here) but it can also
2395  * be used for sequences, or any autogenerated relation kind.
2396  *
2397  * name1, name2, and label are used the same way as for makeObjectName(),
2398  * except that the label can't be NULL; digits will be appended to the label
2399  * if needed to create a name that is unique within the specified namespace.
2400  *
2401  * If isconstraint is true, we also avoid choosing a name matching any
2402  * existing constraint in the same namespace. (This is stricter than what
2403  * Postgres itself requires, but the SQL standard says that constraint names
2404  * should be unique within schemas, so we follow that for autogenerated
2405  * constraint names.)
2406  *
2407  * Note: it is theoretically possible to get a collision anyway, if someone
2408  * else chooses the same name concurrently. This is fairly unlikely to be
2409  * a problem in practice, especially if one is holding an exclusive lock on
2410  * the relation identified by name1. However, if choosing multiple names
2411  * within a single command, you'd better create the new object and do
2412  * CommandCounterIncrement before choosing the next one!
2413  *
2414  * Returns a palloc'd string.
2415  */
2416 char *
2417 ChooseRelationName(const char *name1, const char *name2,
2418  const char *label, Oid namespaceid,
2419  bool isconstraint)
2420 {
2421  int pass = 0;
2422  char *relname = NULL;
2423  char modlabel[NAMEDATALEN];
2424 
2425  /* try the unmodified label first */
2426  strlcpy(modlabel, label, sizeof(modlabel));
2427 
2428  for (;;)
2429  {
2430  relname = makeObjectName(name1, name2, modlabel);
2431 
2432  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2433  {
2434  if (!isconstraint ||
2435  !ConstraintNameExists(relname, namespaceid))
2436  break;
2437  }
2438 
2439  /* found a conflict, so try a new name component */
2440  pfree(relname);
2441  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2442  }
2443 
2444  return relname;
2445 }
2446 
2447 /*
2448  * Select the name to be used for an index.
2449  *
2450  * The argument list is pretty ad-hoc :-(
2451  */
2452 static char *
2453 ChooseIndexName(const char *tabname, Oid namespaceId,
2454  List *colnames, List *exclusionOpNames,
2455  bool primary, bool isconstraint)
2456 {
2457  char *indexname;
2458 
2459  if (primary)
2460  {
2461  /* the primary key's name does not depend on the specific column(s) */
2462  indexname = ChooseRelationName(tabname,
2463  NULL,
2464  "pkey",
2465  namespaceId,
2466  true);
2467  }
2468  else if (exclusionOpNames != NIL)
2469  {
2470  indexname = ChooseRelationName(tabname,
2471  ChooseIndexNameAddition(colnames),
2472  "excl",
2473  namespaceId,
2474  true);
2475  }
2476  else if (isconstraint)
2477  {
2478  indexname = ChooseRelationName(tabname,
2479  ChooseIndexNameAddition(colnames),
2480  "key",
2481  namespaceId,
2482  true);
2483  }
2484  else
2485  {
2486  indexname = ChooseRelationName(tabname,
2487  ChooseIndexNameAddition(colnames),
2488  "idx",
2489  namespaceId,
2490  false);
2491  }
2492 
2493  return indexname;
2494 }
2495 
2496 /*
2497  * Generate "name2" for a new index given the list of column names for it
2498  * (as produced by ChooseIndexColumnNames). This will be passed to
2499  * ChooseRelationName along with the parent table name and a suitable label.
2500  *
2501  * We know that less than NAMEDATALEN characters will actually be used,
2502  * so we can truncate the result once we've generated that many.
2503  *
2504  * XXX See also ChooseForeignKeyConstraintNameAddition and
2505  * ChooseExtendedStatisticNameAddition.
2506  */
2507 static char *
2509 {
2510  char buf[NAMEDATALEN * 2];
2511  int buflen = 0;
2512  ListCell *lc;
2513 
2514  buf[0] = '\0';
2515  foreach(lc, colnames)
2516  {
2517  const char *name = (const char *) lfirst(lc);
2518 
2519  if (buflen > 0)
2520  buf[buflen++] = '_'; /* insert _ between names */
2521 
2522  /*
2523  * At this point we have buflen <= NAMEDATALEN. name should be less
2524  * than NAMEDATALEN already, but use strlcpy for paranoia.
2525  */
2526  strlcpy(buf + buflen, name, NAMEDATALEN);
2527  buflen += strlen(buf + buflen);
2528  if (buflen >= NAMEDATALEN)
2529  break;
2530  }
2531  return pstrdup(buf);
2532 }
2533 
2534 /*
2535  * Select the actual names to be used for the columns of an index, given the
2536  * list of IndexElems for the columns. This is mostly about ensuring the
2537  * names are unique so we don't get a conflicting-attribute-names error.
2538  *
2539  * Returns a List of plain strings (char *, not String nodes).
2540  */
2541 static List *
2543 {
2544  List *result = NIL;
2545  ListCell *lc;
2546 
2547  foreach(lc, indexElems)
2548  {
2549  IndexElem *ielem = (IndexElem *) lfirst(lc);
2550  const char *origname;
2551  const char *curname;
2552  int i;
2553  char buf[NAMEDATALEN];
2554 
2555  /* Get the preliminary name from the IndexElem */
2556  if (ielem->indexcolname)
2557  origname = ielem->indexcolname; /* caller-specified name */
2558  else if (ielem->name)
2559  origname = ielem->name; /* simple column reference */
2560  else
2561  origname = "expr"; /* default name for expression */
2562 
2563  /* If it conflicts with any previous column, tweak it */
2564  curname = origname;
2565  for (i = 1;; i++)
2566  {
2567  ListCell *lc2;
2568  char nbuf[32];
2569  int nlen;
2570 
2571  foreach(lc2, result)
2572  {
2573  if (strcmp(curname, (char *) lfirst(lc2)) == 0)
2574  break;
2575  }
2576  if (lc2 == NULL)
2577  break; /* found nonconflicting name */
2578 
2579  sprintf(nbuf, "%d", i);
2580 
2581  /* Ensure generated names are shorter than NAMEDATALEN */
2582  nlen = pg_mbcliplen(origname, strlen(origname),
2583  NAMEDATALEN - 1 - strlen(nbuf));
2584  memcpy(buf, origname, nlen);
2585  strcpy(buf + nlen, nbuf);
2586  curname = buf;
2587  }
2588 
2589  /* And attach to the result list */
2590  result = lappend(result, pstrdup(curname));
2591  }
2592  return result;
2593 }
2594 
2595 /*
2596  * ExecReindex
2597  *
2598  * Primary entry point for manual REINDEX commands. This is mainly a
2599  * preparation wrapper for the real operations that will happen in
2600  * each subroutine of REINDEX.
2601  */
2602 void
2603 ExecReindex(ParseState *pstate, ReindexStmt *stmt, bool isTopLevel)
2604 {
2605  ReindexParams params = {0};
2606  ListCell *lc;
2607  bool concurrently = false;
2608  bool verbose = false;
2609  char *tablespacename = NULL;
2610 
2611  /* Parse option list */
2612  foreach(lc, stmt->params)
2613  {
2614  DefElem *opt = (DefElem *) lfirst(lc);
2615 
2616  if (strcmp(opt->defname, "verbose") == 0)
2617  verbose = defGetBoolean(opt);
2618  else if (strcmp(opt->defname, "concurrently") == 0)
2619  concurrently = defGetBoolean(opt);
2620  else if (strcmp(opt->defname, "tablespace") == 0)
2621  tablespacename = defGetString(opt);
2622  else
2623  ereport(ERROR,
2624  (errcode(ERRCODE_SYNTAX_ERROR),
2625  errmsg("unrecognized REINDEX option \"%s\"",
2626  opt->defname),
2627  parser_errposition(pstate, opt->location)));
2628  }
2629 
2630  if (concurrently)
2631  PreventInTransactionBlock(isTopLevel,
2632  "REINDEX CONCURRENTLY");
2633 
2634  params.options =
2635  (verbose ? REINDEXOPT_VERBOSE : 0) |
2636  (concurrently ? REINDEXOPT_CONCURRENTLY : 0);
2637 
2638  /*
2639  * Assign the tablespace OID to move indexes to, with InvalidOid to do
2640  * nothing.
2641  */
2642  if (tablespacename != NULL)
2643  {
2644  params.tablespaceOid = get_tablespace_oid(tablespacename, false);
2645 
2646  /* Check permissions except when moving to database's default */
2647  if (OidIsValid(params.tablespaceOid) &&
2649  {
2650  AclResult aclresult;
2651 
2652  aclresult = object_aclcheck(TableSpaceRelationId, params.tablespaceOid,
2653  GetUserId(), ACL_CREATE);
2654  if (aclresult != ACLCHECK_OK)
2655  aclcheck_error(aclresult, OBJECT_TABLESPACE,
2657  }
2658  }
2659  else
2660  params.tablespaceOid = InvalidOid;
2661 
2662  switch (stmt->kind)
2663  {
2664  case REINDEX_OBJECT_INDEX:
2665  ReindexIndex(stmt->relation, &params, isTopLevel);
2666  break;
2667  case REINDEX_OBJECT_TABLE:
2668  ReindexTable(stmt->relation, &params, isTopLevel);
2669  break;
2670  case REINDEX_OBJECT_SCHEMA:
2671  case REINDEX_OBJECT_SYSTEM:
2673 
2674  /*
2675  * This cannot run inside a user transaction block; if we were
2676  * inside a transaction, then its commit- and
2677  * start-transaction-command calls would not have the intended
2678  * effect!
2679  */
2680  PreventInTransactionBlock(isTopLevel,
2681  (stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" :
2682  (stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" :
2683  "REINDEX DATABASE");
2684  ReindexMultipleTables(stmt->name, stmt->kind, &params);
2685  break;
2686  default:
2687  elog(ERROR, "unrecognized object type: %d",
2688  (int) stmt->kind);
2689  break;
2690  }
2691 }
2692 
2693 /*
2694  * ReindexIndex
2695  * Recreate a specific index.
2696  */
2697 static void
2698 ReindexIndex(RangeVar *indexRelation, ReindexParams *params, bool isTopLevel)
2699 {
2701  Oid indOid;
2702  char persistence;
2703  char relkind;
2704 
2705  /*
2706  * Find and lock index, and check permissions on table; use callback to
2707  * obtain lock on table first, to avoid deadlock hazard. The lock level
2708  * used here must match the index lock obtained in reindex_index().
2709  *
2710  * If it's a temporary index, we will perform a non-concurrent reindex,
2711  * even if CONCURRENTLY was requested. In that case, reindex_index() will
2712  * upgrade the lock, but that's OK, because other sessions can't hold
2713  * locks on our temporary table.
2714  */
2715  state.params = *params;
2716  state.locked_table_oid = InvalidOid;
2717  indOid = RangeVarGetRelidExtended(indexRelation,
2720  0,
2722  &state);
2723 
2724  /*
2725  * Obtain the current persistence and kind of the existing index. We
2726  * already hold a lock on the index.
2727  */
2728  persistence = get_rel_persistence(indOid);
2729  relkind = get_rel_relkind(indOid);
2730 
2731  if (relkind == RELKIND_PARTITIONED_INDEX)
2732  ReindexPartitions(indOid, params, isTopLevel);
2733  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2734  persistence != RELPERSISTENCE_TEMP)
2736  else
2737  {
2738  ReindexParams newparams = *params;
2739 
2740  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2741  reindex_index(indOid, false, persistence, &newparams);
2742  }
2743 }
2744 
2745 /*
2746  * Check permissions on table before acquiring relation lock; also lock
2747  * the heap before the RangeVarGetRelidExtended takes the index lock, to avoid
2748  * deadlocks.
2749  */
2750 static void
2752  Oid relId, Oid oldRelId, void *arg)
2753 {
2754  char relkind;
2756  LOCKMODE table_lockmode;
2757 
2758  /*
2759  * Lock level here should match table lock in reindex_index() for
2760  * non-concurrent case and table locks used by index_concurrently_*() for
2761  * concurrent case.
2762  */
2763  table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ?
2765 
2766  /*
2767  * If we previously locked some other index's heap, and the name we're
2768  * looking up no longer refers to that relation, release the now-useless
2769  * lock.
2770  */
2771  if (relId != oldRelId && OidIsValid(oldRelId))
2772  {
2773  UnlockRelationOid(state->locked_table_oid, table_lockmode);
2774  state->locked_table_oid = InvalidOid;
2775  }
2776 
2777  /* If the relation does not exist, there's nothing more to do. */
2778  if (!OidIsValid(relId))
2779  return;
2780 
2781  /*
2782  * If the relation does exist, check whether it's an index. But note that
2783  * the relation might have been dropped between the time we did the name
2784  * lookup and now. In that case, there's nothing to do.
2785  */
2786  relkind = get_rel_relkind(relId);
2787  if (!relkind)
2788  return;
2789  if (relkind != RELKIND_INDEX &&
2790  relkind != RELKIND_PARTITIONED_INDEX)
2791  ereport(ERROR,
2792  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2793  errmsg("\"%s\" is not an index", relation->relname)));
2794 
2795  /* Check permissions */
2796  if (!object_ownercheck(RelationRelationId, relId, GetUserId()))
2798 
2799  /* Lock heap before index to avoid deadlock. */
2800  if (relId != oldRelId)
2801  {
2802  Oid table_oid = IndexGetRelation(relId, true);
2803 
2804  /*
2805  * If the OID isn't valid, it means the index was concurrently
2806  * dropped, which is not a problem for us; just return normally.
2807  */
2808  if (OidIsValid(table_oid))
2809  {
2810  LockRelationOid(table_oid, table_lockmode);
2811  state->locked_table_oid = table_oid;
2812  }
2813  }
2814 }
2815 
2816 /*
2817  * ReindexTable
2818  * Recreate all indexes of a table (and of its toast table, if any)
2819  */
2820 static Oid
2821 ReindexTable(RangeVar *relation, ReindexParams *params, bool isTopLevel)
2822 {
2823  Oid heapOid;
2824  bool result;
2825 
2826  /*
2827  * The lock level used here should match reindex_relation().
2828  *
2829  * If it's a temporary table, we will perform a non-concurrent reindex,
2830  * even if CONCURRENTLY was requested. In that case, reindex_relation()
2831  * will upgrade the lock, but that's OK, because other sessions can't hold
2832  * locks on our temporary table.
2833  */
2834  heapOid = RangeVarGetRelidExtended(relation,
2837  0,
2839 
2840  if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE)
2841  ReindexPartitions(heapOid, params, isTopLevel);
2842  else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
2843  get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP)
2844  {
2845  result = ReindexRelationConcurrently(heapOid, params);
2846 
2847  if (!result)
2848  ereport(NOTICE,
2849  (errmsg("table \"%s\" has no indexes that can be reindexed concurrently",
2850  relation->relname)));
2851  }
2852  else
2853  {
2854  ReindexParams newparams = *params;
2855 
2856  newparams.options |= REINDEXOPT_REPORT_PROGRESS;
2857  result = reindex_relation(heapOid,
2860  &newparams);
2861  if (!result)
2862  ereport(NOTICE,
2863  (errmsg("table \"%s\" has no indexes to reindex",
2864  relation->relname)));
2865  }
2866 
2867  return heapOid;
2868 }
2869 
2870 /*
2871  * ReindexMultipleTables
2872  * Recreate indexes of tables selected by objectName/objectKind.
2873  *
2874  * To reduce the probability of deadlocks, each table is reindexed in a
2875  * separate transaction, so we can release the lock on it right away.
2876  * That means this must not be called within a user transaction block!
2877  */
2878 static void
2879 ReindexMultipleTables(const char *objectName, ReindexObjectType objectKind,
2881 {
2882  Oid objectOid;
2883  Relation relationRelation;
2884  TableScanDesc scan;
2885  ScanKeyData scan_keys[1];
2886  HeapTuple tuple;
2887  MemoryContext private_context;
2888  MemoryContext old;
2889  List *relids = NIL;
2890  int num_keys;
2891  bool concurrent_warning = false;
2892  bool tablespace_warning = false;
2893 
2894  Assert(objectKind == REINDEX_OBJECT_SCHEMA ||
2895  objectKind == REINDEX_OBJECT_SYSTEM ||
2896  objectKind == REINDEX_OBJECT_DATABASE);
2897 
2898  /*
2899  * This matches the options enforced by the grammar, where the object name
2900  * is optional for DATABASE and SYSTEM.
2901  */
2902  Assert(objectName || objectKind != REINDEX_OBJECT_SCHEMA);
2903 
2904  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2906  ereport(ERROR,
2907  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2908  errmsg("cannot reindex system catalogs concurrently")));
2909 
2910  /*
2911  * Get OID of object to reindex, being the database currently being used
2912  * by session for a database or for system catalogs, or the schema defined
2913  * by caller. At the same time do permission checks that need different
2914  * processing depending on the object type.
2915  */
2916  if (objectKind == REINDEX_OBJECT_SCHEMA)
2917  {
2918  objectOid = get_namespace_oid(objectName, false);
2919 
2920  if (!object_ownercheck(NamespaceRelationId, objectOid, GetUserId()))
2922  objectName);
2923  }
2924  else
2925  {
2926  objectOid = MyDatabaseId;
2927 
2928  if (objectName && strcmp(objectName, get_database_name(objectOid)) != 0)
2929  ereport(ERROR,
2930  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2931  errmsg("can only reindex the currently open database")));
2932  if (!object_ownercheck(DatabaseRelationId, objectOid, GetUserId()))
2934  get_database_name(objectOid));
2935  }
2936 
2937  /*
2938  * Create a memory context that will survive forced transaction commits we
2939  * do below. Since it is a child of PortalContext, it will go away
2940  * eventually even if we suffer an error; there's no need for special
2941  * abort cleanup logic.
2942  */
2943  private_context = AllocSetContextCreate(PortalContext,
2944  "ReindexMultipleTables",
2946 
2947  /*
2948  * Define the search keys to find the objects to reindex. For a schema, we
2949  * select target relations using relnamespace, something not necessary for
2950  * a database-wide operation.
2951  */
2952  if (objectKind == REINDEX_OBJECT_SCHEMA)
2953  {
2954  num_keys = 1;
2955  ScanKeyInit(&scan_keys[0],
2956  Anum_pg_class_relnamespace,
2957  BTEqualStrategyNumber, F_OIDEQ,
2958  ObjectIdGetDatum(objectOid));
2959  }
2960  else
2961  num_keys = 0;
2962 
2963  /*
2964  * Scan pg_class to build a list of the relations we need to reindex.
2965  *
2966  * We only consider plain relations and materialized views here (toast
2967  * rels will be processed indirectly by reindex_relation).
2968  */
2969  relationRelation = table_open(RelationRelationId, AccessShareLock);
2970  scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys);
2971  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2972  {
2973  Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple);
2974  Oid relid = classtuple->oid;
2975 
2976  /*
2977  * Only regular tables and matviews can have indexes, so ignore any
2978  * other kind of relation.
2979  *
2980  * Partitioned tables/indexes are skipped but matching leaf partitions
2981  * are processed.
2982  */
2983  if (classtuple->relkind != RELKIND_RELATION &&
2984  classtuple->relkind != RELKIND_MATVIEW)
2985  continue;
2986 
2987  /* Skip temp tables of other backends; we can't reindex them at all */
2988  if (classtuple->relpersistence == RELPERSISTENCE_TEMP &&
2989  !isTempNamespace(classtuple->relnamespace))
2990  continue;
2991 
2992  /*
2993  * Check user/system classification. SYSTEM processes all the
2994  * catalogs, and DATABASE processes everything that's not a catalog.
2995  */
2996  if (objectKind == REINDEX_OBJECT_SYSTEM &&
2997  !IsCatalogRelationOid(relid))
2998  continue;
2999  else if (objectKind == REINDEX_OBJECT_DATABASE &&
3000  IsCatalogRelationOid(relid))
3001  continue;
3002 
3003  /*
3004  * The table can be reindexed if the user is superuser, the table
3005  * owner, or the database/schema owner (but in the latter case, only
3006  * if it's not a shared relation). object_ownercheck includes the
3007  * superuser case, and depending on objectKind we already know that
3008  * the user has permission to run REINDEX on this database or schema
3009  * per the permission checks at the beginning of this routine.
3010  */
3011  if (classtuple->relisshared &&
3012  !object_ownercheck(RelationRelationId, relid, GetUserId()))
3013  continue;
3014 
3015  /*
3016  * Skip system tables, since index_create() would reject indexing them
3017  * concurrently (and it would likely fail if we tried).
3018  */
3019  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3020  IsCatalogRelationOid(relid))
3021  {
3022  if (!concurrent_warning)
3023  ereport(WARNING,
3024  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3025  errmsg("cannot reindex system catalogs concurrently, skipping all")));
3026  concurrent_warning = true;
3027  continue;
3028  }
3029 
3030  /*
3031  * If a new tablespace is set, check if this relation has to be
3032  * skipped.
3033  */
3035  {
3036  bool skip_rel = false;
3037 
3038  /*
3039  * Mapped relations cannot be moved to different tablespaces (in
3040  * particular this eliminates all shared catalogs.).
3041  */
3042  if (RELKIND_HAS_STORAGE(classtuple->relkind) &&
3043  !RelFileNumberIsValid(classtuple->relfilenode))
3044  skip_rel = true;
3045 
3046  /*
3047  * A system relation is always skipped, even with
3048  * allow_system_table_mods enabled.
3049  */
3050  if (IsSystemClass(relid, classtuple))
3051  skip_rel = true;
3052 
3053  if (skip_rel)
3054  {
3055  if (!tablespace_warning)
3056  ereport(WARNING,
3057  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3058  errmsg("cannot move system relations, skipping all")));
3059  tablespace_warning = true;
3060  continue;
3061  }
3062  }
3063 
3064  /* Save the list of relation OIDs in private context */
3065  old = MemoryContextSwitchTo(private_context);
3066 
3067  /*
3068  * We always want to reindex pg_class first if it's selected to be
3069  * reindexed. This ensures that if there is any corruption in
3070  * pg_class' indexes, they will be fixed before we process any other
3071  * tables. This is critical because reindexing itself will try to
3072  * update pg_class.
3073  */
3074  if (relid == RelationRelationId)
3075  relids = lcons_oid(relid, relids);
3076  else
3077  relids = lappend_oid(relids, relid);
3078 
3079  MemoryContextSwitchTo(old);
3080  }
3081  table_endscan(scan);
3082  table_close(relationRelation, AccessShareLock);
3083 
3084  /*
3085  * Process each relation listed in a separate transaction. Note that this
3086  * commits and then starts a new transaction immediately.
3087  */
3089 
3090  MemoryContextDelete(private_context);
3091 }
3092 
3093 /*
3094  * Error callback specific to ReindexPartitions().
3095  */
3096 static void
3098 {
3099  ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg;
3100 
3101  Assert(RELKIND_HAS_PARTITIONS(errinfo->relkind));
3102 
3103  if (errinfo->relkind == RELKIND_PARTITIONED_TABLE)
3104  errcontext("while reindexing partitioned table \"%s.%s\"",
3105  errinfo->relnamespace, errinfo->relname);
3106  else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX)
3107  errcontext("while reindexing partitioned index \"%s.%s\"",
3108  errinfo->relnamespace, errinfo->relname);
3109 }
3110 
3111 /*
3112  * ReindexPartitions
3113  *
3114  * Reindex a set of partitions, per the partitioned index or table given
3115  * by the caller.
3116  */
3117 static void
3118 ReindexPartitions(Oid relid, ReindexParams *params, bool isTopLevel)
3119 {
3120  List *partitions = NIL;
3121  char relkind = get_rel_relkind(relid);
3122  char *relname = get_rel_name(relid);
3123  char *relnamespace = get_namespace_name(get_rel_namespace(relid));
3124  MemoryContext reindex_context;
3125  List *inhoids;
3126  ListCell *lc;
3127  ErrorContextCallback errcallback;
3128  ReindexErrorInfo errinfo;
3129 
3130  Assert(RELKIND_HAS_PARTITIONS(relkind));
3131 
3132  /*
3133  * Check if this runs in a transaction block, with an error callback to
3134  * provide more context under which a problem happens.
3135  */
3136  errinfo.relname = pstrdup(relname);
3137  errinfo.relnamespace = pstrdup(relnamespace);
3138  errinfo.relkind = relkind;
3139  errcallback.callback = reindex_error_callback;
3140  errcallback.arg = (void *) &errinfo;
3141  errcallback.previous = error_context_stack;
3142  error_context_stack = &errcallback;
3143 
3144  PreventInTransactionBlock(isTopLevel,
3145  relkind == RELKIND_PARTITIONED_TABLE ?
3146  "REINDEX TABLE" : "REINDEX INDEX");
3147 
3148  /* Pop the error context stack */
3149  error_context_stack = errcallback.previous;
3150 
3151  /*
3152  * Create special memory context for cross-transaction storage.
3153  *
3154  * Since it is a child of PortalContext, it will go away eventually even
3155  * if we suffer an error so there is no need for special abort cleanup
3156  * logic.
3157  */
3158  reindex_context = AllocSetContextCreate(PortalContext, "Reindex",
3160 
3161  /* ShareLock is enough to prevent schema modifications */
3162  inhoids = find_all_inheritors(relid, ShareLock, NULL);
3163 
3164  /*
3165  * The list of relations to reindex are the physical partitions of the
3166  * tree so discard any partitioned table or index.
3167  */
3168  foreach(lc, inhoids)
3169  {
3170  Oid partoid = lfirst_oid(lc);
3171  char partkind = get_rel_relkind(partoid);
3172  MemoryContext old_context;
3173 
3174  /*
3175  * This discards partitioned tables, partitioned indexes and foreign
3176  * tables.
3177  */
3178  if (!RELKIND_HAS_STORAGE(partkind))
3179  continue;
3180 
3181  Assert(partkind == RELKIND_INDEX ||
3182  partkind == RELKIND_RELATION);
3183 
3184  /* Save partition OID */
3185  old_context = MemoryContextSwitchTo(reindex_context);
3186  partitions = lappend_oid(partitions, partoid);
3187  MemoryContextSwitchTo(old_context);
3188  }
3189 
3190  /*
3191  * Process each partition listed in a separate transaction. Note that
3192  * this commits and then starts a new transaction immediately.
3193  */
3195 
3196  /*
3197  * Clean up working storage --- note we must do this after
3198  * StartTransactionCommand, else we might be trying to delete the active
3199  * context!
3200  */
3201  MemoryContextDelete(reindex_context);
3202 }
3203 
3204 /*
3205  * ReindexMultipleInternal
3206  *
3207  * Reindex a list of relations, each one being processed in its own
3208  * transaction. This commits the existing transaction immediately,
3209  * and starts a new transaction when finished.
3210  */
3211 static void
3213 {
3214  ListCell *l;
3215 
3218 
3219  foreach(l, relids)
3220  {
3221  Oid relid = lfirst_oid(l);
3222  char relkind;
3223  char relpersistence;
3224 
3226 
3227  /* functions in indexes may want a snapshot set */
3229 
3230  /* check if the relation still exists */
3232  {
3235  continue;
3236  }
3237 
3238  /*
3239  * Check permissions except when moving to database's default if a new
3240  * tablespace is chosen. Note that this check also happens in
3241  * ExecReindex(), but we do an extra check here as this runs across
3242  * multiple transactions.
3243  */
3246  {
3247  AclResult aclresult;
3248 
3249  aclresult = object_aclcheck(TableSpaceRelationId, params->tablespaceOid,
3250  GetUserId(), ACL_CREATE);
3251  if (aclresult != ACLCHECK_OK)
3252  aclcheck_error(aclresult, OBJECT_TABLESPACE,
3254  }
3255 
3256  relkind = get_rel_relkind(relid);
3257  relpersistence = get_rel_persistence(relid);
3258 
3259  /*
3260  * Partitioned tables and indexes can never be processed directly, and
3261  * a list of their leaves should be built first.
3262  */
3263  Assert(!RELKIND_HAS_PARTITIONS(relkind));
3264 
3265  if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 &&
3266  relpersistence != RELPERSISTENCE_TEMP)
3267  {
3268  ReindexParams newparams = *params;
3269 
3270  newparams.options |= REINDEXOPT_MISSING_OK;
3271  (void) ReindexRelationConcurrently(relid, &newparams);
3272  /* ReindexRelationConcurrently() does the verbose output */
3273  }
3274  else if (relkind == RELKIND_INDEX)
3275  {
3276  ReindexParams newparams = *params;
3277 
3278  newparams.options |=
3280  reindex_index(relid, false, relpersistence, &newparams);
3282  /* reindex_index() does the verbose output */
3283  }
3284  else
3285  {
3286  bool result;
3287  ReindexParams newparams = *params;
3288 
3289  newparams.options |=
3291  result = reindex_relation(relid,
3294  &newparams);
3295 
3296  if (result && (params->options & REINDEXOPT_VERBOSE) != 0)
3297  ereport(INFO,
3298  (errmsg("table \"%s.%s\" was reindexed",
3300  get_rel_name(relid))));
3301 
3303  }
3304 
3306  }
3307 
3309 }
3310 
3311 
3312 /*
3313  * ReindexRelationConcurrently - process REINDEX CONCURRENTLY for given
3314  * relation OID
3315  *
3316  * 'relationOid' can either belong to an index, a table or a materialized
3317  * view. For tables and materialized views, all its indexes will be rebuilt,
3318  * excluding invalid indexes and any indexes used in exclusion constraints,
3319  * but including its associated toast table indexes. For indexes, the index
3320  * itself will be rebuilt.
3321  *
3322  * The locks taken on parent tables and involved indexes are kept until the
3323  * transaction is committed, at which point a session lock is taken on each
3324  * relation. Both of these protect against concurrent schema changes.
3325  *
3326  * Returns true if any indexes have been rebuilt (including toast table's
3327  * indexes, when relevant), otherwise returns false.
3328  *
3329  * NOTE: This cannot be used on temporary relations. A concurrent build would
3330  * cause issues with ON COMMIT actions triggered by the transactions of the
3331  * concurrent build. Temporary relations are not subject to concurrent
3332  * concerns, so there's no need for the more complicated concurrent build,
3333  * anyway, and a non-concurrent reindex is more efficient.
3334  */
3335 static bool
3337 {
3338  typedef struct ReindexIndexInfo
3339  {
3340  Oid indexId;
3341  Oid tableId;
3342  Oid amId;
3343  bool safe; /* for set_indexsafe_procflags */
3344  } ReindexIndexInfo;
3345  List *heapRelationIds = NIL;
3346  List *indexIds = NIL;
3347  List *newIndexIds = NIL;
3348  List *relationLocks = NIL;
3349  List *lockTags = NIL;
3350  ListCell *lc,
3351  *lc2;
3352  MemoryContext private_context;
3353  MemoryContext oldcontext;
3354  char relkind;
3355  char *relationName = NULL;
3356  char *relationNamespace = NULL;
3357  PGRUsage ru0;
3358  const int progress_index[] = {
3363  };
3364  int64 progress_vals[4];
3365 
3366  /*
3367  * Create a memory context that will survive forced transaction commits we
3368  * do below. Since it is a child of PortalContext, it will go away
3369  * eventually even if we suffer an error; there's no need for special
3370  * abort cleanup logic.
3371  */
3372  private_context = AllocSetContextCreate(PortalContext,
3373  "ReindexConcurrent",
3375 
3376  if ((params->options & REINDEXOPT_VERBOSE) != 0)
3377  {
3378  /* Save data needed by REINDEX VERBOSE in private context */
3379  oldcontext = MemoryContextSwitchTo(private_context);
3380 
3381  relationName = get_rel_name(relationOid);
3382  relationNamespace = get_namespace_name(get_rel_namespace(relationOid));
3383 
3384  pg_rusage_init(&ru0);
3385 
3386  MemoryContextSwitchTo(oldcontext);
3387  }
3388 
3389  relkind = get_rel_relkind(relationOid);
3390 
3391  /*
3392  * Extract the list of indexes that are going to be rebuilt based on the
3393  * relation Oid given by caller.
3394  */
3395  switch (relkind)
3396  {
3397  case RELKIND_RELATION:
3398  case RELKIND_MATVIEW:
3399  case RELKIND_TOASTVALUE:
3400  {
3401  /*
3402  * In the case of a relation, find all its indexes including
3403  * toast indexes.
3404  */
3405  Relation heapRelation;
3406 
3407  /* Save the list of relation OIDs in private context */
3408  oldcontext = MemoryContextSwitchTo(private_context);
3409 
3410  /* Track this relation for session locks */
3411  heapRelationIds = lappend_oid(heapRelationIds, relationOid);
3412 
3413  MemoryContextSwitchTo(oldcontext);
3414 
3415  if (IsCatalogRelationOid(relationOid))
3416  ereport(ERROR,
3417  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3418  errmsg("cannot reindex system catalogs concurrently")));
3419 
3420  /* Open relation to get its indexes */
3421  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3422  {
3423  heapRelation = try_table_open(relationOid,
3425  /* leave if relation does not exist */
3426  if (!heapRelation)
3427  break;
3428  }
3429  else
3430  heapRelation = table_open(relationOid,
3432 
3433  if (OidIsValid(params->tablespaceOid) &&
3434  IsSystemRelation(heapRelation))
3435  ereport(ERROR,
3436  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3437  errmsg("cannot move system relation \"%s\"",
3438  RelationGetRelationName(heapRelation))));
3439 
3440  /* Add all the valid indexes of relation to list */
3441  foreach(lc, RelationGetIndexList(heapRelation))
3442  {
3443  Oid cellOid = lfirst_oid(lc);
3444  Relation indexRelation = index_open(cellOid,
3446 
3447  if (!indexRelation->rd_index->indisvalid)
3448  ereport(WARNING,
3449  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3450  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3452  get_rel_name(cellOid))));
3453  else if (indexRelation->rd_index->indisexclusion)
3454  ereport(WARNING,
3455  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3456  errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping",
3458  get_rel_name(cellOid))));
3459  else
3460  {
3461  ReindexIndexInfo *idx;
3462 
3463  /* Save the list of relation OIDs in private context */
3464  oldcontext = MemoryContextSwitchTo(private_context);
3465 
3466  idx = palloc_object(ReindexIndexInfo);
3467  idx->indexId = cellOid;
3468  /* other fields set later */
3469 
3470  indexIds = lappend(indexIds, idx);
3471 
3472  MemoryContextSwitchTo(oldcontext);
3473  }
3474 
3475  index_close(indexRelation, NoLock);
3476  }
3477 
3478  /* Also add the toast indexes */
3479  if (OidIsValid(heapRelation->rd_rel->reltoastrelid))
3480  {
3481  Oid toastOid = heapRelation->rd_rel->reltoastrelid;
3482  Relation toastRelation = table_open(toastOid,
3484 
3485  /* Save the list of relation OIDs in private context */
3486  oldcontext = MemoryContextSwitchTo(private_context);
3487 
3488  /* Track this relation for session locks */
3489  heapRelationIds = lappend_oid(heapRelationIds, toastOid);
3490 
3491  MemoryContextSwitchTo(oldcontext);
3492 
3493  foreach(lc2, RelationGetIndexList(toastRelation))
3494  {
3495  Oid cellOid = lfirst_oid(lc2);
3496  Relation indexRelation = index_open(cellOid,
3498 
3499  if (!indexRelation->rd_index->indisvalid)
3500  ereport(WARNING,
3501  (errcode(ERRCODE_INDEX_CORRUPTED),
3502  errmsg("cannot reindex invalid index \"%s.%s\" concurrently, skipping",
3504  get_rel_name(cellOid))));
3505  else
3506  {
3507  ReindexIndexInfo *idx;
3508 
3509  /*
3510  * Save the list of relation OIDs in private
3511  * context
3512  */
3513  oldcontext = MemoryContextSwitchTo(private_context);
3514 
3515  idx = palloc_object(ReindexIndexInfo);
3516  idx->indexId = cellOid;
3517  indexIds = lappend(indexIds, idx);
3518  /* other fields set later */
3519 
3520  MemoryContextSwitchTo(oldcontext);
3521  }
3522 
3523  index_close(indexRelation, NoLock);
3524  }
3525 
3526  table_close(toastRelation, NoLock);
3527  }
3528 
3529  table_close(heapRelation, NoLock);
3530  break;
3531  }
3532  case RELKIND_INDEX:
3533  {
3534  Oid heapId = IndexGetRelation(relationOid,
3535  (params->options & REINDEXOPT_MISSING_OK) != 0);
3536  Relation heapRelation;
3537  ReindexIndexInfo *idx;
3538 
3539  /* if relation is missing, leave */
3540  if (!OidIsValid(heapId))
3541  break;
3542 
3543  if (IsCatalogRelationOid(heapId))
3544  ereport(ERROR,
3545  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3546  errmsg("cannot reindex system catalogs concurrently")));
3547 
3548  /*
3549  * Don't allow reindex for an invalid index on TOAST table, as
3550  * if rebuilt it would not be possible to drop it. Match
3551  * error message in reindex_index().
3552  */
3553  if (IsToastNamespace(get_rel_namespace(relationOid)) &&
3554  !get_index_isvalid(relationOid))
3555  ereport(ERROR,
3556  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3557  errmsg("cannot reindex invalid index on TOAST table")));
3558 
3559  /*
3560  * Check if parent relation can be locked and if it exists,
3561  * this needs to be done at this stage as the list of indexes
3562  * to rebuild is not complete yet, and REINDEXOPT_MISSING_OK
3563  * should not be used once all the session locks are taken.
3564  */
3565  if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3566  {
3567  heapRelation = try_table_open(heapId,
3569  /* leave if relation does not exist */
3570  if (!heapRelation)
3571  break;
3572  }
3573  else
3574  heapRelation = table_open(heapId,
3576 
3577  if (OidIsValid(params->tablespaceOid) &&
3578  IsSystemRelation(heapRelation))
3579  ereport(ERROR,
3580  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3581  errmsg("cannot move system relation \"%s\"",
3582  get_rel_name(relationOid))));
3583 
3584  table_close(heapRelation, NoLock);
3585 
3586  /* Save the list of relation OIDs in private context */
3587  oldcontext = MemoryContextSwitchTo(private_context);
3588 
3589  /* Track the heap relation of this index for session locks */
3590  heapRelationIds = list_make1_oid(heapId);
3591 
3592  /*
3593  * Save the list of relation OIDs in private context. Note
3594  * that invalid indexes are allowed here.
3595  */
3596  idx = palloc_object(ReindexIndexInfo);
3597  idx->indexId = relationOid;
3598  indexIds = lappend(indexIds, idx);
3599  /* other fields set later */
3600 
3601  MemoryContextSwitchTo(oldcontext);
3602  break;
3603  }
3604 
3605  case RELKIND_PARTITIONED_TABLE:
3606  case RELKIND_PARTITIONED_INDEX:
3607  default:
3608  /* Return error if type of relation is not supported */
3609  ereport(ERROR,
3610  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3611  errmsg("cannot reindex this type of relation concurrently")));
3612  break;
3613  }
3614 
3615  /*
3616  * Definitely no indexes, so leave. Any checks based on
3617  * REINDEXOPT_MISSING_OK should be done only while the list of indexes to
3618  * work on is built as the session locks taken before this transaction
3619  * commits will make sure that they cannot be dropped by a concurrent
3620  * session until this operation completes.
3621  */
3622  if (indexIds == NIL)
3623  {
3625  return false;
3626  }
3627 
3628  /* It's not a shared catalog, so refuse to move it to shared tablespace */
3629  if (params->tablespaceOid == GLOBALTABLESPACE_OID)
3630  ereport(ERROR,
3631  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3632  errmsg("cannot move non-shared relation to tablespace \"%s\"",
3633  get_tablespace_name(params->tablespaceOid))));
3634 
3635  Assert(heapRelationIds != NIL);
3636 
3637  /*-----
3638  * Now we have all the indexes we want to process in indexIds.
3639  *
3640  * The phases now are:
3641  *
3642  * 1. create new indexes in the catalog
3643  * 2. build new indexes
3644  * 3. let new indexes catch up with tuples inserted in the meantime
3645  * 4. swap index names
3646  * 5. mark old indexes as dead
3647  * 6. drop old indexes
3648  *
3649  * We process each phase for all indexes before moving to the next phase,
3650  * for efficiency.
3651  */
3652 
3653  /*
3654  * Phase 1 of REINDEX CONCURRENTLY
3655  *
3656  * Create a new index with the same properties as the old one, but it is
3657  * only registered in catalogs and will be built later. Then get session
3658  * locks on all involved tables. See analogous code in DefineIndex() for
3659  * more detailed comments.
3660  */
3661 
3662  foreach(lc, indexIds)
3663  {
3664  char *concurrentName;
3665  ReindexIndexInfo *idx = lfirst(lc);
3666  ReindexIndexInfo *newidx;
3667  Oid newIndexId;
3668  Relation indexRel;
3669  Relation heapRel;
3670  Oid save_userid;
3671  int save_sec_context;
3672  int save_nestlevel;
3673  Relation newIndexRel;
3674  LockRelId *lockrelid;
3675  Oid tablespaceid;
3676 
3677  indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock);
3678  heapRel = table_open(indexRel->rd_index->indrelid,
3680 
3681  /*
3682  * Switch to the table owner's userid, so that any index functions are
3683  * run as that user. Also lock down security-restricted operations
3684  * and arrange to make GUC variable changes local to this command.
3685  */
3686  GetUserIdAndSecContext(&save_userid, &save_sec_context);
3687  SetUserIdAndSecContext(heapRel->rd_rel->relowner,
3688  save_sec_context | SECURITY_RESTRICTED_OPERATION);
3689  save_nestlevel = NewGUCNestLevel();
3690 
3691  /* determine safety of this index for set_indexsafe_procflags */
3692  idx->safe = (indexRel->rd_indexprs == NIL &&
3693  indexRel->rd_indpred == NIL);
3694  idx->tableId = RelationGetRelid(heapRel);
3695  idx->amId = indexRel->rd_rel->relam;
3696 
3697  /* This function shouldn't be called for temporary relations. */
3698  if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
3699  elog(ERROR, "cannot reindex a temporary table concurrently");
3700 
3702  idx->tableId);
3703 
3705  progress_vals[1] = 0; /* initializing */
3706  progress_vals[2] = idx->indexId;
3707  progress_vals[3] = idx->amId;
3708  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3709 
3710  /* Choose a temporary relation name for the new index */
3711  concurrentName = ChooseRelationName(get_rel_name(idx->indexId),
3712  NULL,
3713  "ccnew",
3714  get_rel_namespace(indexRel->rd_index->indrelid),
3715  false);
3716 
3717  /* Choose the new tablespace, indexes of toast tables are not moved */
3718  if (OidIsValid(params->tablespaceOid) &&
3719  heapRel->rd_rel->relkind != RELKIND_TOASTVALUE)
3720  tablespaceid = params->tablespaceOid;
3721  else
3722  tablespaceid = indexRel->rd_rel->reltablespace;
3723 
3724  /* Create new index definition based on given index */
3725  newIndexId = index_concurrently_create_copy(heapRel,
3726  idx->indexId,
3727  tablespaceid,
3728  concurrentName);
3729 
3730  /*
3731  * Now open the relation of the new index, a session-level lock is
3732  * also needed on it.
3733  */
3734  newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock);
3735 
3736  /*
3737  * Save the list of OIDs and locks in private context
3738  */
3739  oldcontext = MemoryContextSwitchTo(private_context);
3740 
3741  newidx = palloc_object(ReindexIndexInfo);
3742  newidx->indexId = newIndexId;
3743  newidx->safe = idx->safe;
3744  newidx->tableId = idx->tableId;
3745  newidx->amId = idx->amId;
3746 
3747  newIndexIds = lappend(newIndexIds, newidx);
3748 
3749  /*
3750  * Save lockrelid to protect each relation from drop then close
3751  * relations. The lockrelid on parent relation is not taken here to
3752  * avoid multiple locks taken on the same relation, instead we rely on
3753  * parentRelationIds built earlier.
3754  */
3755  lockrelid = palloc_object(LockRelId);
3756  *lockrelid = indexRel->rd_lockInfo.lockRelId;
3757  relationLocks = lappend(relationLocks, lockrelid);
3758  lockrelid = palloc_object(LockRelId);
3759  *lockrelid = newIndexRel->rd_lockInfo.lockRelId;
3760  relationLocks = lappend(relationLocks, lockrelid);
3761 
3762  MemoryContextSwitchTo(oldcontext);
3763 
3764  index_close(indexRel, NoLock);
3765  index_close(newIndexRel, NoLock);
3766 
3767  /* Roll back any GUC changes executed by index functions */
3768  AtEOXact_GUC(false, save_nestlevel);
3769 
3770  /* Restore userid and security context */
3771  SetUserIdAndSecContext(save_userid, save_sec_context);
3772 
3773  table_close(heapRel, NoLock);
3774  }
3775 
3776  /*
3777  * Save the heap lock for following visibility checks with other backends
3778  * might conflict with this session.
3779  */
3780  foreach(lc, heapRelationIds)
3781  {
3783  LockRelId *lockrelid;
3784  LOCKTAG *heaplocktag;
3785 
3786  /* Save the list of locks in private context */
3787  oldcontext = MemoryContextSwitchTo(private_context);
3788 
3789  /* Add lockrelid of heap relation to the list of locked relations */
3790  lockrelid = palloc_object(LockRelId);
3791  *lockrelid = heapRelation->rd_lockInfo.lockRelId;
3792  relationLocks = lappend(relationLocks, lockrelid);
3793 
3794  heaplocktag = palloc_object(LOCKTAG);
3795 
3796  /* Save the LOCKTAG for this parent relation for the wait phase */
3797  SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId);
3798  lockTags = lappend(lockTags, heaplocktag);
3799 
3800  MemoryContextSwitchTo(oldcontext);
3801 
3802  /* Close heap relation */
3803  table_close(heapRelation, NoLock);
3804  }
3805 
3806  /* Get a session-level lock on each table. */
3807  foreach(lc, relationLocks)
3808  {
3809  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
3810 
3812  }
3813 
3817 
3818  /*
3819  * Because we don't take a snapshot in this transaction, there's no need
3820  * to set the PROC_IN_SAFE_IC flag here.
3821  */
3822 
3823  /*
3824  * Phase 2 of REINDEX CONCURRENTLY
3825  *
3826  * Build the new indexes in a separate transaction for each index to avoid
3827  * having open transactions for an unnecessary long time. But before
3828  * doing that, wait until no running transactions could have the table of
3829  * the index open with the old list of indexes. See "phase 2" in
3830  * DefineIndex() for more details.
3831  */
3832 
3835  WaitForLockersMultiple(lockTags, ShareLock, true);
3837 
3838  foreach(lc, newIndexIds)
3839  {
3840  ReindexIndexInfo *newidx = lfirst(lc);
3841 
3842  /* Start new transaction for this index's concurrent build */
3844 
3845  /*
3846  * Check for user-requested abort. This is inside a transaction so as
3847  * xact.c does not issue a useless WARNING, and ensures that
3848  * session-level locks are cleaned up on abort.
3849  */
3851 
3852  /* Tell concurrent indexing to ignore us, if index qualifies */
3853  if (newidx->safe)
3855 
3856  /* Set ActiveSnapshot since functions in the indexes may need it */
3858 
3859  /*
3860  * Update progress for the index to build, with the correct parent
3861  * table involved.
3862  */
3865  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD;
3866  progress_vals[2] = newidx->indexId;
3867  progress_vals[3] = newidx->amId;
3868  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3869 
3870  /* Perform concurrent build of new index */
3871  index_concurrently_build(newidx->tableId, newidx->indexId);
3872 
3875  }
3876 
3878 
3879  /*
3880  * Because we don't take a snapshot or Xid in this transaction, there's no
3881  * need to set the PROC_IN_SAFE_IC flag here.
3882  */
3883 
3884  /*
3885  * Phase 3 of REINDEX CONCURRENTLY
3886  *
3887  * During this phase the old indexes catch up with any new tuples that
3888  * were created during the previous phase. See "phase 3" in DefineIndex()
3889  * for more details.
3890  */
3891 
3894  WaitForLockersMultiple(lockTags, ShareLock, true);
3896 
3897  foreach(lc, newIndexIds)
3898  {
3899  ReindexIndexInfo *newidx = lfirst(lc);
3900  TransactionId limitXmin;
3901  Snapshot snapshot;
3902 
3904 
3905  /*
3906  * Check for user-requested abort. This is inside a transaction so as
3907  * xact.c does not issue a useless WARNING, and ensures that
3908  * session-level locks are cleaned up on abort.
3909  */
3911 
3912  /* Tell concurrent indexing to ignore us, if index qualifies */
3913  if (newidx->safe)
3915 
3916  /*
3917  * Take the "reference snapshot" that will be used by validate_index()
3918  * to filter candidate tuples.
3919  */
3921  PushActiveSnapshot(snapshot);
3922 
3923  /*
3924  * Update progress for the index to build, with the correct parent
3925  * table involved.
3926  */
3928  newidx->tableId);
3930  progress_vals[1] = PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN;
3931  progress_vals[2] = newidx->indexId;
3932  progress_vals[3] = newidx->amId;
3933  pgstat_progress_update_multi_param(4, progress_index, progress_vals);
3934 
3935  validate_index(newidx->tableId, newidx->indexId, snapshot);
3936 
3937  /*
3938  * We can now do away with our active snapshot, we still need to save
3939  * the xmin limit to wait for older snapshots.
3940  */
3941  limitXmin = snapshot->xmin;
3942 
3944  UnregisterSnapshot(snapshot);
3945 
3946  /*
3947  * To ensure no deadlocks, we must commit and start yet another
3948  * transaction, and do our wait before any snapshot has been taken in
3949  * it.
3950  */
3953 
3954  /*
3955  * The index is now valid in the sense that it contains all currently
3956  * interesting tuples. But since it might not contain tuples deleted
3957  * just before the reference snap was taken, we have to wait out any
3958  * transactions that might have older snapshots.
3959  *
3960  * Because we don't take a snapshot or Xid in this transaction,
3961  * there's no need to set the PROC_IN_SAFE_IC flag here.
3962  */
3965  WaitForOlderSnapshots(limitXmin, true);
3966 
3968  }
3969 
3970  /*
3971  * Phase 4 of REINDEX CONCURRENTLY
3972  *
3973  * Now that the new indexes have been validated, swap each new index with
3974  * its corresponding old index.
3975  *
3976  * We mark the new indexes as valid and the old indexes as not valid at
3977  * the same time to make sure we only get constraint violations from the
3978  * indexes with the correct names.
3979  */
3980 
3982 
3983  /*
3984  * Because this transaction only does catalog manipulations and doesn't do
3985  * any index operations, we can set the PROC_IN_SAFE_IC flag here
3986  * unconditionally.
3987  */
3989 
3990  forboth(lc, indexIds, lc2, newIndexIds)
3991  {
3992  ReindexIndexInfo *oldidx = lfirst(lc);
3993  ReindexIndexInfo *newidx = lfirst(lc2);
3994  char *oldName;
3995 
3996  /*
3997  * Check for user-requested abort. This is inside a transaction so as
3998  * xact.c does not issue a useless WARNING, and ensures that
3999  * session-level locks are cleaned up on abort.
4000  */
4002 
4003  /* Choose a relation name for old index */
4004  oldName = ChooseRelationName(get_rel_name(oldidx->indexId),
4005  NULL,
4006  "ccold",
4007  get_rel_namespace(oldidx->tableId),
4008  false);
4009 
4010  /*
4011  * Swap old index with the new one. This also marks the new one as
4012  * valid and the old one as not valid.
4013  */
4014  index_concurrently_swap(newidx->indexId, oldidx->indexId, oldName);
4015 
4016  /*
4017  * Invalidate the relcache for the table, so that after this commit
4018  * all sessions will refresh any cached plans that might reference the
4019  * index.
4020  */
4021  CacheInvalidateRelcacheByRelid(oldidx->tableId);
4022 
4023  /*
4024  * CCI here so that subsequent iterations see the oldName in the
4025  * catalog and can choose a nonconflicting name for their oldName.
4026  * Otherwise, this could lead to conflicts if a table has two indexes
4027  * whose names are equal for the first NAMEDATALEN-minus-a-few
4028  * characters.
4029  */
4031  }
4032 
4033  /* Commit this transaction and make index swaps visible */
4036 
4037  /*
4038  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
4039  * real need for that, because we only acquire an Xid after the wait is
4040  * done, and that lasts for a very short period.
4041  */
4042 
4043  /*
4044  * Phase 5 of REINDEX CONCURRENTLY
4045  *
4046  * Mark the old indexes as dead. First we must wait until no running
4047  * transaction could be using the index for a query. See also
4048  * index_drop() for more details.
4049  */
4050 
4054 
4055  foreach(lc, indexIds)
4056  {
4057  ReindexIndexInfo *oldidx = lfirst(lc);
4058 
4059  /*
4060  * Check for user-requested abort. This is inside a transaction so as
4061  * xact.c does not issue a useless WARNING, and ensures that
4062  * session-level locks are cleaned up on abort.
4063  */
4065 
4066  index_concurrently_set_dead(oldidx->tableId, oldidx->indexId);
4067  }
4068 
4069  /* Commit this transaction to make the updates visible. */
4072 
4073  /*
4074  * While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no
4075  * real need for that, because we only acquire an Xid after the wait is
4076  * done, and that lasts for a very short period.
4077  */
4078 
4079  /*
4080  * Phase 6 of REINDEX CONCURRENTLY
4081  *
4082  * Drop the old indexes.
4083  */
4084 
4088 
4090 
4091  {
4093 
4094  foreach(lc, indexIds)
4095  {
4096  ReindexIndexInfo *idx = lfirst(lc);
4097  ObjectAddress object;
4098 
4099  object.classId = RelationRelationId;
4100  object.objectId = idx->indexId;
4101  object.objectSubId = 0;
4102 
4103  add_exact_object_address(&object, objects);
4104  }
4105 
4106  /*
4107  * Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the
4108  * right lock level.
4109  */
4112  }
4113 
4116 
4117  /*
4118  * Finally, release the session-level lock on the table.
4119  */
4120  foreach(lc, relationLocks)
4121  {
4122  LockRelId *lockrelid = (LockRelId *) lfirst(lc);
4123 
4125  }
4126 
4127  /* Start a new transaction to finish process properly */
4129 
4130  /* Log what we did */
4131  if ((params->options & REINDEXOPT_VERBOSE) != 0)
4132  {
4133  if (relkind == RELKIND_INDEX)
4134  ereport(INFO,
4135  (errmsg("index \"%s.%s\" was reindexed",
4136  relationNamespace, relationName),
4137  errdetail("%s.",
4138  pg_rusage_show(&ru0))));
4139  else
4140  {
4141  foreach(lc, newIndexIds)
4142  {
4143  ReindexIndexInfo *idx = lfirst(lc);
4144  Oid indOid = idx->indexId;
4145 
4146  ereport(INFO,
4147  (errmsg("index \"%s.%s\" was reindexed",
4149  get_rel_name(indOid))));
4150  /* Don't show rusage here, since it's not per index. */
4151  }
4152 
4153  ereport(INFO,
4154  (errmsg("table \"%s.%s\" was reindexed",
4155  relationNamespace, relationName),
4156  errdetail("%s.",
4157  pg_rusage_show(&ru0))));
4158  }
4159  }
4160 
4161  MemoryContextDelete(private_context);
4162 
4164 
4165  return true;
4166 }
4167 
4168 /*
4169  * Insert or delete an appropriate pg_inherits tuple to make the given index
4170  * be a partition of the indicated parent index.
4171  *
4172  * This also corrects the pg_depend information for the affected index.
4173  */
4174 void
4175 IndexSetParentIndex(Relation partitionIdx, Oid parentOid)
4176 {
4177  Relation pg_inherits;
4178  ScanKeyData key[2];
4179  SysScanDesc scan;
4180  Oid partRelid = RelationGetRelid(partitionIdx);
4181  HeapTuple tuple;
4182  bool fix_dependencies;
4183 
4184  /* Make sure this is an index */
4185  Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX ||
4186  partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX);
4187 
4188  /*
4189  * Scan pg_inherits for rows linking our index to some parent.
4190  */
4191  pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock);
4192  ScanKeyInit(&key[0],
4193  Anum_pg_inherits_inhrelid,
4194  BTEqualStrategyNumber, F_OIDEQ,
4195  ObjectIdGetDatum(partRelid));
4196  ScanKeyInit(&key[1],
4197  Anum_pg_inherits_inhseqno,
4198  BTEqualStrategyNumber, F_INT4EQ,
4199  Int32GetDatum(1));
4200  scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true,
4201  NULL, 2, key);
4202  tuple = systable_getnext(scan);
4203 
4204  if (!HeapTupleIsValid(tuple))
4205  {
4206  if (parentOid == InvalidOid)
4207  {
4208  /*
4209  * No pg_inherits row, and no parent wanted: nothing to do in this
4210  * case.
4211  */
4212  fix_dependencies = false;
4213  }
4214  else
4215  {
4216  StoreSingleInheritance(partRelid, parentOid, 1);
4217  fix_dependencies = true;
4218  }
4219  }
4220  else
4221  {
4222  Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple);
4223 
4224  if (parentOid == InvalidOid)
4225  {
4226  /*
4227  * There exists a pg_inherits row, which we want to clear; do so.
4228  */
4229  CatalogTupleDelete(pg_inherits, &tuple->t_self);
4230  fix_dependencies = true;
4231  }
4232  else
4233  {
4234  /*
4235  * A pg_inherits row exists. If it's the same we want, then we're
4236  * good; if it differs, that amounts to a corrupt catalog and
4237  * should not happen.
4238  */
4239  if (inhForm->inhparent != parentOid)
4240  {
4241  /* unexpected: we should not get called in this case */
4242  elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u",
4243  inhForm->inhrelid, inhForm->inhparent);
4244  }
4245 
4246  /* already in the right state */
4247  fix_dependencies = false;
4248  }
4249  }
4250 
4251  /* done with pg_inherits */
4252  systable_endscan(scan);
4253  relation_close(pg_inherits, RowExclusiveLock);
4254 
4255  /* set relhassubclass if an index partition has been added to the parent */
4256  if (OidIsValid(parentOid))
4257  SetRelationHasSubclass(parentOid, true);
4258 
4259  /* set relispartition correctly on the partition */
4260  update_relispartition(partRelid, OidIsValid(parentOid));
4261 
4262  if (fix_dependencies)
4263  {
4264  /*
4265  * Insert/delete pg_depend rows. If setting a parent, add PARTITION
4266  * dependencies on the parent index and the table; if removing a
4267  * parent, delete PARTITION dependencies.
4268  */
4269  if (OidIsValid(parentOid))
4270  {
4271  ObjectAddress partIdx;
4272  ObjectAddress parentIdx;
4273  ObjectAddress partitionTbl;
4274 
4275  ObjectAddressSet(partIdx, RelationRelationId, partRelid);
4276  ObjectAddressSet(parentIdx, RelationRelationId, parentOid);
4277  ObjectAddressSet(partitionTbl, RelationRelationId,
4278  partitionIdx->rd_index->indrelid);
4279  recordDependencyOn(&partIdx, &parentIdx,
4281  recordDependencyOn(&partIdx, &partitionTbl,
4283  }
4284  else
4285  {
4286  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4287  RelationRelationId,
4289  deleteDependencyRecordsForClass(RelationRelationId, partRelid,
4290  RelationRelationId,
4292  }
4293 
4294  /* make our updates visible */
4296  }
4297 }
4298 
4299 /*
4300  * Subroutine of IndexSetParentIndex to update the relispartition flag of the
4301  * given index to the given value.
4302  */
4303 static void
4305 {
4306  HeapTuple tup;
4307  Relation classRel;
4308 
4309  classRel = table_open(RelationRelationId, RowExclusiveLock);
4310  tup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relationId));
4311  if (!HeapTupleIsValid(tup))
4312  elog(ERROR, "cache lookup failed for relation %u", relationId);
4313  Assert(((Form_pg_class) GETSTRUCT(tup))->relispartition != newval);
4314  ((Form_pg_class) GETSTRUCT(tup))->relispartition = newval;
4315  CatalogTupleUpdate(classRel, &tup->t_self, tup);
4316  heap_freetuple(tup);
4317  table_close(classRel, RowExclusiveLock);
4318 }
4319 
4320 /*
4321  * Set the PROC_IN_SAFE_IC flag in MyProc->statusFlags.
4322  *
4323  * When doing concurrent index builds, we can set this flag
4324  * to tell other processes concurrently running CREATE
4325  * INDEX CONCURRENTLY or REINDEX CONCURRENTLY to ignore us when
4326  * doing their waits for concurrent snapshots. On one hand it
4327  * avoids pointlessly waiting for a process that's not interesting
4328  * anyway; but more importantly it avoids deadlocks in some cases.
4329  *
4330  * This can be done safely only for indexes that don't execute any
4331  * expressions that could access other tables, so index must not be
4332  * expressional nor partial. Caller is responsible for only calling
4333  * this routine when that assumption holds true.
4334  *
4335  * (The flag is reset automatically at transaction end, so it must be
4336  * set for each transaction.)
4337  */
4338 static inline void
4340 {
4341  /*
4342  * This should only be called before installing xid or xmin in MyProc;
4343  * otherwise, concurrent processes could see an Xmin that moves backwards.
4344  */
4347 
4348  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
4351  LWLockRelease(ProcArrayLock);
4352 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
AclResult
Definition: acl.h:183
@ ACLCHECK_OK
Definition: acl.h:184
@ ACLCHECK_NOT_OWNER
Definition: acl.h:186
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3485
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:4598
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4799
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
bytea *(* amoptions_function)(Datum reloptions, bool validate)
Definition: amapi.h:140
Datum array_eq(PG_FUNCTION_ARGS)
Definition: arrayfuncs.c:3759
void free_attrmap(AttrMap *map)
Definition: attmap.c:57
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:178
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1478
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1432
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1149
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
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
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:428
#define NameStr(name)
Definition: c.h:682
unsigned short uint16
Definition: c.h:441
uint16 bits16
Definition: c.h:450
signed short int16
Definition: c.h:429
#define InvalidSubTransactionId
Definition: c.h:594
uint32 TransactionId
Definition: c.h:588
#define OidIsValid(objectId)
Definition: c.h:711
bool IsToastNamespace(Oid namespaceId)
Definition: catalog.c:202
bool IsSystemRelation(Relation relation)
Definition: catalog.c:75
bool IsCatalogRelationOid(Oid relid)
Definition: catalog.c:122
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition: catalog.c:87
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:365
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:143
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2981
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition: dependency.c:381
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2526
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2581
@ DEPENDENCY_PARTITION_PRI
Definition: dependency.h:36
@ DEPENDENCY_PARTITION_SEC
Definition: dependency.h:37
#define PERFORM_DELETION_CONCURRENT_LOCK
Definition: dependency.h:141
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:136
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1033
int errdetail(const char *fmt,...)
Definition: elog.c:1079
ErrorContextCallback * error_context_stack
Definition: elog.c:94
int errhint(const char *fmt,...)
Definition: elog.c:1193
int errcode(int sqlerrcode)
Definition: elog.c:735
int errmsg(const char *fmt,...)
Definition: elog.c:946
#define errcontext
Definition: elog.h:192
#define WARNING
Definition: elog.h:32
#define DEBUG1
Definition: elog.h:26
#define ERROR
Definition: elog.h:35
#define NOTICE
Definition: elog.h:31
#define INFO
Definition: elog.h:30
#define ereport(elevel,...)
Definition: elog.h:145
const char * name
Definition: encode.c:561
#define palloc_object(type)
Definition: fe_memutils.h:62
#define palloc_array(type, count)
Definition: fe_memutils.h:64
#define palloc0_array(type, count)
Definition: fe_memutils.h:65
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:644
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
bool allowSystemTableMods
Definition: globals.c:124
Oid MyDatabaseTableSpace
Definition: globals.c:91
Oid MyDatabaseId
Definition: globals.c:89
int NewGUCNestLevel(void)
Definition: guc.c:2183
#define newval
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2197
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:3266
@ GUC_ACTION_SAVE
Definition: guc.h:199
@ PGC_S_SESSION
Definition: guc.h:122
@ PGC_USERSET
Definition: guc.h:75
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1299
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
Definition: index.c:3293
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3522
void index_concurrently_set_dead(Oid heapId, Oid indexId)
Definition: index.c:1836
void index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
Definition: index.c:1509
bool CompareIndexInfo(IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, Oid *opfamilies1, Oid *opfamilies2, AttrMap *attmap)
Definition: index.c:2527
void index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
Definition: index.c:3441
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, RelFileNumber relFileNumber, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
Definition: index.c:700
Oid index_concurrently_create_copy(Relation heapRelation, Oid oldIndexId, Oid tablespaceOid, const char *newName)
Definition: index.c:1273
void reindex_index(Oid indexId, bool skip_constraint_checks, char persistence, ReindexParams *params)
Definition: index.c:3547
bool reindex_relation(Oid relid, int flags, ReindexParams *params)
Definition: index.c:3861
void index_check_primary_key(Relation heapRel, IndexInfo *indexInfo, bool is_alter_table, IndexStmt *stmt)
Definition: index.c:206
void index_concurrently_build(Oid heapRelationId, Oid indexRelationId)
Definition: index.c:1443
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2420
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:61
#define INDEX_CREATE_IF_NOT_EXISTS
Definition: index.h:65
#define REINDEX_REL_PROCESS_TOAST
Definition: index.h:155
#define INDEX_CREATE_PARTITIONED
Definition: index.h:66
#define REINDEXOPT_CONCURRENTLY
Definition: index.h:44
#define REINDEXOPT_MISSING_OK
Definition: index.h:43
#define INDEX_CREATE_INVALID
Definition: index.h:67
#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:90
#define REINDEXOPT_REPORT_PROGRESS
Definition: index.h:42
@ INDEX_CREATE_SET_VALID
Definition: index.h:27
#define INDEX_CONSTR_CREATE_INIT_DEFERRED
Definition: index.h:91
#define INDEX_CREATE_CONCURRENT
Definition: index.h:64
#define REINDEXOPT_VERBOSE
Definition: index.h:41
#define REINDEX_REL_CHECK_CONSTRAINTS
Definition: index.h:157
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2331
ObjectAddress DefineIndex(Oid relationId, IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition: indexcmds.c:524
void ExecReindex(ParseState *pstate, ReindexStmt *stmt, bool isTopLevel)
Definition: indexcmds.c:2603
static void set_indexsafe_procflags(void)
Definition: indexcmds.c:4339
static bool ReindexRelationConcurrently(Oid relationOid, ReindexParams *params)
Definition: indexcmds.c:3336
static void reindex_error_callback(void *arg)
Definition: indexcmds.c:3097
void IndexSetParentIndex(Relation partitionIdx, Oid parentOid)
Definition: indexcmds.c:4175
static char * ChooseIndexName(const char *tabname, Oid namespaceId, List *colnames, List *exclusionOpNames, bool primary, bool isconstraint)
Definition: indexcmds.c:2453
static void ReindexMultipleTables(const char *objectName, ReindexObjectType objectKind, ReindexParams *params)
Definition: indexcmds.c:2879
static bool CompareOpclassOptions(Datum *opts1, Datum *opts2, int natts)
Definition: indexcmds.c:352
bool CheckIndexCompatible(Oid oldId, const char *accessMethodName, List *attributeList, List *exclusionOpNames)
Definition: indexcmds.c:170
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2222
static void ReindexIndex(RangeVar *indexRelation, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2698
static bool CheckMutability(Expr *expr)
Definition: indexcmds.c:1705
static void update_relispartition(Oid relationId, bool newval)
Definition: indexcmds.c:4304
static void ReindexMultipleInternal(List *relids, ReindexParams *params)
Definition: indexcmds.c:3212
Oid ResolveOpClass(List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
Definition: indexcmds.c:2137
void WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
Definition: indexcmds.c:419
static void ReindexPartitions(Oid relid, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:3118
struct ReindexErrorInfo ReindexErrorInfo
static Oid ReindexTable(RangeVar *relation, ReindexParams *params, bool isTopLevel)
Definition: indexcmds.c:2821
static void CheckPredicate(Expr *predicate)
Definition: indexcmds.c:1739
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: indexcmds.c:2751
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, Oid ddl_userid, int ddl_sec_context, int *ddl_save_nestlevel)
Definition: indexcmds.c:1766
static List * ChooseIndexColumnNames(List *indexElems)
Definition: indexcmds.c:2542
static char * ChooseIndexNameAddition(List *colnames)
Definition: indexcmds.c:2508
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2417
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1422
int j
Definition: isn.c:74
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
void list_free(List *list)
Definition: list.c:1545
List * lcons_oid(Oid datum, List *list)
Definition: list.c:530
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:597
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:228
void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:908
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:398
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress)
Definition: lmgr.c:986
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:411
bool VirtualXactLock(VirtualTransactionId vxid, bool wait)
Definition: lock.c:4599
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:72
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition: lock.h:184
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:76
#define SetInvalidVirtualTransactionId(vxid)
Definition: lock.h:79
int LOCKMODE
Definition: lockdefs.h:26
#define NoLock
Definition: lockdefs.h:34
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define AccessShareLock
Definition: lockdefs.h:36
#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:2060
bool get_index_isvalid(Oid index_oid)
Definition: lsyscache.c:3547
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1216
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1194
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
bool get_opclass_opfamily_and_input_type(Oid opclass, Oid *opfamily, Oid *opcintype)
Definition: lsyscache.c:1239
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1985
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1934
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1267
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:82
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1910
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:165
bool type_is_collatable(Oid typid)
Definition: lsyscache.c:3039
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2479
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1867
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1491
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1340
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1194
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1802
@ LW_EXCLUSIVE
Definition: lwlock.h:112
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool nulls_not_distinct, bool isready, bool concurrent)
Definition: makefuncs.c:743
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1026
char * pstrdup(const char *in)
Definition: mcxt.c:1483
void pfree(void *pointer)
Definition: mcxt.c:1306
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
void * palloc(Size size)
Definition: mcxt.c:1199
MemoryContext PortalContext
Definition: mcxt.c:139
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:163
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:402
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:305
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:618
Oid GetUserId(void)
Definition: miscinit.c:497
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:625
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:1843
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2936
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2852
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3200
Oid get_collation_oid(List *collname, bool missing_ok)
Definition: namespace.c:3644
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:3086
char * NameListToString(List *names)
Definition: namespace.c:3145
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:239
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
#define copyObject(obj)
Definition: nodes.h:233
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
TYPCATEGORY TypeCategory(Oid type)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
bool IsPreferredType(TYPCATEGORY category, Oid type)
char TYPCATEGORY
Definition: parse_coerce.h:21
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError)
Definition: parse_oper.c:499
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:61
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:62
@ PARTITION_STRATEGY_HASH
Definition: parsenodes.h:837
@ DROP_RESTRICT
Definition: parsenodes.h:1961
@ OBJECT_SCHEMA
Definition: parsenodes.h:1924
@ OBJECT_TABLESPACE
Definition: parsenodes.h:1930
@ OBJECT_INDEX
Definition: parsenodes.h:1908
@ OBJECT_DATABASE
Definition: parsenodes.h:1897
ReindexObjectType
Definition: parsenodes.h:3600
@ REINDEX_OBJECT_DATABASE
Definition: parsenodes.h:3605
@ REINDEX_OBJECT_INDEX
Definition: parsenodes.h:3601
@ REINDEX_OBJECT_SCHEMA
Definition: parsenodes.h:3603
@ REINDEX_OBJECT_SYSTEM
Definition: parsenodes.h:3604
@ REINDEX_OBJECT_TABLE
Definition: parsenodes.h:3602
#define ACL_CREATE
Definition: parsenodes.h:92
@ SORTBY_DESC
Definition: parsenodes.h:55
@ SORTBY_DEFAULT
Definition: parsenodes.h:53
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:72
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
static void fix_dependencies(ArchiveHandle *AH)
void * arg
static int verbose
static char * label
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
NameData relname
Definition: pg_class.h:38
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define INDEX_MAX_KEYS
#define NAMEDATALEN
Oid get_relation_idx_constraint_oid(Oid relationId, Oid indexId)
void ConstraintSetParentConstraint(Oid childConstrId, Oid parentConstrId, Oid childTableId)
bool ConstraintNameExists(const char *conname, Oid namespaceid)
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:350
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:256
void StoreSingleInheritance(Oid relationId, Oid parentOid, int32 seqNumber)
Definition: pg_inherits.c:509
bool has_superclass(Oid relationId)
Definition: pg_inherits.c:378
FormData_pg_inherits * Form_pg_inherits
Definition: pg_inherits.h:45
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
#define NIL
Definition: pg_list.h:66
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:465
#define list_make1_oid(x1)
Definition: pg_list.h:240
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
#define lfirst_oid(lc)
Definition: pg_list.h:172
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:51
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
static char * buf
Definition: pg_test_fsync.c:67
int progress
Definition: pgbench.c:270
static int partitions
Definition: pgbench.c:232
Expr * expression_planner(Expr *expr)
Definition: planner.c:6151
#define sprintf
Definition: port.h:240
#define snprintf
Definition: port.h:238
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static bool DatumGetBool(Datum X)
Definition: postgres.h:438
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
uintptr_t Datum
Definition: postgres.h:412
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:560
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define PROC_IN_SAFE_IC
Definition: proc.h:58
#define PROC_IN_VACUUM
Definition: proc.h:57
#define PROC_IS_AUTOVACUUM
Definition: proc.h:56
VirtualTransactionId * GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids)
Definition: procarray.c:3290
#define PROGRESS_CREATEIDX_PHASE_WAIT_4
Definition: progress.h:98
#define PROGRESS_CREATEIDX_PHASE_BUILD
Definition: progress.h:92
#define PROGRESS_CREATEIDX_PARTITIONS_DONE
Definition: progress.h:87
#define PROGRESS_CREATEIDX_PHASE_WAIT_1
Definition: progress.h:91
#define PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY
Definition: progress.h:109
#define PROGRESS_CREATEIDX_ACCESS_METHOD_OID
Definition: progress.h:81
#define PROGRESS_WAITFOR_DONE
Definition: progress.h:115
#define PROGRESS_CREATEIDX_PHASE_WAIT_3
Definition: progress.h:97
#define PROGRESS_WAITFOR_TOTAL
Definition: progress.h:114
#define PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY
Definition: progress.h:111
#define PROGRESS_CREATEIDX_COMMAND_CREATE
Definition: progress.h:108
#define PROGRESS_WAITFOR_CURRENT_PID
Definition: progress.h:116
#define PROGRESS_CREATEIDX_PHASE_WAIT_2
Definition: progress.h:93
#define PROGRESS_CREATEIDX_PHASE
Definition: progress.h:82
#define PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN
Definition: progress.h:94
#define PROGRESS_CREATEIDX_PHASE_WAIT_5
Definition: progress.h:99
#define PROGRESS_CREATEIDX_INDEX_OID
Definition: progress.h:80
#define PROGRESS_CREATEIDX_PARTITIONS_TOTAL
Definition: progress.h:86
#define PROGRESS_CREATEIDX_COMMAND
Definition: progress.h:79
char * format_operator(Oid operator_oid)
Definition: regproc.c:852
#define RelationGetRelid(relation)
Definition: rel.h:501
#define RelationGetDescr(relation)
Definition: rel.h:527
#define RelationGetRelationName(relation)
Definition: rel.h:535
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:656
#define RelationGetNamespace(relation)
Definition: rel.h:542
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4738
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5769
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5486
bytea * index_reloptions(amoptions_function amoptions, Datum reloptions, bool validate)
Definition: reloptions.c:2055
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1158
#define InvalidRelFileNumber
Definition: relpath.h:26
#define RelFileNumberIsValid(relnumber)
Definition: relpath.h:27
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:26
PGPROC * BackendIdGetProc(int backendID)
Definition: sinvaladt.c:385
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:251
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:871
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:683
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:829
void PopActiveSnapshot(void)
Definition: snapmgr.c:778
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
PGPROC * MyProc
Definition: proc.c:68
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define HTEqualStrategyNumber
Definition: stratnum.h:41
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Definition: attmap.h:35
char * defname
Definition: parsenodes.h:779
int location
Definition: parsenodes.h:783
struct ErrorContextCallback * previous
Definition: elog.h:234
void(* callback)(void *arg)
Definition: elog.h:235
ItemPointerData t_self
Definition: htup.h:65
amoptions_function amoptions
Definition: amapi.h:266
amgettuple_function amgettuple
Definition: amapi.h:273
bool amcanunique
Definition: amapi.h:226
bool amcanmulticol
Definition: amapi.h:228
bool amcanorder
Definition: amapi.h:220
bool amcaninclude
Definition: amapi.h:244
Node * expr
Definition: parsenodes.h:748
SortByDir ordering
Definition: parsenodes.h:753
List * opclassopts
Definition: parsenodes.h:752
char * indexcolname
Definition: parsenodes.h:749
SortByNulls nulls_ordering
Definition: parsenodes.h:754
List * opclass
Definition: parsenodes.h:751
char * name
Definition: parsenodes.h:747
List * collation
Definition: parsenodes.h:750
uint16 * ii_ExclusionStrats
Definition: execnodes.h:185
int ii_NumIndexAttrs
Definition: execnodes.h:176
Datum * ii_OpclassOptions
Definition: execnodes.h:189
Oid * ii_ExclusionOps
Definition: execnodes.h:183
int ii_NumIndexKeyAttrs
Definition: execnodes.h:177
List * ii_Expressions
Definition: execnodes.h:179
Oid * ii_ExclusionProcs
Definition: execnodes.h:184
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:178
List * ii_Predicate
Definition: execnodes.h:181
bool unique
Definition: parsenodes.h:3010
bool reset_default_tblspc
Definition: parsenodes.h:3019
bool deferrable
Definition: parsenodes.h:3014
List * indexParams
Definition: parsenodes.h:2998
Oid indexOid
Definition: parsenodes.h:3005
bool initdeferred
Definition: parsenodes.h:3015
RangeVar * relation
Definition: parsenodes.h:2995
SubTransactionId oldFirstRelfilelocatorSubid
Definition: parsenodes.h:3008
List * options
Definition: parsenodes.h:3001
char * tableSpace
Definition: parsenodes.h:2997
SubTransactionId oldCreateSubid
Definition: parsenodes.h:3007
bool isconstraint
Definition: parsenodes.h:3013
List * excludeOpNames
Definition: parsenodes.h:3003
bool nulls_not_distinct
Definition: parsenodes.h:3011
bool concurrent
Definition: parsenodes.h:3017
char * idxname
Definition: parsenodes.h:2994
Node * whereClause
Definition: parsenodes.h:3002
bool if_not_exists
Definition: parsenodes.h:3018
char * accessMethod
Definition: parsenodes.h:2996
char * idxcomment
Definition: parsenodes.h:3004
RelFileNumber oldNumber
Definition: parsenodes.h:3006
bool primary
Definition: parsenodes.h:3012
List * indexIncludingParams
Definition: parsenodes.h:2999
Definition: lock.h:168
Definition: pg_list.h:52
LockRelId lockRelId
Definition: rel.h:45
Definition: rel.h:38
Oid relId
Definition: rel.h:39
Oid dbId
Definition: rel.h:40
Definition: nodes.h:118
Definition: proc.h:162
TransactionId xmin
Definition: proc.h:178
uint8 statusFlags
Definition: proc.h:233
int pid
Definition: proc.h:186
int pgxactoff
Definition: proc.h:188
TransactionId xid
Definition: proc.h:173
uint8 * statusFlags
Definition: proc.h:377
char * relname
Definition: primnodes.h:77
bool inh
Definition: primnodes.h:80
char * relnamespace
Definition: indexcmds.c:128
ReindexParams params
Definition: indexcmds.c:118
Oid tablespaceOid
Definition: index.h:36
bits32 options
Definition: index.h:35
const char * name
Definition: parsenodes.h:3614
ReindexObjectType kind
Definition: parsenodes.h:3611
RangeVar * relation
Definition: parsenodes.h:3613
List * params
Definition: parsenodes.h:3615
List * rd_indpred
Definition: rel.h:209
LockInfoData rd_lockInfo
Definition: rel.h:113
List * rd_indexprs
Definition: rel.h:208
TupleDesc rd_att
Definition: rel.h:111
Form_pg_index rd_index
Definition: rel.h:188
Oid * rd_opfamily
Definition: rel.h:203
Oid * rd_indcollation
Definition: rel.h:213
Form_pg_class rd_rel
Definition: rel.h:110
TransactionId xmin
Definition: snapshot.h:157
Definition: primnodes.h:205
Definition: c.h:662
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:669
Definition: regguts.h:318
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1195
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1314
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ OPFAMILYOID
Definition: syscache.h:74
@ AMNAME
Definition: syscache.h:35
@ INDEXRELID
Definition: syscache.h:66
@ RELOID
Definition: syscache.h:89
@ CLAOID
Definition: syscache.h:48
@ CLAAMNAMENSP
Definition: syscache.h:47
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:188
Relation try_table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:60
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:993
void RangeVarCallbackOwnsTable(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
Definition: tablecmds.c:16938
void CheckTableNotInUse(Relation rel, const char *stmt)
Definition: tablecmds.c:4004
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3249
#define InvalidTransactionId
Definition: transam.h:31
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:281
void CommandCounterIncrement(void)
Definition: xact.c:1077
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3469
void StartTransactionCommand(void)
Definition: xact.c:2925
void CommitTransactionCommand(void)
Definition: xact.c:3022