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