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