Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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