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