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