Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * index.c
4 : : * code to create and destroy POSTGRES index relations
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/catalog/index.c
12 : : *
13 : : *
14 : : * INTERFACE ROUTINES
15 : : * index_create() - Create a cataloged index relation
16 : : * index_drop() - Removes index relation from catalogs
17 : : * BuildIndexInfo() - Prepare to insert index tuples
18 : : * FormIndexDatum() - Construct datum vector for one index tuple
19 : : *
20 : : *-------------------------------------------------------------------------
21 : : */
22 : : #include "postgres.h"
23 : :
24 : : #include <unistd.h>
25 : :
26 : : #include "access/amapi.h"
27 : : #include "access/attmap.h"
28 : : #include "access/heapam.h"
29 : : #include "access/multixact.h"
30 : : #include "access/relscan.h"
31 : : #include "access/tableam.h"
32 : : #include "access/toast_compression.h"
33 : : #include "access/transam.h"
34 : : #include "access/visibilitymap.h"
35 : : #include "access/xact.h"
36 : : #include "bootstrap/bootstrap.h"
37 : : #include "catalog/binary_upgrade.h"
38 : : #include "catalog/catalog.h"
39 : : #include "catalog/dependency.h"
40 : : #include "catalog/heap.h"
41 : : #include "catalog/index.h"
42 : : #include "catalog/objectaccess.h"
43 : : #include "catalog/partition.h"
44 : : #include "catalog/pg_am.h"
45 : : #include "catalog/pg_collation.h"
46 : : #include "catalog/pg_constraint.h"
47 : : #include "catalog/pg_description.h"
48 : : #include "catalog/pg_inherits.h"
49 : : #include "catalog/pg_opclass.h"
50 : : #include "catalog/pg_operator.h"
51 : : #include "catalog/pg_tablespace.h"
52 : : #include "catalog/pg_trigger.h"
53 : : #include "catalog/pg_type.h"
54 : : #include "catalog/storage.h"
55 : : #include "catalog/storage_xlog.h"
56 : : #include "commands/event_trigger.h"
57 : : #include "commands/progress.h"
58 : : #include "commands/tablecmds.h"
59 : : #include "commands/trigger.h"
60 : : #include "executor/executor.h"
61 : : #include "miscadmin.h"
62 : : #include "nodes/makefuncs.h"
63 : : #include "nodes/nodeFuncs.h"
64 : : #include "optimizer/optimizer.h"
65 : : #include "parser/parser.h"
66 : : #include "pgstat.h"
67 : : #include "postmaster/autovacuum.h"
68 : : #include "rewrite/rewriteManip.h"
69 : : #include "storage/bufmgr.h"
70 : : #include "storage/lmgr.h"
71 : : #include "storage/predicate.h"
72 : : #include "storage/smgr.h"
73 : : #include "utils/builtins.h"
74 : : #include "utils/fmgroids.h"
75 : : #include "utils/guc.h"
76 : : #include "utils/inval.h"
77 : : #include "utils/lsyscache.h"
78 : : #include "utils/memutils.h"
79 : : #include "utils/pg_rusage.h"
80 : : #include "utils/rel.h"
81 : : #include "utils/snapmgr.h"
82 : : #include "utils/syscache.h"
83 : : #include "utils/tuplesort.h"
84 : :
85 : : /* Potentially set by pg_upgrade_support functions */
86 : : Oid binary_upgrade_next_index_pg_class_oid = InvalidOid;
87 : : RelFileNumber binary_upgrade_next_index_pg_class_relfilenumber =
88 : : InvalidRelFileNumber;
89 : :
90 : : /*
91 : : * Pointer-free representation of variables used when reindexing system
92 : : * catalogs; we use this to propagate those values to parallel workers.
93 : : */
94 : : typedef struct
95 : : {
96 : : Oid currentlyReindexedHeap;
97 : : Oid currentlyReindexedIndex;
98 : : int numPendingReindexedIndexes;
99 : : Oid pendingReindexedIndexes[FLEXIBLE_ARRAY_MEMBER];
100 : : } SerializedReindexState;
101 : :
102 : : /* non-export function prototypes */
103 : : static bool relationHasPrimaryKey(Relation rel);
104 : : static TupleDesc ConstructTupleDescriptor(Relation heapRelation,
105 : : const IndexInfo *indexInfo,
106 : : const List *indexColNames,
107 : : Oid accessMethodId,
108 : : const Oid *collationIds,
109 : : const Oid *opclassIds);
110 : : static void InitializeAttributeOids(Relation indexRelation,
111 : : int numatts, Oid indexoid);
112 : : static void AppendAttributeTuples(Relation indexRelation, const Datum *attopts, const NullableDatum *stattargets);
113 : : static void UpdateIndexRelation(Oid indexoid, Oid heapoid,
114 : : Oid parentIndexId,
115 : : const IndexInfo *indexInfo,
116 : : const Oid *collationOids,
117 : : const Oid *opclassOids,
118 : : const int16 *coloptions,
119 : : bool primary,
120 : : bool isexclusion,
121 : : bool immediate,
122 : : bool isvalid,
123 : : bool isready);
124 : : static void index_update_stats(Relation rel,
125 : : bool hasindex,
126 : : double reltuples);
127 : : static void IndexCheckExclusion(Relation heapRelation,
128 : : Relation indexRelation,
129 : : IndexInfo *indexInfo);
130 : : static bool validate_index_callback(ItemPointer itemptr, void *opaque);
131 : : static bool ReindexIsCurrentlyProcessingIndex(Oid indexOid);
132 : : static void SetReindexProcessing(Oid heapOid, Oid indexOid);
133 : : static void ResetReindexProcessing(void);
134 : : static void SetReindexPending(List *indexes);
135 : : static void RemoveReindexPending(Oid indexOid);
136 : :
137 : :
138 : : /*
139 : : * relationHasPrimaryKey
140 : : * See whether an existing relation has a primary key.
141 : : *
142 : : * Caller must have suitable lock on the relation.
143 : : *
144 : : * Note: we intentionally do not check indisvalid here; that's because this
145 : : * is used to enforce the rule that there can be only one indisprimary index,
146 : : * and we want that to be true even if said index is invalid.
147 : : */
148 : : static bool
5693 tgl@sss.pgh.pa.us 149 :CBC 5028 : relationHasPrimaryKey(Relation rel)
150 : : {
151 : 5028 : bool result = false;
152 : : List *indexoidlist;
153 : : ListCell *indexoidscan;
154 : :
155 : : /*
156 : : * Get the list of index OIDs for the table from the relcache, and look up
157 : : * each one in the pg_index syscache until we find one marked primary key
158 : : * (hopefully there isn't more than one such).
159 : : */
160 : 5028 : indexoidlist = RelationGetIndexList(rel);
161 : :
162 [ + + + + : 12148 : foreach(indexoidscan, indexoidlist)
+ + ]
163 : : {
164 : 7144 : Oid indexoid = lfirst_oid(indexoidscan);
165 : : HeapTuple indexTuple;
166 : :
167 : 7144 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid));
3354 168 [ - + ]: 7144 : if (!HeapTupleIsValid(indexTuple)) /* should not happen */
5693 tgl@sss.pgh.pa.us 169 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for index %u", indexoid);
5693 tgl@sss.pgh.pa.us 170 :CBC 7144 : result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
171 : 7144 : ReleaseSysCache(indexTuple);
172 [ + + ]: 7144 : if (result)
173 : 24 : break;
174 : : }
175 : :
176 : 5028 : list_free(indexoidlist);
177 : :
178 : 5028 : return result;
179 : : }
180 : :
181 : : /*
182 : : * index_check_primary_key
183 : : * Apply special checks needed before creating a PRIMARY KEY index
184 : : *
185 : : * This processing used to be in DefineIndex(), but has been split out
186 : : * so that it can be applied during ALTER TABLE ADD PRIMARY KEY USING INDEX.
187 : : *
188 : : * We check for a pre-existing primary key, and that all columns of the index
189 : : * are simple column references (not expressions), and that all those
190 : : * columns are marked NOT NULL. If not, fail.
191 : : *
192 : : * We used to automatically change unmarked columns to NOT NULL here by doing
193 : : * our own local ALTER TABLE command. But that doesn't work well if we're
194 : : * executing one subcommand of an ALTER TABLE: the operations may not get
195 : : * performed in the right order overall. Now we expect that the parser
196 : : * inserted any required ALTER TABLE SET NOT NULL operations before trying
197 : : * to create a primary-key index.
198 : : *
199 : : * Caller had better have at least ShareLock on the table, else the not-null
200 : : * checking isn't trustworthy.
201 : : */
202 : : void
203 : 9394 : index_check_primary_key(Relation heapRel,
204 : : const IndexInfo *indexInfo,
205 : : bool is_alter_table,
206 : : const IndexStmt *stmt)
207 : : {
208 : : int i;
209 : :
210 : : /*
211 : : * If ALTER TABLE or CREATE TABLE .. PARTITION OF, check that there isn't
212 : : * already a PRIMARY KEY. In CREATE TABLE for an ordinary relation, we
213 : : * have faith that the parser rejected multiple pkey clauses; and CREATE
214 : : * INDEX doesn't have a way to say PRIMARY KEY, so it's no problem either.
215 : : */
2884 alvherre@alvh.no-ip. 216 [ + + + + : 14422 : if ((is_alter_table || heapRel->rd_rel->relispartition) &&
+ + ]
5693 tgl@sss.pgh.pa.us 217 : 5028 : relationHasPrimaryKey(heapRel))
218 : : {
219 [ + - ]: 24 : ereport(ERROR,
220 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
221 : : errmsg("multiple primary keys for table \"%s\" are not allowed",
222 : : RelationGetRelationName(heapRel))));
223 : : }
224 : :
225 : : /*
226 : : * Indexes created with NULLS NOT DISTINCT cannot be used for primary key
227 : : * constraints. While there is no direct syntax to reach here, it can be
228 : : * done by creating a separate index and attaching it via ALTER TABLE ..
229 : : * USING INDEX.
230 : : */
1280 dgustafsson@postgres 231 [ + + ]: 9370 : if (indexInfo->ii_NullsNotDistinct)
232 : : {
233 [ + - ]: 4 : ereport(ERROR,
234 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
235 : : errmsg("primary keys cannot use NULLS NOT DISTINCT indexes")));
236 : : }
237 : :
238 : : /*
239 : : * Check that all of the attributes in a primary key are marked as not
240 : : * null. (We don't really expect to see that; it'd mean the parser messed
241 : : * up. But it seems wise to check anyway.)
242 : : */
3064 teodor@sigaev.ru 243 [ + + ]: 20873 : for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
244 : : {
3059 245 : 11507 : AttrNumber attnum = indexInfo->ii_IndexAttrNumbers[i];
246 : : HeapTuple atttuple;
247 : : Form_pg_attribute attform;
248 : :
5693 tgl@sss.pgh.pa.us 249 [ - + ]: 11507 : if (attnum == 0)
5693 tgl@sss.pgh.pa.us 250 [ # # ]:UBC 0 : ereport(ERROR,
251 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
252 : : errmsg("primary keys cannot be expressions")));
253 : :
254 : : /* System attributes are never null, so no need to check */
5693 tgl@sss.pgh.pa.us 255 [ - + ]:CBC 11507 : if (attnum < 0)
5693 tgl@sss.pgh.pa.us 256 :UBC 0 : continue;
257 : :
5693 tgl@sss.pgh.pa.us 258 :CBC 11507 : atttuple = SearchSysCache2(ATTNUM,
259 : : ObjectIdGetDatum(RelationGetRelid(heapRel)),
260 : : Int16GetDatum(attnum));
261 [ - + ]: 11507 : if (!HeapTupleIsValid(atttuple))
5693 tgl@sss.pgh.pa.us 262 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
263 : : attnum, RelationGetRelid(heapRel));
5693 tgl@sss.pgh.pa.us 264 :CBC 11507 : attform = (Form_pg_attribute) GETSTRUCT(atttuple);
265 : :
266 [ - + ]: 11507 : if (!attform->attnotnull)
2683 tgl@sss.pgh.pa.us 267 [ # # ]:UBC 0 : ereport(ERROR,
268 : : (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
269 : : errmsg("primary key column \"%s\" is not marked NOT NULL",
270 : : NameStr(attform->attname))));
271 : :
5693 tgl@sss.pgh.pa.us 272 :CBC 11507 : ReleaseSysCache(atttuple);
273 : : }
274 : 9366 : }
275 : :
276 : : /*
277 : : * ConstructTupleDescriptor
278 : : *
279 : : * Build an index tuple descriptor for a new index
280 : : */
281 : : static TupleDesc
9346 282 : 30538 : ConstructTupleDescriptor(Relation heapRelation,
283 : : const IndexInfo *indexInfo,
284 : : const List *indexColNames,
285 : : Oid accessMethodId,
286 : : const Oid *collationIds,
287 : : const Oid *opclassIds)
288 : : {
8492 289 : 30538 : int numatts = indexInfo->ii_NumIndexAttrs;
3059 teodor@sigaev.ru 290 : 30538 : int numkeyatts = indexInfo->ii_NumIndexKeyAttrs;
6091 tgl@sss.pgh.pa.us 291 : 30538 : ListCell *colnames_item = list_head(indexColNames);
8128 neilc@samurai.com 292 : 30538 : ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
293 : : const IndexAmRoutine *amroutine;
294 : : TupleDesc heapTupDesc;
295 : : TupleDesc indexTupDesc;
296 : : int natts; /* #atts in heap rel --- for error checks */
297 : : int i;
298 : :
299 : : /* We need access to the index AM's API struct */
1100 peter@eisentraut.org 300 : 30538 : amroutine = GetIndexAmRoutineByAmId(accessMethodId, false);
301 : :
302 : : /* ... and to the table's tuple descriptor */
9540 tgl@sss.pgh.pa.us 303 : 30538 : heapTupDesc = RelationGetDescr(heapRelation);
304 : 30538 : natts = RelationGetForm(heapRelation)->relnatts;
305 : :
306 : : /*
307 : : * allocate the new tuple descriptor
308 : : */
2837 andres@anarazel.de 309 : 30538 : indexTupDesc = CreateTemplateTupleDesc(numatts);
310 : :
311 : : /*
312 : : * Fill in the pg_attribute row.
313 : : */
9540 tgl@sss.pgh.pa.us 314 [ + + ]: 80288 : for (i = 0; i < numatts; i++)
315 : : {
3059 teodor@sigaev.ru 316 : 49754 : AttrNumber atnum = indexInfo->ii_IndexAttrNumbers[i];
3294 andres@anarazel.de 317 : 49754 : Form_pg_attribute to = TupleDescAttr(indexTupDesc, i);
318 : : HeapTuple tuple;
319 : : Form_pg_type typeTup;
320 : : Form_pg_opclass opclassTup;
321 : : Oid keyType;
322 : :
2922 peter_e@gmx.net 323 [ + + - + : 49754 : MemSet(to, 0, ATTRIBUTE_FIXED_PART_SIZE);
- - - - -
- ]
324 : 49754 : to->attnum = i + 1;
325 : 49754 : to->attislocal = true;
1100 peter@eisentraut.org 326 [ + + ]: 49754 : to->attcollation = (i < numkeyatts) ? collationIds[i] : InvalidOid;
327 : :
328 : : /*
329 : : * Set the attribute name as specified by caller.
330 : : */
2445 tgl@sss.pgh.pa.us 331 [ - + ]: 49754 : if (colnames_item == NULL) /* shouldn't happen */
2445 tgl@sss.pgh.pa.us 332 [ # # ]:UBC 0 : elog(ERROR, "too few entries in colnames list");
2445 tgl@sss.pgh.pa.us 333 :CBC 49754 : namestrcpy(&to->attname, (const char *) lfirst(colnames_item));
334 : 49754 : colnames_item = lnext(indexColNames, colnames_item);
335 : :
336 : : /*
337 : : * For simple index columns, we copy some pg_attribute fields from the
338 : : * parent relation. For expressions we have to look at the expression
339 : : * result.
340 : : */
8492 341 [ + + ]: 49754 : if (atnum != 0)
342 : : {
343 : : /* Simple index column */
344 : : const FormData_pg_attribute *from;
345 : :
2781 346 [ - + ]: 48993 : Assert(atnum > 0); /* should've been caught above */
347 : :
2837 andres@anarazel.de 348 [ - + ]: 48993 : if (atnum > natts) /* safety check */
2837 andres@anarazel.de 349 [ # # ]:UBC 0 : elog(ERROR, "invalid column number %d", atnum);
2837 andres@anarazel.de 350 :CBC 48993 : from = TupleDescAttr(heapTupDesc,
351 [ - + ]: 48993 : AttrNumberGetAttrOffset(atnum));
352 : :
2922 peter_e@gmx.net 353 : 48993 : to->atttypid = from->atttypid;
354 : 48993 : to->attlen = from->attlen;
355 : 48993 : to->attndims = from->attndims;
356 : 48993 : to->atttypmod = from->atttypmod;
357 : 48993 : to->attbyval = from->attbyval;
358 : 48993 : to->attalign = from->attalign;
1922 tgl@sss.pgh.pa.us 359 : 48993 : to->attstorage = from->attstorage;
1987 rhaas@postgresql.org 360 : 48993 : to->attcompression = from->attcompression;
361 : : }
362 : : else
363 : : {
364 : : /* Expressional index */
365 : : Node *indexkey;
366 : :
8128 neilc@samurai.com 367 [ - + ]: 761 : if (indexpr_item == NULL) /* shouldn't happen */
8492 tgl@sss.pgh.pa.us 368 [ # # ]:UBC 0 : elog(ERROR, "too few entries in indexprs list");
8128 neilc@samurai.com 369 :CBC 761 : indexkey = (Node *) lfirst(indexpr_item);
2600 tgl@sss.pgh.pa.us 370 : 761 : indexpr_item = lnext(indexInfo->ii_Expressions, indexpr_item);
371 : :
372 : : /*
373 : : * Lookup the expression type in pg_type for the type length etc.
374 : : */
8492 375 : 761 : keyType = exprType(indexkey);
6038 rhaas@postgresql.org 376 : 761 : tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
8492 tgl@sss.pgh.pa.us 377 [ - + ]: 761 : if (!HeapTupleIsValid(tuple))
8438 tgl@sss.pgh.pa.us 378 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for type %u", keyType);
8492 tgl@sss.pgh.pa.us 379 :CBC 761 : typeTup = (Form_pg_type) GETSTRUCT(tuple);
380 : :
381 : : /*
382 : : * Assign some of the attributes values. Leave the rest.
383 : : */
384 : 761 : to->atttypid = keyType;
385 : 761 : to->attlen = typeTup->typlen;
1922 386 : 761 : to->atttypmod = exprTypmod(indexkey);
8492 387 : 761 : to->attbyval = typeTup->typbyval;
388 : 761 : to->attalign = typeTup->typalign;
1922 389 : 761 : to->attstorage = typeTup->typstorage;
390 : :
391 : : /*
392 : : * For expression columns, set attcompression invalid, since
393 : : * there's no table column from which to copy the value. Whenever
394 : : * we actually need to compress a value, we'll use whatever the
395 : : * current value of default_toast_compression is at that point in
396 : : * time.
397 : : */
1981 rhaas@postgresql.org 398 : 761 : to->attcompression = InvalidCompressionMethod;
399 : :
8492 tgl@sss.pgh.pa.us 400 : 761 : ReleaseSysCache(tuple);
401 : :
402 : : /*
403 : : * Make sure the expression yields a type that's safe to store in
404 : : * an index. We need this defense because we have index opclasses
405 : : * for pseudo-types such as "record", and the actually stored type
406 : : * had better be safe; eg, a named composite type is okay, an
407 : : * anonymous record type is not. The test is the same as for
408 : : * whether a table column is of a safe type (which is why we
409 : : * needn't check for the non-expression case).
410 : : */
5631 411 : 761 : CheckAttributeType(NameStr(to->attname),
412 : : to->atttypid, to->attcollation,
413 : : NIL, 0);
414 : : }
415 : :
416 : : /*
417 : : * We do not yet have the correct relation OID for the index, so just
418 : : * set it invalid for now. InitializeAttributeOids() will fix it
419 : : * later.
420 : : */
9346 421 : 49750 : to->attrelid = InvalidOid;
422 : :
423 : : /*
424 : : * Check the opclass and index AM to see if either provides a keytype
425 : : * (overriding the attribute type). Opclass (if exists) takes
426 : : * precedence.
427 : : */
3064 teodor@sigaev.ru 428 : 49750 : keyType = amroutine->amkeytype;
429 : :
430 [ + + ]: 49750 : if (i < indexInfo->ii_NumIndexKeyAttrs)
431 : : {
1100 peter@eisentraut.org 432 : 49339 : tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclassIds[i]));
3064 teodor@sigaev.ru 433 [ - + ]: 49339 : if (!HeapTupleIsValid(tuple))
1100 peter@eisentraut.org 434 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for opclass %u", opclassIds[i]);
3064 teodor@sigaev.ru 435 :CBC 49339 : opclassTup = (Form_pg_opclass) GETSTRUCT(tuple);
436 [ + + ]: 49339 : if (OidIsValid(opclassTup->opckeytype))
437 : 3265 : keyType = opclassTup->opckeytype;
438 : :
439 : : /*
440 : : * If keytype is specified as ANYELEMENT, and opcintype is
441 : : * ANYARRAY, then the attribute type must be an array (else it'd
442 : : * not have matched this opclass); use its element type.
443 : : *
444 : : * We could also allow ANYCOMPATIBLE/ANYCOMPATIBLEARRAY here, but
445 : : * there seems no need to do so; there's no reason to declare an
446 : : * opclass as taking ANYCOMPATIBLEARRAY rather than ANYARRAY.
447 : : */
448 [ + + + - ]: 49339 : if (keyType == ANYELEMENTOID && opclassTup->opcintype == ANYARRAYOID)
449 : : {
450 : 137 : keyType = get_base_element_type(to->atttypid);
451 [ - + ]: 137 : if (!OidIsValid(keyType))
3064 teodor@sigaev.ru 452 [ # # ]:UBC 0 : elog(ERROR, "could not get element type of array type %u",
453 : : to->atttypid);
454 : : }
455 : :
3064 teodor@sigaev.ru 456 :CBC 49339 : ReleaseSysCache(tuple);
457 : : }
458 : :
459 : : /*
460 : : * If a key type different from the heap value is specified, update
461 : : * the type-related fields in the index tupdesc.
462 : : */
9136 tgl@sss.pgh.pa.us 463 [ + + + + ]: 49750 : if (OidIsValid(keyType) && keyType != to->atttypid)
464 : : {
6038 rhaas@postgresql.org 465 : 2692 : tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(keyType));
9136 tgl@sss.pgh.pa.us 466 [ - + ]: 2692 : if (!HeapTupleIsValid(tuple))
8438 tgl@sss.pgh.pa.us 467 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for type %u", keyType);
9136 tgl@sss.pgh.pa.us 468 :CBC 2692 : typeTup = (Form_pg_type) GETSTRUCT(tuple);
469 : :
9072 bruce@momjian.us 470 : 2692 : to->atttypid = keyType;
471 : 2692 : to->atttypmod = -1;
472 : 2692 : to->attlen = typeTup->typlen;
473 : 2692 : to->attbyval = typeTup->typbyval;
474 : 2692 : to->attalign = typeTup->typalign;
9136 tgl@sss.pgh.pa.us 475 : 2692 : to->attstorage = typeTup->typstorage;
476 : : /* As above, use the default compression method in this case */
1922 477 : 2692 : to->attcompression = InvalidCompressionMethod;
478 : :
9136 479 : 2692 : ReleaseSysCache(tuple);
480 : : }
481 : :
615 drowley@postgresql.o 482 : 49750 : populate_compact_attribute(indexTupDesc, i);
483 : : }
484 : :
164 485 : 30534 : TupleDescFinalize(indexTupDesc);
486 : :
10581 bruce@momjian.us 487 : 30534 : return indexTupDesc;
488 : : }
489 : :
490 : : /* ----------------------------------------------------------------
491 : : * InitializeAttributeOids
492 : : * ----------------------------------------------------------------
493 : : */
494 : : static void
495 : 30534 : InitializeAttributeOids(Relation indexRelation,
496 : : int numatts,
497 : : Oid indexoid)
498 : : {
499 : : TupleDesc tupleDescriptor;
500 : : int i;
501 : :
10222 502 : 30534 : tupleDescriptor = RelationGetDescr(indexRelation);
503 : :
10581 504 [ + + ]: 80280 : for (i = 0; i < numatts; i += 1)
3294 andres@anarazel.de 505 : 49746 : TupleDescAttr(tupleDescriptor, i)->attrelid = indexoid;
10581 bruce@momjian.us 506 : 30534 : }
507 : :
508 : : /* ----------------------------------------------------------------
509 : : * AppendAttributeTuples
510 : : * ----------------------------------------------------------------
511 : : */
512 : : static void
893 peter@eisentraut.org 513 : 30534 : AppendAttributeTuples(Relation indexRelation, const Datum *attopts, const NullableDatum *stattargets)
514 : : {
515 : : Relation pg_attribute;
516 : : CatalogIndexState indstate;
517 : : TupleDesc indexTupDesc;
518 : 30534 : FormExtraData_pg_attribute *attrs_extra = NULL;
519 : :
520 [ + + ]: 30534 : if (attopts)
521 : : {
522 : 19257 : attrs_extra = palloc0_array(FormExtraData_pg_attribute, indexRelation->rd_att->natts);
523 : :
524 [ + + ]: 46449 : for (int i = 0; i < indexRelation->rd_att->natts; i++)
525 : : {
526 [ + + ]: 27192 : if (attopts[i])
527 : 99 : attrs_extra[i].attoptions.value = attopts[i];
528 : : else
529 : 27093 : attrs_extra[i].attoptions.isnull = true;
530 : :
531 [ + + ]: 27192 : if (stattargets)
532 : 461 : attrs_extra[i].attstattarget = stattargets[i];
533 : : else
534 : 26731 : attrs_extra[i].attstattarget.isnull = true;
535 : : }
536 : : }
537 : :
538 : : /*
539 : : * open the attribute relation and its indexes
540 : : */
2775 andres@anarazel.de 541 : 30534 : pg_attribute = table_open(AttributeRelationId, RowExclusiveLock);
542 : :
8788 tgl@sss.pgh.pa.us 543 : 30534 : indstate = CatalogOpenIndexes(pg_attribute);
544 : :
545 : : /*
546 : : * insert data from new index's tupdesc into pg_attribute
547 : : */
10222 bruce@momjian.us 548 : 30534 : indexTupDesc = RelationGetDescr(indexRelation);
549 : :
893 peter@eisentraut.org 550 : 30534 : InsertPgAttributeTuples(pg_attribute, indexTupDesc, InvalidOid, attrs_extra, indstate);
551 : :
8788 tgl@sss.pgh.pa.us 552 : 30534 : CatalogCloseIndexes(indstate);
553 : :
2775 andres@anarazel.de 554 : 30534 : table_close(pg_attribute, RowExclusiveLock);
10581 bruce@momjian.us 555 : 30534 : }
556 : :
557 : : /* ----------------------------------------------------------------
558 : : * UpdateIndexRelation
559 : : *
560 : : * Construct and insert a new entry in the pg_index catalog
561 : : * ----------------------------------------------------------------
562 : : */
563 : : static void
564 : 30534 : UpdateIndexRelation(Oid indexoid,
565 : : Oid heapoid,
566 : : Oid parentIndexId,
567 : : const IndexInfo *indexInfo,
568 : : const Oid *collationOids,
569 : : const Oid *opclassOids,
570 : : const int16 *coloptions,
571 : : bool primary,
572 : : bool isexclusion,
573 : : bool immediate,
574 : : bool isvalid,
575 : : bool isready)
576 : : {
577 : : int2vector *indkey;
578 : : oidvector *indcollation;
579 : : oidvector *indclass;
580 : : int2vector *indoption;
581 : : Datum exprsDatum;
582 : : Datum predDatum;
583 : : Datum values[Natts_pg_index];
1503 peter@eisentraut.org 584 : 30534 : bool nulls[Natts_pg_index] = {0};
585 : : Relation pg_index;
586 : : HeapTuple tuple;
587 : : int i;
588 : :
589 : : /*
590 : : * Copy the index key, opclass, and indoption info into arrays (should we
591 : : * make the caller pass them like this to start with?)
592 : : */
7821 tgl@sss.pgh.pa.us 593 : 30534 : indkey = buildint2vector(NULL, indexInfo->ii_NumIndexAttrs);
8735 594 [ + + ]: 80280 : for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
3059 teodor@sigaev.ru 595 : 49746 : indkey->values[i] = indexInfo->ii_IndexAttrNumbers[i];
596 : 30534 : indcollation = buildoidvector(collationOids, indexInfo->ii_NumIndexKeyAttrs);
1100 peter@eisentraut.org 597 : 30534 : indclass = buildoidvector(opclassOids, indexInfo->ii_NumIndexKeyAttrs);
3059 teodor@sigaev.ru 598 : 30534 : indoption = buildint2vector(coloptions, indexInfo->ii_NumIndexKeyAttrs);
599 : :
600 : : /*
601 : : * Convert the index expressions (if any) to a text datum
602 : : */
8492 tgl@sss.pgh.pa.us 603 [ + + ]: 30534 : if (indexInfo->ii_Expressions != NIL)
604 : : {
605 : : char *exprsString;
606 : :
607 : 741 : exprsString = nodeToString(indexInfo->ii_Expressions);
6729 608 : 741 : exprsDatum = CStringGetTextDatum(exprsString);
8492 609 : 741 : pfree(exprsString);
610 : : }
611 : : else
612 : 29793 : exprsDatum = (Datum) 0;
613 : :
614 : : /*
615 : : * Convert the index predicate (if any) to a text datum. Note we convert
616 : : * implicit-AND format to normal explicit-AND for storage.
617 : : */
9173 618 [ + + ]: 30534 : if (indexInfo->ii_Predicate != NIL)
619 : : {
620 : : char *predString;
621 : :
8278 622 : 324 : predString = nodeToString(make_ands_explicit(indexInfo->ii_Predicate));
6729 623 : 324 : predDatum = CStringGetTextDatum(predString);
10581 bruce@momjian.us 624 : 324 : pfree(predString);
625 : : }
626 : : else
8492 tgl@sss.pgh.pa.us 627 : 30210 : predDatum = (Datum) 0;
628 : :
629 : :
630 : : /*
631 : : * open the system catalog index relation
632 : : */
2775 andres@anarazel.de 633 : 30534 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
634 : :
635 : : /*
636 : : * Build a pg_index tuple
637 : : */
8735 tgl@sss.pgh.pa.us 638 : 30534 : values[Anum_pg_index_indexrelid - 1] = ObjectIdGetDatum(indexoid);
639 : 30534 : values[Anum_pg_index_indrelid - 1] = ObjectIdGetDatum(heapoid);
8492 640 : 30534 : values[Anum_pg_index_indnatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexAttrs);
3064 teodor@sigaev.ru 641 : 30534 : values[Anum_pg_index_indnkeyatts - 1] = Int16GetDatum(indexInfo->ii_NumIndexKeyAttrs);
8735 tgl@sss.pgh.pa.us 642 : 30534 : values[Anum_pg_index_indisunique - 1] = BoolGetDatum(indexInfo->ii_Unique);
1666 peter@eisentraut.org 643 : 30534 : values[Anum_pg_index_indnullsnotdistinct - 1] = BoolGetDatum(indexInfo->ii_NullsNotDistinct);
8735 tgl@sss.pgh.pa.us 644 : 30534 : values[Anum_pg_index_indisprimary - 1] = BoolGetDatum(primary);
5693 645 : 30534 : values[Anum_pg_index_indisexclusion - 1] = BoolGetDatum(isexclusion);
6238 646 : 30534 : values[Anum_pg_index_indimmediate - 1] = BoolGetDatum(immediate);
8492 647 : 30534 : values[Anum_pg_index_indisclustered - 1] = BoolGetDatum(false);
7307 648 : 30534 : values[Anum_pg_index_indisvalid - 1] = BoolGetDatum(isvalid);
6916 649 : 30534 : values[Anum_pg_index_indcheckxmin - 1] = BoolGetDatum(false);
3142 alvherre@alvh.no-ip. 650 : 30534 : values[Anum_pg_index_indisready - 1] = BoolGetDatum(isready);
5020 tgl@sss.pgh.pa.us 651 : 30534 : values[Anum_pg_index_indislive - 1] = BoolGetDatum(true);
4675 rhaas@postgresql.org 652 : 30534 : values[Anum_pg_index_indisreplident - 1] = BoolGetDatum(false);
7821 tgl@sss.pgh.pa.us 653 : 30534 : values[Anum_pg_index_indkey - 1] = PointerGetDatum(indkey);
5679 peter_e@gmx.net 654 : 30534 : values[Anum_pg_index_indcollation - 1] = PointerGetDatum(indcollation);
7821 tgl@sss.pgh.pa.us 655 : 30534 : values[Anum_pg_index_indclass - 1] = PointerGetDatum(indclass);
7170 656 : 30534 : values[Anum_pg_index_indoption - 1] = PointerGetDatum(indoption);
8492 657 : 30534 : values[Anum_pg_index_indexprs - 1] = exprsDatum;
658 [ + + ]: 30534 : if (exprsDatum == (Datum) 0)
6507 659 : 29793 : nulls[Anum_pg_index_indexprs - 1] = true;
8735 660 : 30534 : values[Anum_pg_index_indpred - 1] = predDatum;
8492 661 [ + + ]: 30534 : if (predDatum == (Datum) 0)
6507 662 : 30210 : nulls[Anum_pg_index_indpred - 1] = true;
663 : :
664 : 30534 : tuple = heap_form_tuple(RelationGetDescr(pg_index), values, nulls);
665 : :
666 : : /*
667 : : * insert the tuple into the pg_index catalog
668 : : */
3495 alvherre@alvh.no-ip. 669 : 30534 : CatalogTupleInsert(pg_index, tuple);
670 : :
671 : : /*
672 : : * close the relation and free the tuple
673 : : */
2775 andres@anarazel.de 674 : 30534 : table_close(pg_index, RowExclusiveLock);
9751 JanWieck@Yahoo.com 675 : 30534 : heap_freetuple(tuple);
10581 bruce@momjian.us 676 : 30534 : }
677 : :
678 : :
679 : : /*
680 : : * index_create
681 : : *
682 : : * heapRelation: table to build index on (suitably locked by caller)
683 : : * indexRelationName: what it say
684 : : * indexRelationId: normally, pass InvalidOid to let this routine
685 : : * generate an OID for the index. During bootstrap this may be
686 : : * nonzero to specify a preselected OID.
687 : : * parentIndexRelid: if creating an index partition, the OID of the
688 : : * parent index; otherwise InvalidOid.
689 : : * parentConstraintId: if creating a constraint on a partition, the OID
690 : : * of the constraint in the parent; otherwise InvalidOid.
691 : : * relFileNumber: normally, pass InvalidRelFileNumber to get new storage.
692 : : * May be nonzero to attach an existing valid build.
693 : : * indexInfo: same info executor uses to insert into the index
694 : : * indexColNames: column names to use for index (List of char *)
695 : : * accessMethodId: OID of index AM to use
696 : : * tableSpaceId: OID of tablespace to use
697 : : * collationIds: array of collation OIDs, one per index column
698 : : * opclassIds: array of index opclass OIDs, one per index column
699 : : * coloptions: array of per-index-column indoption settings
700 : : * reloptions: AM-specific options
701 : : * flags: bitmask that can include any combination of these bits:
702 : : * INDEX_CREATE_IS_PRIMARY
703 : : * the index is a primary key
704 : : * INDEX_CREATE_ADD_CONSTRAINT:
705 : : * invoke index_constraint_create also
706 : : * INDEX_CREATE_SKIP_BUILD:
707 : : * skip the index_build() step for the moment; caller must do it
708 : : * later (typically via reindex_index())
709 : : * INDEX_CREATE_CONCURRENT:
710 : : * do not lock the table against writers. The index will be
711 : : * marked "invalid" and the caller must take additional steps
712 : : * to fix it up.
713 : : * INDEX_CREATE_IF_NOT_EXISTS:
714 : : * do not throw an error if a relation with the same name
715 : : * already exists.
716 : : * INDEX_CREATE_PARTITIONED:
717 : : * create a partitioned index (table must be partitioned)
718 : : * INDEX_CREATE_SUPPRESS_PROGRESS:
719 : : * don't report progress during the index build.
720 : : * INDEX_CREATE_DEFERRABLE:
721 : : * index supports a deferrable constraint, mark it as
722 : : * non-immediate (indimmediate = false).
723 : : *
724 : : * constr_flags: flags passed to index_constraint_create
725 : : * (only if INDEX_CREATE_ADD_CONSTRAINT is set)
726 : : * allow_system_table_mods: allow table to be a system catalog
727 : : * is_internal: if true, post creation hook for new index
728 : : * constraintId: if not NULL, receives OID of created constraint
729 : : *
730 : : * Returns the OID of the created index.
731 : : *
732 : : * NB: Caller is responsible for ensuring the user has USAGE on all types
733 : : * indexInfo->ii_{Expressions,Predicate} depend on.
734 : : */
735 : : Oid
5693 tgl@sss.pgh.pa.us 736 : 30566 : index_create(Relation heapRelation,
737 : : const char *indexRelationName,
738 : : Oid indexRelationId,
739 : : Oid parentIndexRelid,
740 : : Oid parentConstraintId,
741 : : RelFileNumber relFileNumber,
742 : : IndexInfo *indexInfo,
743 : : const List *indexColNames,
744 : : Oid accessMethodId,
745 : : Oid tableSpaceId,
746 : : const Oid *collationIds,
747 : : const Oid *opclassIds,
748 : : const Datum *opclassOptions,
749 : : const int16 *coloptions,
750 : : const NullableDatum *stattargets,
751 : : Datum reloptions,
752 : : uint16 flags,
753 : : uint16 constr_flags,
754 : : bool allow_system_table_mods,
755 : : bool is_internal,
756 : : Oid *constraintId)
757 : : {
758 : 30566 : Oid heapRelationId = RelationGetRelid(heapRelation);
759 : : Relation pg_class;
760 : : Relation indexRelation;
761 : : TupleDesc indexTupDesc;
762 : : bool shared_relation;
763 : : bool mapped_relation;
764 : : bool is_exclusion;
765 : : Oid namespaceId;
766 : : int i;
767 : : char relpersistence;
3208 alvherre@alvh.no-ip. 768 : 30566 : bool isprimary = (flags & INDEX_CREATE_IS_PRIMARY) != 0;
3142 769 : 30566 : bool invalid = (flags & INDEX_CREATE_INVALID) != 0;
3208 770 : 30566 : bool concurrent = (flags & INDEX_CREATE_CONCURRENT) != 0;
3142 771 : 30566 : bool partitioned = (flags & INDEX_CREATE_PARTITIONED) != 0;
144 alvherre@kurilemu.de 772 : 30566 : bool progress = (flags & INDEX_CREATE_SUPPRESS_PROGRESS) == 0;
773 : : char relkind;
774 : : TransactionId relfrozenxid;
775 : : MultiXactId relminmxid;
1513 rhaas@postgresql.org 776 : 30566 : bool create_storage = !RelFileNumberIsValid(relFileNumber);
777 : :
778 : : /* constraint flags can only be set when a constraint is requested */
3208 alvherre@alvh.no-ip. 779 [ + + - + ]: 30566 : Assert((constr_flags == 0) ||
780 : : ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0));
781 : : /* partitioned indexes must never be "built" by themselves */
3142 782 [ + + - + ]: 30566 : Assert(!partitioned || (flags & INDEX_CREATE_SKIP_BUILD));
783 : :
784 [ + + ]: 30566 : relkind = partitioned ? RELKIND_PARTITIONED_INDEX : RELKIND_INDEX;
6107 tgl@sss.pgh.pa.us 785 : 30566 : is_exclusion = (indexInfo->ii_ExclusionOps != NULL);
786 : :
2775 andres@anarazel.de 787 : 30566 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
788 : :
789 : : /*
790 : : * The index will be in the same namespace as its parent table, and is
791 : : * shared across databases if and only if the parent is. Likewise, it
792 : : * will use the relfilenumber map if and only if the parent does; and it
793 : : * inherits the parent's relpersistence.
794 : : */
8920 tgl@sss.pgh.pa.us 795 : 30566 : namespaceId = RelationGetNamespace(heapRelation);
8888 796 : 30566 : shared_relation = heapRelation->rd_rel->relisshared;
6045 797 [ + + + - : 30566 : mapped_relation = RelationIsMapped(heapRelation);
+ - + + +
+ + + ]
5736 rhaas@postgresql.org 798 : 30566 : relpersistence = heapRelation->rd_rel->relpersistence;
799 : :
800 : : /*
801 : : * check parameters
802 : : */
8492 tgl@sss.pgh.pa.us 803 [ - + ]: 30566 : if (indexInfo->ii_NumIndexAttrs < 1)
9148 peter_e@gmx.net 804 [ # # ]:UBC 0 : elog(ERROR, "must index at least one column");
805 : :
8920 tgl@sss.pgh.pa.us 806 [ + + + + ]:CBC 49457 : if (!allow_system_table_mods &&
8903 807 : 18891 : IsSystemRelation(heapRelation) &&
8920 808 [ - + ]: 7425 : IsNormalProcessingMode())
8438 tgl@sss.pgh.pa.us 809 [ # # ]:UBC 0 : ereport(ERROR,
810 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
811 : : errmsg("user-defined indexes on system catalog tables are not supported")));
812 : :
813 : : /*
814 : : * Btree text_pattern_ops uses texteq as the equality operator, which is
815 : : * fine as long as the collation is deterministic; texteq then reduces to
816 : : * bitwise equality and so it is semantically compatible with the other
817 : : * operators and functions in that opclass. But with a nondeterministic
818 : : * collation, texteq could yield results that are incompatible with the
819 : : * actual behavior of the index (which is determined by the opclass's
820 : : * comparison function). We prevent such problems by refusing creation of
821 : : * an index with that opclass and a nondeterministic collation.
822 : : *
823 : : * The same applies to varchar_pattern_ops and bpchar_pattern_ops. If we
824 : : * find more cases, we might decide to create a real mechanism for marking
825 : : * opclasses as incompatible with nondeterminism; but for now, this small
826 : : * hack suffices.
827 : : *
828 : : * Another solution is to use a special operator, not texteq, as the
829 : : * equality opclass member; but that is undesirable because it would
830 : : * prevent index usage in many queries that work fine today.
831 : : */
2532 tgl@sss.pgh.pa.us 832 [ + + ]:CBC 79933 : for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
833 : : {
1100 peter@eisentraut.org 834 : 49375 : Oid collation = collationIds[i];
835 : 49375 : Oid opclass = opclassIds[i];
836 : :
2532 tgl@sss.pgh.pa.us 837 [ + + ]: 49375 : if (collation)
838 : : {
839 [ + + + - ]: 3884 : if ((opclass == TEXT_BTREE_PATTERN_OPS_OID ||
840 [ + + ]: 3835 : opclass == VARCHAR_BTREE_PATTERN_OPS_OID ||
841 : 57 : opclass == BPCHAR_BTREE_PATTERN_OPS_OID) &&
842 [ + + ]: 57 : !get_collation_isdeterministic(collation))
843 : : {
844 : : HeapTuple classtup;
845 : :
846 : 8 : classtup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
847 [ - + ]: 8 : if (!HeapTupleIsValid(classtup))
2532 tgl@sss.pgh.pa.us 848 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for operator class %u", opclass);
2532 tgl@sss.pgh.pa.us 849 [ + - ]:CBC 8 : ereport(ERROR,
850 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
851 : : errmsg("nondeterministic collations are not supported for operator class \"%s\"",
852 : : NameStr(((Form_pg_opclass) GETSTRUCT(classtup))->opcname))));
853 : : ReleaseSysCache(classtup);
854 : : }
855 : : }
856 : : }
857 : :
858 : : /*
859 : : * Concurrent index build on a system catalog is unsafe because we tend to
860 : : * release locks before committing in catalogs.
861 : : */
7307 862 [ + + - + ]: 30999 : if (concurrent &&
2708 peter@eisentraut.org 863 : 441 : IsCatalogRelation(heapRelation))
7307 tgl@sss.pgh.pa.us 864 [ # # ]:UBC 0 : ereport(ERROR,
865 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
866 : : errmsg("concurrent index creation on system catalog tables is not supported")));
867 : :
868 : : /*
869 : : * This case is currently not supported. There's no way to ask for it in
870 : : * the grammar with CREATE INDEX, but it can happen with REINDEX.
871 : : */
6107 tgl@sss.pgh.pa.us 872 [ + + - + ]:CBC 30558 : if (concurrent && is_exclusion)
6107 tgl@sss.pgh.pa.us 873 [ # # ]:UBC 0 : ereport(ERROR,
874 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
875 : : errmsg("concurrent index creation for exclusion constraints is not supported")));
876 : :
877 : : /*
878 : : * We cannot allow indexing a shared relation after initdb (because
879 : : * there's no way to make the entry in other databases' pg_class).
880 : : */
7332 tgl@sss.pgh.pa.us 881 [ + + - + ]:CBC 30558 : if (shared_relation && !IsBootstrapProcessingMode())
8438 tgl@sss.pgh.pa.us 882 [ # # ]:UBC 0 : ereport(ERROR,
883 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
884 : : errmsg("shared indexes cannot be created after initdb")));
885 : :
886 : : /*
887 : : * Shared relations must be in pg_global, too (last-ditch check)
888 : : */
6045 tgl@sss.pgh.pa.us 889 [ + + - + ]:CBC 30558 : if (shared_relation && tableSpaceId != GLOBALTABLESPACE_OID)
6045 tgl@sss.pgh.pa.us 890 [ # # ]:UBC 0 : elog(ERROR, "shared relations must be placed in pg_global tablespace");
891 : :
892 : : /*
893 : : * Check for duplicate name (both as to the index, and as to the
894 : : * associated constraint if any). Such cases would fail on the relevant
895 : : * catalogs' unique indexes anyway, but we prefer to give a friendlier
896 : : * error message.
897 : : */
8915 tgl@sss.pgh.pa.us 898 [ + + ]:CBC 30558 : if (get_relname_relid(indexRelationName, namespaceId))
899 : : {
3208 alvherre@alvh.no-ip. 900 [ + + ]: 16 : if ((flags & INDEX_CREATE_IF_NOT_EXISTS) != 0)
901 : : {
4312 fujii@postgresql.org 902 [ + - ]: 12 : ereport(NOTICE,
903 : : (errcode(ERRCODE_DUPLICATE_TABLE),
904 : : errmsg("relation \"%s\" already exists, skipping",
905 : : indexRelationName)));
2775 andres@anarazel.de 906 : 12 : table_close(pg_class, RowExclusiveLock);
4312 fujii@postgresql.org 907 : 12 : return InvalidOid;
908 : : }
909 : :
8438 tgl@sss.pgh.pa.us 910 [ + - ]: 4 : ereport(ERROR,
911 : : (errcode(ERRCODE_DUPLICATE_TABLE),
912 : : errmsg("relation \"%s\" already exists",
913 : : indexRelationName)));
914 : : }
915 : :
2914 916 [ + + + + ]: 37146 : if ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0 &&
917 : 6604 : ConstraintNameIsUsed(CONSTRAINT_RELATION, heapRelationId,
918 : : indexRelationName))
919 : : {
920 : : /*
921 : : * INDEX_CREATE_IF_NOT_EXISTS does not apply here, since the
922 : : * conflicting constraint is not an index.
923 : : */
924 [ + - ]: 4 : ereport(ERROR,
925 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
926 : : errmsg("constraint \"%s\" for relation \"%s\" already exists",
927 : : indexRelationName, RelationGetRelationName(heapRelation))));
928 : : }
929 : :
930 : : /*
931 : : * construct tuple descriptor for index tuples
932 : : */
8492 933 : 30538 : indexTupDesc = ConstructTupleDescriptor(heapRelation,
934 : : indexInfo,
935 : : indexColNames,
936 : : accessMethodId,
937 : : collationIds,
938 : : opclassIds);
939 : :
940 : : /*
941 : : * Allocate an OID for the index, unless we were told what to use.
942 : : *
943 : : * The OID will be the relfilenumber as well, so make sure it doesn't
944 : : * collide with either pg_class OIDs or existing physical files.
945 : : */
6049 946 [ + + ]: 30534 : if (!OidIsValid(indexRelationId))
947 : : {
948 : : /* Use binary-upgrade override for pg_class.oid and relfilenumber */
4385 bruce@momjian.us 949 [ + + ]: 21074 : if (IsBinaryUpgrade)
950 : : {
951 [ - + ]: 611 : if (!OidIsValid(binary_upgrade_next_index_pg_class_oid))
4385 bruce@momjian.us 952 [ # # ]:UBC 0 : ereport(ERROR,
953 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
954 : : errmsg("pg_class index OID value not set when in binary upgrade mode")));
955 : :
5711 bruce@momjian.us 956 :CBC 611 : indexRelationId = binary_upgrade_next_index_pg_class_oid;
957 : 611 : binary_upgrade_next_index_pg_class_oid = InvalidOid;
958 : :
959 : : /* Override the index relfilenumber */
1683 rhaas@postgresql.org 960 [ + + ]: 611 : if ((relkind == RELKIND_INDEX) &&
1513 961 [ - + ]: 582 : (!RelFileNumberIsValid(binary_upgrade_next_index_pg_class_relfilenumber)))
1683 rhaas@postgresql.org 962 [ # # ]:UBC 0 : ereport(ERROR,
963 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
964 : : errmsg("index relfilenumber value not set when in binary upgrade mode")));
1513 rhaas@postgresql.org 965 :CBC 611 : relFileNumber = binary_upgrade_next_index_pg_class_relfilenumber;
966 : 611 : binary_upgrade_next_index_pg_class_relfilenumber = InvalidRelFileNumber;
967 : :
968 : : /*
969 : : * Note that we want create_storage = true for binary upgrade. The
970 : : * storage we create here will be replaced later, but we need to
971 : : * have something on disk in the meanwhile.
972 : : */
1683 973 [ - + ]: 611 : Assert(create_storage);
974 : : }
975 : : else
976 : : {
977 : : indexRelationId =
1429 978 : 20463 : GetNewRelFileNumber(tableSpaceId, pg_class, relpersistence);
979 : : }
980 : : }
981 : :
982 : : /*
983 : : * create the index relation's relcache entry and, if necessary, the
984 : : * physical disk file. (If we fail further down, it's the smgr's
985 : : * responsibility to remove the disk file again, if any.)
986 : : */
8920 tgl@sss.pgh.pa.us 987 : 30534 : indexRelation = heap_create(indexRelationName,
988 : : namespaceId,
989 : : tableSpaceId,
990 : : indexRelationId,
991 : : relFileNumber,
992 : : accessMethodId,
993 : : indexTupDesc,
994 : : relkind,
995 : : relpersistence,
996 : : shared_relation,
997 : : mapped_relation,
998 : : allow_system_table_mods,
999 : : &relfrozenxid,
1000 : : &relminmxid,
1001 : : create_storage);
1002 : :
2709 andres@anarazel.de 1003 [ - + ]: 30534 : Assert(relfrozenxid == InvalidTransactionId);
1004 [ - + ]: 30534 : Assert(relminmxid == InvalidMultiXactId);
7685 tgl@sss.pgh.pa.us 1005 [ - + ]: 30534 : Assert(indexRelationId == RelationGetRelid(indexRelation));
1006 : :
1007 : : /*
1008 : : * Obtain exclusive lock on it. Although no other transactions can see it
1009 : : * until we commit, this prevents deadlock-risk complaints from lock
1010 : : * manager in cases such as CLUSTER.
1011 : : */
9423 1012 : 30534 : LockRelation(indexRelation, AccessExclusiveLock);
1013 : :
1014 : : /*
1015 : : * Fill in fields of the index's pg_class entry that are not set correctly
1016 : : * by heap_create.
1017 : : *
1018 : : * XXX should have a cleaner way to create cataloged indexes
1019 : : */
7671 1020 : 30534 : indexRelation->rd_rel->relowner = heapRelation->rd_rel->relowner;
1100 peter@eisentraut.org 1021 : 30534 : indexRelation->rd_rel->relam = accessMethodId;
3060 alvherre@alvh.no-ip. 1022 : 30534 : indexRelation->rd_rel->relispartition = OidIsValid(parentIndexRelid);
1023 : :
1024 : : /*
1025 : : * store index's pg_class entry
1026 : : */
7360 tgl@sss.pgh.pa.us 1027 : 30534 : InsertPgClassTuple(pg_class, indexRelation,
1028 : : RelationGetRelid(indexRelation),
1029 : : (Datum) 0,
1030 : : reloptions);
1031 : :
1032 : : /* done with pg_class */
2775 andres@anarazel.de 1033 : 30534 : table_close(pg_class, RowExclusiveLock);
1034 : :
1035 : : /*
1036 : : * now update the object id's of all the attribute tuple forms in the
1037 : : * index relation's tuple descriptor
1038 : : */
9540 tgl@sss.pgh.pa.us 1039 : 30534 : InitializeAttributeOids(indexRelation,
1040 : : indexInfo->ii_NumIndexAttrs,
1041 : : indexRelationId);
1042 : :
1043 : : /*
1044 : : * append ATTRIBUTE tuples for the index
1045 : : */
893 peter@eisentraut.org 1046 : 30534 : AppendAttributeTuples(indexRelation, opclassOptions, stattargets);
1047 : :
1048 : : /* ----------------
1049 : : * update pg_index
1050 : : * (append INDEX tuple)
1051 : : *
1052 : : * Note that this stows away a representation of "predicate".
1053 : : * (Or, could define a rule to maintain the predicate) --Nels, Feb '92
1054 : : * ----------------
1055 : : */
3142 alvherre@alvh.no-ip. 1056 : 91602 : UpdateIndexRelation(indexRelationId, heapRelationId, parentIndexRelid,
1057 : : indexInfo,
1058 : : collationIds, opclassIds, coloptions,
1059 : : isprimary, is_exclusion,
30 michael@paquier.xyz 1060 : 30534 : (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) == 0 &&
1061 [ + + ]: 30442 : (flags & INDEX_CREATE_DEFERRABLE) == 0,
3142 alvherre@alvh.no-ip. 1062 [ + + ]: 30534 : !concurrent && !invalid,
6238 tgl@sss.pgh.pa.us 1063 [ + + + + ]: 91602 : !concurrent);
1064 : :
1065 : : /*
1066 : : * Register relcache invalidation on the indexes' heap relation, to
1067 : : * maintain consistency of its index list
1068 : : */
2946 pg@bowt.ie 1069 : 30534 : CacheInvalidateRelcache(heapRelation);
1070 : :
1071 : : /* update pg_inherits and the parent's relhassubclass, if needed */
3142 alvherre@alvh.no-ip. 1072 [ + + ]: 30534 : if (OidIsValid(parentIndexRelid))
1073 : : {
1074 : 1628 : StoreSingleInheritance(indexRelationId, parentIndexRelid, 1);
791 noah@leadboat.com 1075 : 1628 : LockRelationOid(parentIndexRelid, ShareUpdateExclusiveLock);
2866 michael@paquier.xyz 1076 : 1628 : SetRelationHasSubclass(parentIndexRelid, true);
1077 : : }
1078 : :
1079 : : /*
1080 : : * Register constraint and dependencies for the index.
1081 : : *
1082 : : * If the index is from a CONSTRAINT clause, construct a pg_constraint
1083 : : * entry. The index will be linked to the constraint, which in turn is
1084 : : * linked to the table. If it's not a CONSTRAINT, we need to make a
1085 : : * dependency directly on the table.
1086 : : *
1087 : : * We don't need a dependency on the namespace, because there'll be an
1088 : : * indirect dependency via our parent table.
1089 : : *
1090 : : * During bootstrap we can't register any dependencies, and we don't try
1091 : : * to make a constraint either.
1092 : : */
8812 tgl@sss.pgh.pa.us 1093 [ + + ]: 30534 : if (!IsBootstrapProcessingMode())
1094 : : {
1095 : : ObjectAddress myself,
1096 : : referenced;
1097 : : ObjectAddresses *addrs;
1098 : :
2248 michael@paquier.xyz 1099 : 21074 : ObjectAddressSet(myself, RelationRelationId, indexRelationId);
1100 : :
3208 alvherre@alvh.no-ip. 1101 [ + + ]: 21074 : if ((flags & INDEX_CREATE_ADD_CONSTRAINT) != 0)
1102 : : {
1103 : : char constraintType;
1104 : : ObjectAddress localaddr;
1105 : :
7414 tgl@sss.pgh.pa.us 1106 [ + + ]: 6600 : if (isprimary)
8812 1107 : 5755 : constraintType = CONSTRAINT_PRIMARY;
1108 [ + + ]: 845 : else if (indexInfo->ii_Unique)
1109 : 699 : constraintType = CONSTRAINT_UNIQUE;
6107 1110 [ + - ]: 146 : else if (is_exclusion)
1111 : 146 : constraintType = CONSTRAINT_EXCLUSION;
1112 : : else
1113 : : {
6107 tgl@sss.pgh.pa.us 1114 [ # # ]:UBC 0 : elog(ERROR, "constraint must be PRIMARY, UNIQUE or EXCLUDE");
1115 : : constraintType = 0; /* keep compiler quiet */
1116 : : }
1117 : :
3111 alvherre@alvh.no-ip. 1118 :CBC 6600 : localaddr = index_constraint_create(heapRelation,
1119 : : indexRelationId,
1120 : : parentConstraintId,
1121 : : indexInfo,
1122 : : indexRelationName,
1123 : : constraintType,
1124 : : constr_flags,
1125 : : allow_system_table_mods,
1126 : : is_internal);
1127 [ + - ]: 6600 : if (constraintId)
1128 : 6600 : *constraintId = localaddr.objectId;
1129 : : }
1130 : : else
1131 : : {
6860 bruce@momjian.us 1132 : 14474 : bool have_simple_col = false;
1133 : :
2182 michael@paquier.xyz 1134 : 14474 : addrs = new_object_addresses();
1135 : :
1136 : : /* Create auto dependencies on simply-referenced columns */
8492 tgl@sss.pgh.pa.us 1137 [ + + ]: 39800 : for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
1138 : : {
3059 teodor@sigaev.ru 1139 [ + + ]: 25326 : if (indexInfo->ii_IndexAttrNumbers[i] != 0)
1140 : : {
2248 michael@paquier.xyz 1141 : 24591 : ObjectAddressSubSet(referenced, RelationRelationId,
1142 : : heapRelationId,
1143 : : indexInfo->ii_IndexAttrNumbers[i]);
2182 1144 : 24591 : add_exact_object_address(&referenced, addrs);
6867 tgl@sss.pgh.pa.us 1145 : 24591 : have_simple_col = true;
1146 : : }
1147 : : }
1148 : :
1149 : : /*
1150 : : * If there are no simply-referenced columns, give the index an
1151 : : * auto dependency on the whole table. In most cases, this will
1152 : : * be redundant, but it might not be if the index expressions and
1153 : : * predicate contain no Vars or only whole-row Vars.
1154 : : */
5777 1155 [ + + ]: 14474 : if (!have_simple_col)
1156 : : {
2248 michael@paquier.xyz 1157 : 612 : ObjectAddressSet(referenced, RelationRelationId,
1158 : : heapRelationId);
2182 1159 : 612 : add_exact_object_address(&referenced, addrs);
1160 : : }
1161 : :
1162 : 14474 : record_object_address_dependencies(&myself, addrs, DEPENDENCY_AUTO);
1163 : 14474 : free_object_addresses(addrs);
1164 : : }
1165 : :
1166 : : /*
1167 : : * If this is an index partition, create partition dependencies on
1168 : : * both the parent index and the table. (Note: these must be *in
1169 : : * addition to*, not instead of, all other dependencies. Otherwise
1170 : : * we'll be short some dependencies after DETACH PARTITION.)
1171 : : */
3142 alvherre@alvh.no-ip. 1172 [ + + ]: 21074 : if (OidIsValid(parentIndexRelid))
1173 : : {
2248 michael@paquier.xyz 1174 : 1628 : ObjectAddressSet(referenced, RelationRelationId, parentIndexRelid);
2754 tgl@sss.pgh.pa.us 1175 : 1628 : recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
1176 : :
2248 michael@paquier.xyz 1177 : 1628 : ObjectAddressSet(referenced, RelationRelationId, heapRelationId);
2754 tgl@sss.pgh.pa.us 1178 : 1628 : recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
1179 : : }
1180 : :
1181 : : /* placeholder for normal dependencies */
1938 tmunro@postgresql.or 1182 : 21074 : addrs = new_object_addresses();
1183 : :
1184 : : /* Store dependency on collations */
1185 : :
1186 : : /* The default collation is pinned, so don't bother recording it */
1187 [ + + ]: 54184 : for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1188 : : {
1100 peter@eisentraut.org 1189 [ + + + + ]: 33110 : if (OidIsValid(collationIds[i]) && collationIds[i] != DEFAULT_COLLATION_OID)
1190 : : {
1191 : 248 : ObjectAddressSet(referenced, CollationRelationId, collationIds[i]);
1938 tmunro@postgresql.or 1192 : 248 : add_exact_object_address(&referenced, addrs);
1193 : : }
1194 : : }
1195 : :
1196 : : /* Store dependency on operator classes */
3064 teodor@sigaev.ru 1197 [ + + ]: 54184 : for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1198 : : {
1100 peter@eisentraut.org 1199 : 33110 : ObjectAddressSet(referenced, OperatorClassRelationId, opclassIds[i]);
2182 michael@paquier.xyz 1200 : 33110 : add_exact_object_address(&referenced, addrs);
1201 : : }
1202 : :
1203 : 21074 : record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
1204 : 21074 : free_object_addresses(addrs);
1205 : :
1206 : : /* Store dependencies on anything mentioned in index expressions */
8492 tgl@sss.pgh.pa.us 1207 [ + + ]: 21074 : if (indexInfo->ii_Expressions)
1208 : : {
1209 : 741 : recordDependencyOnSingleRelExpr(&myself,
3354 1210 : 741 : (Node *) indexInfo->ii_Expressions,
1211 : : heapRelationId,
1212 : : DEPENDENCY_NORMAL,
1213 : : DEPENDENCY_AUTO, false);
1214 : : }
1215 : :
1216 : : /* Store dependencies on anything mentioned in predicate */
8492 1217 [ + + ]: 21074 : if (indexInfo->ii_Predicate)
1218 : : {
1219 : 324 : recordDependencyOnSingleRelExpr(&myself,
7621 bruce@momjian.us 1220 : 324 : (Node *) indexInfo->ii_Predicate,
1221 : : heapRelationId,
1222 : : DEPENDENCY_NORMAL,
1223 : : DEPENDENCY_AUTO, false);
1224 : : }
1225 : : }
1226 : : else
1227 : : {
1228 : : /* Bootstrap mode - assert we weren't asked for constraint support */
3208 alvherre@alvh.no-ip. 1229 [ - + ]: 9460 : Assert((flags & INDEX_CREATE_ADD_CONSTRAINT) == 0);
1230 : : }
1231 : :
1232 : : /* Post creation hook for new index */
4922 rhaas@postgresql.org 1233 [ + + ]: 30534 : InvokeObjectPostCreateHookArg(RelationRelationId,
1234 : : indexRelationId, 0, is_internal);
1235 : :
1236 : : /*
1237 : : * Advance the command counter so that we can see the newly-entered
1238 : : * catalog tuples for the index.
1239 : : */
9091 tgl@sss.pgh.pa.us 1240 : 30534 : CommandCounterIncrement();
1241 : :
1242 : : /*
1243 : : * In bootstrap mode, we have to fill in the index strategy structure with
1244 : : * information from the catalogs. If we aren't bootstrapping, then the
1245 : : * relcache entry has already been rebuilt thanks to sinval update during
1246 : : * CommandCounterIncrement.
1247 : : */
7733 1248 [ + + ]: 30530 : if (IsBootstrapProcessingMode())
1249 : 9460 : RelationInitIndexAccessInfo(indexRelation);
1250 : : else
1251 [ - + ]: 21070 : Assert(indexRelation->rd_indexcxt != NULL);
1252 : :
3064 teodor@sigaev.ru 1253 : 30530 : indexRelation->rd_index->indnkeyatts = indexInfo->ii_NumIndexKeyAttrs;
1254 : :
1255 : : /* Validate opclass-specific options */
1059 peter@eisentraut.org 1256 [ + + ]: 30530 : if (opclassOptions)
2341 akorotkov@postgresql 1257 [ + + ]: 45976 : for (i = 0; i < indexInfo->ii_NumIndexKeyAttrs; i++)
1258 : 26777 : (void) index_opclass_options(indexRelation, i + 1,
1059 peter@eisentraut.org 1259 : 26777 : opclassOptions[i],
1260 : : true);
1261 : :
1262 : : /*
1263 : : * If this is bootstrap (initdb) time, then we don't actually fill in the
1264 : : * index yet. We'll be creating more indexes and classes later, so we
1265 : : * delay filling them in until just before we're done with bootstrapping.
1266 : : * Similarly, if the caller specified to skip the build then filling the
1267 : : * index is delayed till later (ALTER TABLE can save work in some cases
1268 : : * with this). Otherwise, we call the AM routine that constructs the
1269 : : * index.
1270 : : */
10581 bruce@momjian.us 1271 [ + + ]: 30476 : if (IsBootstrapProcessingMode())
1272 : : {
7685 tgl@sss.pgh.pa.us 1273 : 9460 : index_register(heapRelationId, indexRelationId, indexInfo);
1274 : : }
3208 alvherre@alvh.no-ip. 1275 [ + + ]: 21016 : else if ((flags & INDEX_CREATE_SKIP_BUILD) != 0)
1276 : : {
1277 : : /*
1278 : : * Caller is responsible for filling the index later on. However,
1279 : : * we'd better make sure that the heap relation is correctly marked as
1280 : : * having an index.
1281 : : */
7414 tgl@sss.pgh.pa.us 1282 : 2048 : index_update_stats(heapRelation,
1283 : : true,
1284 : : -1.0);
1285 : : /* Make the above update visible */
1286 : 2048 : CommandCounterIncrement();
1287 : : }
1288 : : else
1289 : : {
144 alvherre@kurilemu.de 1290 : 18968 : index_build(heapRelation, indexRelation, indexInfo, false, true,
1291 : : progress);
1292 : : }
1293 : :
1294 : : /*
1295 : : * Close the index; but we keep the lock that we acquired above until end
1296 : : * of transaction. Closing the heap is caller's responsibility.
1297 : : */
7332 tgl@sss.pgh.pa.us 1298 : 30404 : index_close(indexRelation, NoLock);
1299 : :
7685 1300 : 30404 : return indexRelationId;
1301 : : }
1302 : :
1303 : : /*
1304 : : * index_create_copy
1305 : : *
1306 : : * Create an index based on the definition of the one provided by caller. The
1307 : : * index is inserted into catalogs. 'flags' are passed directly to
1308 : : * index_create.
1309 : : *
1310 : : * "tablespaceOid" is the tablespace to use for this index.
1311 : : */
1312 : : Oid
144 alvherre@kurilemu.de 1313 : 342 : index_create_copy(Relation heapRelation, uint16 flags,
1314 : : Oid oldIndexId, Oid tablespaceOid, const char *newName)
1315 : : {
1316 : : Relation indexRelation;
1317 : : IndexInfo *oldInfo,
1318 : : *newInfo;
2708 peter@eisentraut.org 1319 : 342 : Oid newIndexId = InvalidOid;
144 alvherre@kurilemu.de 1320 : 342 : bool concurrently = (flags & INDEX_CREATE_CONCURRENT) != 0;
1321 : : HeapTuple indexTuple,
1322 : : classTuple;
1323 : : Datum indclassDatum,
1324 : : colOptionDatum,
1325 : : reloptionsDatum;
1326 : : Datum *opclassOptions;
1327 : : oidvector *indclass;
1328 : : int2vector *indcoloptions;
1329 : : NullableDatum *stattargets;
1330 : : bool isnull;
2708 peter@eisentraut.org 1331 : 342 : List *indexColNames = NIL;
2586 michael@paquier.xyz 1332 : 342 : List *indexExprs = NIL;
1333 : 342 : List *indexPreds = NIL;
1334 : : Form_pg_index indexForm;
1335 : :
2708 peter@eisentraut.org 1336 : 342 : indexRelation = index_open(oldIndexId, RowExclusiveLock);
1337 : :
1338 : : /* The new index needs some information from the old index */
2586 michael@paquier.xyz 1339 : 342 : oldInfo = BuildIndexInfo(indexRelation);
1340 : :
1341 : : /*
1342 : : * Concurrent build of an index with exclusion constraints is not
1343 : : * supported.
1344 : : */
145 alvherre@kurilemu.de 1345 [ + + + + ]: 342 : if (oldInfo->ii_ExclusionOps != NULL && concurrently)
2586 michael@paquier.xyz 1346 [ + - ]: 4 : ereport(ERROR,
1347 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1348 : : errmsg("concurrent index creation for exclusion constraints is not supported")));
1349 : :
1350 : : /* Get the array of class and column options IDs from index info */
2708 peter@eisentraut.org 1351 : 338 : indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId));
1352 [ - + ]: 338 : if (!HeapTupleIsValid(indexTuple))
2708 peter@eisentraut.org 1353 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for index %u", oldIndexId);
1354 : :
30 michael@paquier.xyz 1355 :CBC 338 : indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
1356 : :
1357 : : /* Old index is deferrable, do the same for the new index */
1358 [ + + ]: 338 : if (!indexForm->indimmediate)
1359 : 1 : flags |= INDEX_CREATE_DEFERRABLE;
1360 : :
1251 dgustafsson@postgres 1361 : 338 : indclassDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
1362 : : Anum_pg_index_indclass);
2708 peter@eisentraut.org 1363 : 338 : indclass = (oidvector *) DatumGetPointer(indclassDatum);
1364 : :
1251 dgustafsson@postgres 1365 : 338 : colOptionDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
1366 : : Anum_pg_index_indoption);
2708 peter@eisentraut.org 1367 : 338 : indcoloptions = (int2vector *) DatumGetPointer(colOptionDatum);
1368 : :
1369 : : /* Fetch reloptions of index if any */
1134 michael@paquier.xyz 1370 : 338 : classTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(oldIndexId));
2708 peter@eisentraut.org 1371 [ - + ]: 338 : if (!HeapTupleIsValid(classTuple))
2708 peter@eisentraut.org 1372 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for relation %u", oldIndexId);
1059 peter@eisentraut.org 1373 :CBC 338 : reloptionsDatum = SysCacheGetAttr(RELOID, classTuple,
1374 : : Anum_pg_class_reloptions, &isnull);
1375 : :
1376 : : /*
1377 : : * Fetch the list of expressions and predicates directly from the
1378 : : * catalogs. This cannot rely on the information from IndexInfo of the
1379 : : * old index as these have been flattened for the planner.
1380 : : */
2586 michael@paquier.xyz 1381 [ + + ]: 338 : if (oldInfo->ii_Expressions != NIL)
1382 : : {
1383 : : Datum exprDatum;
1384 : : char *exprString;
1385 : :
1251 dgustafsson@postgres 1386 : 34 : exprDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
1387 : : Anum_pg_index_indexprs);
2586 michael@paquier.xyz 1388 : 34 : exprString = TextDatumGetCString(exprDatum);
1389 : 34 : indexExprs = (List *) stringToNode(exprString);
1390 : 34 : pfree(exprString);
1391 : : }
1392 [ + + ]: 338 : if (oldInfo->ii_Predicate != NIL)
1393 : : {
1394 : : Datum predDatum;
1395 : : char *predString;
1396 : :
1251 dgustafsson@postgres 1397 : 18 : predDatum = SysCacheGetAttrNotNull(INDEXRELID, indexTuple,
1398 : : Anum_pg_index_indpred);
2586 michael@paquier.xyz 1399 : 18 : predString = TextDatumGetCString(predDatum);
1400 : 18 : indexPreds = (List *) stringToNode(predString);
1401 : :
1402 : : /* Also convert to implicit-AND format */
1403 : 18 : indexPreds = make_ands_implicit((Expr *) indexPreds);
1404 : 18 : pfree(predString);
1405 : : }
1406 : :
1407 : : /*
1408 : : * Build the index information for the new index.
1409 : : */
1410 : 338 : newInfo = makeIndexInfo(oldInfo->ii_NumIndexAttrs,
1411 : : oldInfo->ii_NumIndexKeyAttrs,
1412 : : oldInfo->ii_Am,
1413 : : indexExprs,
1414 : : indexPreds,
1415 : 338 : oldInfo->ii_Unique,
1666 peter@eisentraut.org 1416 : 338 : oldInfo->ii_NullsNotDistinct,
1417 : : !concurrently, /* isready */
1418 : : concurrently, /* concurrent */
709 1419 : 338 : indexRelation->rd_indam->amsummarizing,
1420 : 338 : oldInfo->ii_WithoutOverlaps);
1421 : :
1422 : : /* fetch exclusion constraint info if any */
145 alvherre@kurilemu.de 1423 [ + + ]: 338 : if (indexRelation->rd_index->indisexclusion)
1424 : : {
1425 : : /*
1426 : : * XXX Beware: we're making newInfo point to oldInfo-owned memory. It
1427 : : * would be more orthodox to palloc+memcpy, but we don't need that
1428 : : * here at present.
1429 : : */
1430 : 2 : newInfo->ii_ExclusionOps = oldInfo->ii_ExclusionOps;
1431 : 2 : newInfo->ii_ExclusionProcs = oldInfo->ii_ExclusionProcs;
1432 : 2 : newInfo->ii_ExclusionStrats = oldInfo->ii_ExclusionStrats;
1433 : : }
1434 : :
1435 : : /*
1436 : : * Extract the list of column names and the column numbers for the new
1437 : : * index information. All this information will be used for the index
1438 : : * creation.
1439 : : */
2586 michael@paquier.xyz 1440 [ + + ]: 799 : for (int i = 0; i < oldInfo->ii_NumIndexAttrs; i++)
1441 : : {
2708 peter@eisentraut.org 1442 : 461 : TupleDesc indexTupDesc = RelationGetDescr(indexRelation);
1443 : 461 : Form_pg_attribute att = TupleDescAttr(indexTupDesc, i);
1444 : :
1445 : 461 : indexColNames = lappend(indexColNames, NameStr(att->attname));
2586 michael@paquier.xyz 1446 : 461 : newInfo->ii_IndexAttrNumbers[i] = oldInfo->ii_IndexAttrNumbers[i];
1447 : : }
1448 : :
1449 : : /* Extract opclass options for each attribute */
260 1450 : 338 : opclassOptions = palloc0_array(Datum, newInfo->ii_NumIndexAttrs);
1059 peter@eisentraut.org 1451 [ + + ]: 799 : for (int i = 0; i < newInfo->ii_NumIndexAttrs; i++)
1452 : 461 : opclassOptions[i] = get_attoptions(oldIndexId, i + 1);
1453 : :
1454 : : /* Extract statistic targets for each attribute */
893 1455 : 338 : stattargets = palloc0_array(NullableDatum, newInfo->ii_NumIndexAttrs);
1456 [ + + ]: 799 : for (int i = 0; i < newInfo->ii_NumIndexAttrs; i++)
1457 : : {
1458 : : HeapTuple tp;
1459 : : Datum dat;
1460 : :
1461 : 461 : tp = SearchSysCache2(ATTNUM, ObjectIdGetDatum(oldIndexId), Int16GetDatum(i + 1));
1462 [ - + ]: 461 : if (!HeapTupleIsValid(tp))
893 peter@eisentraut.org 1463 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1464 : : i + 1, oldIndexId);
893 peter@eisentraut.org 1465 :CBC 461 : dat = SysCacheGetAttr(ATTNUM, tp, Anum_pg_attribute_attstattarget, &isnull);
1466 : 461 : ReleaseSysCache(tp);
1467 : 461 : stattargets[i].value = dat;
1468 : 461 : stattargets[i].isnull = isnull;
1469 : : }
1470 : :
1471 : : /*
1472 : : * Now create the new index.
1473 : : *
1474 : : * For a partition index, we adjust the partition dependency later, to
1475 : : * ensure a consistent state at all times. That is why parentIndexRelid
1476 : : * is not set here.
1477 : : */
2708 1478 : 338 : newIndexId = index_create(heapRelation,
1479 : : newName,
1480 : : InvalidOid, /* indexRelationId */
1481 : : InvalidOid, /* parentIndexRelid */
1482 : : InvalidOid, /* parentConstraintId */
1483 : : InvalidRelFileNumber, /* relFileNumber */
1484 : : newInfo,
1485 : : indexColNames,
1486 : 338 : indexRelation->rd_rel->relam,
1487 : : tablespaceOid,
1488 : 338 : indexRelation->rd_indcollation,
1489 : 338 : indclass->values,
1490 : : opclassOptions,
1491 : 338 : indcoloptions->values,
1492 : : stattargets,
1493 : : reloptionsDatum,
1494 : : flags,
1495 : : 0, /* constr_flags */
1496 : : true, /* allow table to be a system catalog? */
1497 : : false, /* is_internal? */
1498 : : NULL);
1499 : :
1500 : : /* Close the relations used and clean up */
1501 : 338 : index_close(indexRelation, NoLock);
1502 : 338 : ReleaseSysCache(indexTuple);
1503 : 338 : ReleaseSysCache(classTuple);
1504 : :
1505 : 338 : return newIndexId;
1506 : : }
1507 : :
1508 : : /*
1509 : : * index_concurrently_build
1510 : : *
1511 : : * Build index for a concurrent operation. Low-level locks are taken when
1512 : : * this operation is performed to prevent only schema changes, but they need
1513 : : * to be kept until the end of the transaction performing this operation.
1514 : : * 'indexOid' refers to an index relation OID already created as part of
1515 : : * previous processing, and 'heapOid' refers to its parent heap relation.
1516 : : */
1517 : : void
1518 : 433 : index_concurrently_build(Oid heapRelationId,
1519 : : Oid indexRelationId)
1520 : : {
1521 : : Relation heapRel;
1522 : : Oid save_userid;
1523 : : int save_sec_context;
1524 : : int save_nestlevel;
1525 : : Relation indexRelation;
1526 : : IndexInfo *indexInfo;
1527 : :
1528 : : /* This had better make sure that a snapshot is active */
1529 [ - + ]: 433 : Assert(ActiveSnapshotSet());
1530 : :
1531 : : /* Open and lock the parent heap relation */
1532 : 433 : heapRel = table_open(heapRelationId, ShareUpdateExclusiveLock);
1533 : :
1534 : : /*
1535 : : * Switch to the table owner's userid, so that any index functions are run
1536 : : * as that user. Also lock down security-restricted operations and
1537 : : * arrange to make GUC variable changes local to this command.
1538 : : */
1571 noah@leadboat.com 1539 : 433 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
1540 : 433 : SetUserIdAndSecContext(heapRel->rd_rel->relowner,
1541 : : save_sec_context | SECURITY_RESTRICTED_OPERATION);
1542 : 433 : save_nestlevel = NewGUCNestLevel();
906 jdavis@postgresql.or 1543 : 433 : RestrictSearchPath();
1544 : :
2708 peter@eisentraut.org 1545 : 433 : indexRelation = index_open(indexRelationId, RowExclusiveLock);
1546 : :
1547 : : /*
1548 : : * We have to re-build the IndexInfo struct, since it was lost in the
1549 : : * commit of the transaction where this concurrent index was created at
1550 : : * the catalog level.
1551 : : */
1552 : 433 : indexInfo = BuildIndexInfo(indexRelation);
1553 [ - + ]: 433 : Assert(!indexInfo->ii_ReadyForInserts);
1554 : 433 : indexInfo->ii_Concurrent = true;
1555 : 433 : indexInfo->ii_BrokenHotChain = false;
1556 : :
1557 : : /* Now build the index */
144 alvherre@kurilemu.de 1558 : 433 : index_build(heapRel, indexRelation, indexInfo, false, true, true);
1559 : :
1560 : : /* Roll back any GUC changes executed by index functions */
1571 noah@leadboat.com 1561 : 404 : AtEOXact_GUC(false, save_nestlevel);
1562 : :
1563 : : /* Restore userid and security context */
1564 : 404 : SetUserIdAndSecContext(save_userid, save_sec_context);
1565 : :
1566 : : /* Close both the relations, but keep the locks */
2708 peter@eisentraut.org 1567 : 404 : table_close(heapRel, NoLock);
1568 : 404 : index_close(indexRelation, NoLock);
1569 : :
1570 : : /*
1571 : : * Update the pg_index row to mark the index as ready for inserts. Once we
1572 : : * commit this transaction, any new transactions that open the table must
1573 : : * insert new entries into the index for insertions and non-HOT updates.
1574 : : */
1575 : 404 : index_set_state_flags(indexRelationId, INDEX_CREATE_SET_READY);
1576 : 404 : }
1577 : :
1578 : : /*
1579 : : * index_concurrently_swap
1580 : : *
1581 : : * Swap name, dependencies, and constraints of the old index over to the new
1582 : : * index, while marking the old index as invalid and the new as valid.
1583 : : */
1584 : : void
1585 : 326 : index_concurrently_swap(Oid newIndexId, Oid oldIndexId, const char *oldName)
1586 : : {
1587 : : Relation pg_class,
1588 : : pg_index,
1589 : : pg_constraint,
1590 : : pg_trigger;
1591 : : Relation oldClassRel,
1592 : : newClassRel;
1593 : : HeapTuple oldClassTuple,
1594 : : newClassTuple;
1595 : : Form_pg_class oldClassForm,
1596 : : newClassForm;
1597 : : HeapTuple oldIndexTuple,
1598 : : newIndexTuple;
1599 : : Form_pg_index oldIndexForm,
1600 : : newIndexForm;
1601 : : bool isPartition;
1602 : : Oid indexConstraintOid;
1603 : 326 : List *constraintOids = NIL;
1604 : : ListCell *lc;
1605 : :
1606 : : /*
1607 : : * Take a necessary lock on the old and new index before swapping them.
1608 : : */
1609 : 326 : oldClassRel = relation_open(oldIndexId, ShareUpdateExclusiveLock);
1610 : 326 : newClassRel = relation_open(newIndexId, ShareUpdateExclusiveLock);
1611 : :
1612 : : /* Now swap names and dependencies of those indexes */
1613 : 326 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
1614 : :
1615 : 326 : oldClassTuple = SearchSysCacheCopy1(RELOID,
1616 : : ObjectIdGetDatum(oldIndexId));
1617 [ - + ]: 326 : if (!HeapTupleIsValid(oldClassTuple))
2708 peter@eisentraut.org 1618 [ # # ]:UBC 0 : elog(ERROR, "could not find tuple for relation %u", oldIndexId);
2708 peter@eisentraut.org 1619 :CBC 326 : newClassTuple = SearchSysCacheCopy1(RELOID,
1620 : : ObjectIdGetDatum(newIndexId));
1621 [ - + ]: 326 : if (!HeapTupleIsValid(newClassTuple))
2708 peter@eisentraut.org 1622 [ # # ]:UBC 0 : elog(ERROR, "could not find tuple for relation %u", newIndexId);
1623 : :
2708 peter@eisentraut.org 1624 :CBC 326 : oldClassForm = (Form_pg_class) GETSTRUCT(oldClassTuple);
1625 : 326 : newClassForm = (Form_pg_class) GETSTRUCT(newClassTuple);
1626 : :
1627 : : /* Swap the names */
1628 : 326 : namestrcpy(&newClassForm->relname, NameStr(oldClassForm->relname));
1629 : 326 : namestrcpy(&oldClassForm->relname, oldName);
1630 : :
1631 : : /* Swap the partition flags to track inheritance properly */
2494 michael@paquier.xyz 1632 : 326 : isPartition = newClassForm->relispartition;
2694 peter@eisentraut.org 1633 : 326 : newClassForm->relispartition = oldClassForm->relispartition;
2494 michael@paquier.xyz 1634 : 326 : oldClassForm->relispartition = isPartition;
1635 : :
2708 peter@eisentraut.org 1636 : 326 : CatalogTupleUpdate(pg_class, &oldClassTuple->t_self, oldClassTuple);
1637 : 326 : CatalogTupleUpdate(pg_class, &newClassTuple->t_self, newClassTuple);
1638 : :
1639 : 326 : heap_freetuple(oldClassTuple);
1640 : 326 : heap_freetuple(newClassTuple);
1641 : :
1642 : : /* Now swap index info */
1643 : 326 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
1644 : :
1645 : 326 : oldIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1646 : : ObjectIdGetDatum(oldIndexId));
1647 [ - + ]: 326 : if (!HeapTupleIsValid(oldIndexTuple))
2708 peter@eisentraut.org 1648 [ # # ]:UBC 0 : elog(ERROR, "could not find tuple for relation %u", oldIndexId);
2708 peter@eisentraut.org 1649 :CBC 326 : newIndexTuple = SearchSysCacheCopy1(INDEXRELID,
1650 : : ObjectIdGetDatum(newIndexId));
1651 [ - + ]: 326 : if (!HeapTupleIsValid(newIndexTuple))
2708 peter@eisentraut.org 1652 [ # # ]:UBC 0 : elog(ERROR, "could not find tuple for relation %u", newIndexId);
1653 : :
2708 peter@eisentraut.org 1654 :CBC 326 : oldIndexForm = (Form_pg_index) GETSTRUCT(oldIndexTuple);
1655 : 326 : newIndexForm = (Form_pg_index) GETSTRUCT(newIndexTuple);
1656 : :
1657 : : /*
1658 : : * Copy constraint flags from the old index. This is safe because the old
1659 : : * index guaranteed uniqueness.
1660 : : */
1661 : 326 : newIndexForm->indisprimary = oldIndexForm->indisprimary;
1662 : 326 : oldIndexForm->indisprimary = false;
1663 : 326 : newIndexForm->indisexclusion = oldIndexForm->indisexclusion;
1664 : 326 : oldIndexForm->indisexclusion = false;
1665 : 326 : newIndexForm->indimmediate = oldIndexForm->indimmediate;
1666 : 326 : oldIndexForm->indimmediate = true;
1667 : :
1668 : : /* Preserve indisreplident in the new index */
2274 michael@paquier.xyz 1669 : 326 : newIndexForm->indisreplident = oldIndexForm->indisreplident;
1670 : :
1671 : : /* Preserve indisclustered in the new index */
2368 1672 : 326 : newIndexForm->indisclustered = oldIndexForm->indisclustered;
1673 : :
1674 : : /*
1675 : : * Mark the new index as valid, and the old index as invalid similarly to
1676 : : * what index_set_state_flags() does.
1677 : : */
2708 peter@eisentraut.org 1678 : 326 : newIndexForm->indisvalid = true;
1679 : 326 : oldIndexForm->indisvalid = false;
1680 : 326 : oldIndexForm->indisclustered = false;
2188 michael@paquier.xyz 1681 : 326 : oldIndexForm->indisreplident = false;
1682 : :
2708 peter@eisentraut.org 1683 : 326 : CatalogTupleUpdate(pg_index, &oldIndexTuple->t_self, oldIndexTuple);
1684 : 326 : CatalogTupleUpdate(pg_index, &newIndexTuple->t_self, newIndexTuple);
1685 : :
1686 : 326 : heap_freetuple(oldIndexTuple);
1687 : 326 : heap_freetuple(newIndexTuple);
1688 : :
1689 : : /*
1690 : : * Move constraints and triggers over to the new index
1691 : : */
1692 : :
1693 : 326 : constraintOids = get_index_ref_constraints(oldIndexId);
1694 : :
1695 : 326 : indexConstraintOid = get_index_constraint(oldIndexId);
1696 : :
1697 [ + + ]: 326 : if (OidIsValid(indexConstraintOid))
1698 : 43 : constraintOids = lappend_oid(constraintOids, indexConstraintOid);
1699 : :
1700 : 326 : pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
1701 : 326 : pg_trigger = table_open(TriggerRelationId, RowExclusiveLock);
1702 : :
1703 [ + + + + : 382 : foreach(lc, constraintOids)
+ + ]
1704 : : {
1705 : : HeapTuple constraintTuple,
1706 : : triggerTuple;
1707 : : Form_pg_constraint conForm;
1708 : : ScanKeyData key[1];
1709 : : SysScanDesc scan;
1710 : 56 : Oid constraintOid = lfirst_oid(lc);
1711 : :
1712 : : /* Move the constraint from the old to the new index */
1713 : 56 : constraintTuple = SearchSysCacheCopy1(CONSTROID,
1714 : : ObjectIdGetDatum(constraintOid));
1715 [ - + ]: 56 : if (!HeapTupleIsValid(constraintTuple))
2708 peter@eisentraut.org 1716 [ # # ]:UBC 0 : elog(ERROR, "could not find tuple for constraint %u", constraintOid);
1717 : :
2708 peter@eisentraut.org 1718 :CBC 56 : conForm = ((Form_pg_constraint) GETSTRUCT(constraintTuple));
1719 : :
1720 [ + - ]: 56 : if (conForm->conindid == oldIndexId)
1721 : : {
1722 : 56 : conForm->conindid = newIndexId;
1723 : :
1724 : 56 : CatalogTupleUpdate(pg_constraint, &constraintTuple->t_self, constraintTuple);
1725 : : }
1726 : :
1727 : 56 : heap_freetuple(constraintTuple);
1728 : :
1729 : : /* Search for trigger records */
1730 : 56 : ScanKeyInit(&key[0],
1731 : : Anum_pg_trigger_tgconstraint,
1732 : : BTEqualStrategyNumber, F_OIDEQ,
1733 : : ObjectIdGetDatum(constraintOid));
1734 : :
1735 : 56 : scan = systable_beginscan(pg_trigger, TriggerConstraintIndexId, true,
1736 : : NULL, 1, key);
1737 : :
1738 [ + + ]: 103 : while (HeapTupleIsValid((triggerTuple = systable_getnext(scan))))
1739 : : {
1740 : 47 : Form_pg_trigger tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1741 : :
1742 [ - + ]: 47 : if (tgForm->tgconstrindid != oldIndexId)
2708 peter@eisentraut.org 1743 :UBC 0 : continue;
1744 : :
1745 : : /* Make a modifiable copy */
2708 peter@eisentraut.org 1746 :CBC 47 : triggerTuple = heap_copytuple(triggerTuple);
1747 : 47 : tgForm = (Form_pg_trigger) GETSTRUCT(triggerTuple);
1748 : :
1749 : 47 : tgForm->tgconstrindid = newIndexId;
1750 : :
1751 : 47 : CatalogTupleUpdate(pg_trigger, &triggerTuple->t_self, triggerTuple);
1752 : :
1753 : 47 : heap_freetuple(triggerTuple);
1754 : : }
1755 : :
1756 : 56 : systable_endscan(scan);
1757 : : }
1758 : :
1759 : : /*
1760 : : * Move comment if any
1761 : : */
1762 : : {
1763 : : Relation description;
1764 : : ScanKeyData skey[3];
1765 : : SysScanDesc sd;
1766 : : HeapTuple tuple;
1767 : 326 : Datum values[Natts_pg_description] = {0};
1768 : 326 : bool nulls[Natts_pg_description] = {0};
1769 : 326 : bool replaces[Natts_pg_description] = {0};
1770 : :
1771 : 326 : values[Anum_pg_description_objoid - 1] = ObjectIdGetDatum(newIndexId);
1772 : 326 : replaces[Anum_pg_description_objoid - 1] = true;
1773 : :
1774 : 326 : ScanKeyInit(&skey[0],
1775 : : Anum_pg_description_objoid,
1776 : : BTEqualStrategyNumber, F_OIDEQ,
1777 : : ObjectIdGetDatum(oldIndexId));
1778 : 326 : ScanKeyInit(&skey[1],
1779 : : Anum_pg_description_classoid,
1780 : : BTEqualStrategyNumber, F_OIDEQ,
1781 : : ObjectIdGetDatum(RelationRelationId));
1782 : 326 : ScanKeyInit(&skey[2],
1783 : : Anum_pg_description_objsubid,
1784 : : BTEqualStrategyNumber, F_INT4EQ,
1785 : : Int32GetDatum(0));
1786 : :
1787 : 326 : description = table_open(DescriptionRelationId, RowExclusiveLock);
1788 : :
1789 : 326 : sd = systable_beginscan(description, DescriptionObjIndexId, true,
1790 : : NULL, 3, skey);
1791 : :
1792 [ + + ]: 326 : while ((tuple = systable_getnext(sd)) != NULL)
1793 : : {
1794 : 4 : tuple = heap_modify_tuple(tuple, RelationGetDescr(description),
1795 : : values, nulls, replaces);
1796 : 4 : CatalogTupleUpdate(description, &tuple->t_self, tuple);
1797 : :
2654 tgl@sss.pgh.pa.us 1798 : 4 : break; /* Assume there can be only one match */
1799 : : }
1800 : :
2708 peter@eisentraut.org 1801 : 326 : systable_endscan(sd);
1802 : 326 : table_close(description, NoLock);
1803 : : }
1804 : :
1805 : : /*
1806 : : * Swap inheritance relationship with parent index
1807 : : */
2694 1808 [ + + ]: 326 : if (get_rel_relispartition(oldIndexId))
1809 : : {
2654 tgl@sss.pgh.pa.us 1810 : 67 : List *ancestors = get_partition_ancestors(oldIndexId);
1811 : 67 : Oid parentIndexRelid = linitial_oid(ancestors);
1812 : :
1981 alvherre@alvh.no-ip. 1813 : 67 : DeleteInheritsTuple(oldIndexId, parentIndexRelid, false, NULL);
2694 peter@eisentraut.org 1814 : 67 : StoreSingleInheritance(newIndexId, parentIndexRelid, 1);
1815 : :
1816 : 67 : list_free(ancestors);
1817 : : }
1818 : :
1819 : : /*
1820 : : * Swap all dependencies of and on the old index to the new one, and
1821 : : * vice-versa. Note that a call to CommandCounterIncrement() would cause
1822 : : * duplicate entries in pg_depend, so this should not be done.
1823 : : */
2366 michael@paquier.xyz 1824 : 326 : changeDependenciesOf(RelationRelationId, newIndexId, oldIndexId);
1825 : 326 : changeDependenciesOn(RelationRelationId, newIndexId, oldIndexId);
1826 : :
2694 peter@eisentraut.org 1827 : 326 : changeDependenciesOf(RelationRelationId, oldIndexId, newIndexId);
2708 1828 : 326 : changeDependenciesOn(RelationRelationId, oldIndexId, newIndexId);
1829 : :
1830 : : /* copy over statistics from old to new index */
1604 andres@anarazel.de 1831 : 326 : pgstat_copy_relation_stats(newClassRel, oldClassRel);
1832 : :
1833 : : /* Copy data of pg_statistic from the old index to the new one */
2125 michael@paquier.xyz 1834 : 326 : CopyStatistics(oldIndexId, newIndexId);
1835 : :
1836 : : /* Close relations */
2708 peter@eisentraut.org 1837 : 326 : table_close(pg_class, RowExclusiveLock);
1838 : 326 : table_close(pg_index, RowExclusiveLock);
1839 : 326 : table_close(pg_constraint, RowExclusiveLock);
1840 : 326 : table_close(pg_trigger, RowExclusiveLock);
1841 : :
1842 : : /* The lock taken previously is not released until the end of transaction */
1843 : 326 : relation_close(oldClassRel, NoLock);
1844 : 326 : relation_close(newClassRel, NoLock);
1845 : 326 : }
1846 : :
1847 : : /*
1848 : : * index_concurrently_set_dead
1849 : : *
1850 : : * Perform the last invalidation stage of DROP INDEX CONCURRENTLY or REINDEX
1851 : : * CONCURRENTLY before actually dropping the index. After calling this
1852 : : * function, the index is seen by all the backends as dead. Low-level locks
1853 : : * taken here are kept until the end of the transaction calling this function.
1854 : : */
1855 : : void
1856 : 380 : index_concurrently_set_dead(Oid heapId, Oid indexId)
1857 : : {
1858 : : Relation userHeapRelation;
1859 : : Relation userIndexRelation;
1860 : :
1861 : : /*
1862 : : * No more predicate locks will be acquired on this index, and we're about
1863 : : * to stop doing inserts into the index which could show conflicts with
1864 : : * existing predicate locks, so now is the time to move them to the heap
1865 : : * relation.
1866 : : */
1867 : 380 : userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
1868 : 380 : userIndexRelation = index_open(indexId, ShareUpdateExclusiveLock);
1869 : 380 : TransferPredicateLocksToHeapRelation(userIndexRelation);
1870 : :
1871 : : /*
1872 : : * Now we are sure that nobody uses the index for queries; they just might
1873 : : * have it open for updating it. So now we can unset indisready and
1874 : : * indislive, then wait till nobody could be using it at all anymore.
1875 : : */
1876 : 380 : index_set_state_flags(indexId, INDEX_DROP_SET_DEAD);
1877 : :
1878 : : /*
1879 : : * Invalidate the relcache for the table, so that after this commit all
1880 : : * sessions will refresh the table's index list. Forgetting just the
1881 : : * index's relcache entry is not enough.
1882 : : */
1883 : 380 : CacheInvalidateRelcache(userHeapRelation);
1884 : :
1885 : : /*
1886 : : * Close the relations again, though still holding session lock.
1887 : : */
1888 : 380 : table_close(userHeapRelation, NoLock);
1889 : 380 : index_close(userIndexRelation, NoLock);
1890 : 380 : }
1891 : :
1892 : : /*
1893 : : * index_constraint_create
1894 : : *
1895 : : * Set up a constraint associated with an index. Return the new constraint's
1896 : : * address.
1897 : : *
1898 : : * heapRelation: table owning the index (must be suitably locked by caller)
1899 : : * indexRelationId: OID of the index
1900 : : * parentConstraintId: if constraint is on a partition, the OID of the
1901 : : * constraint in the parent.
1902 : : * indexInfo: same info executor uses to insert into the index
1903 : : * constraintName: what it say (generally, should match name of index)
1904 : : * constraintType: one of CONSTRAINT_PRIMARY, CONSTRAINT_UNIQUE, or
1905 : : * CONSTRAINT_EXCLUSION
1906 : : * flags: bitmask that can include any combination of these bits:
1907 : : * INDEX_CONSTR_CREATE_MARK_AS_PRIMARY: index is a PRIMARY KEY
1908 : : * INDEX_CONSTR_CREATE_DEFERRABLE: constraint is DEFERRABLE
1909 : : * INDEX_CONSTR_CREATE_INIT_DEFERRED: constraint is INITIALLY DEFERRED
1910 : : * INDEX_CONSTR_CREATE_UPDATE_INDEX: update the pg_index row
1911 : : * INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS: remove existing dependencies
1912 : : * of index on table's columns
1913 : : * INDEX_CONSTR_CREATE_WITHOUT_OVERLAPS: constraint uses WITHOUT OVERLAPS
1914 : : * allow_system_table_mods: allow table to be a system catalog
1915 : : * is_internal: index is constructed due to internal process
1916 : : */
1917 : : ObjectAddress
5693 tgl@sss.pgh.pa.us 1918 : 13005 : index_constraint_create(Relation heapRelation,
1919 : : Oid indexRelationId,
1920 : : Oid parentConstraintId,
1921 : : const IndexInfo *indexInfo,
1922 : : const char *constraintName,
1923 : : char constraintType,
1924 : : uint16 constr_flags,
1925 : : bool allow_system_table_mods,
1926 : : bool is_internal)
1927 : : {
1928 : 13005 : Oid namespaceId = RelationGetNamespace(heapRelation);
1929 : : ObjectAddress myself,
1930 : : idxaddr;
1931 : : Oid conOid;
1932 : : bool deferrable;
1933 : : bool initdeferred;
1934 : : bool mark_as_primary;
1935 : : bool islocal;
1936 : : bool noinherit;
1937 : : bool is_without_overlaps;
1938 : : int16 inhcount;
1939 : :
3208 alvherre@alvh.no-ip. 1940 : 13005 : deferrable = (constr_flags & INDEX_CONSTR_CREATE_DEFERRABLE) != 0;
1941 : 13005 : initdeferred = (constr_flags & INDEX_CONSTR_CREATE_INIT_DEFERRED) != 0;
1942 : 13005 : mark_as_primary = (constr_flags & INDEX_CONSTR_CREATE_MARK_AS_PRIMARY) != 0;
709 peter@eisentraut.org 1943 : 13005 : is_without_overlaps = (constr_flags & INDEX_CONSTR_CREATE_WITHOUT_OVERLAPS) != 0;
1944 : :
1945 : : /* constraint creation support doesn't work while bootstrapping */
5693 tgl@sss.pgh.pa.us 1946 [ - + ]: 13005 : Assert(!IsBootstrapProcessingMode());
1947 : :
1948 : : /* enforce system-table restriction */
1949 [ + + - + ]: 19590 : if (!allow_system_table_mods &&
1950 : 6585 : IsSystemRelation(heapRelation) &&
5693 tgl@sss.pgh.pa.us 1951 [ # # ]:UBC 0 : IsNormalProcessingMode())
1952 [ # # ]: 0 : ereport(ERROR,
1953 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1954 : : errmsg("user-defined indexes on system catalog tables are not supported")));
1955 : :
1956 : : /* primary/unique constraints shouldn't have any expressions */
5693 tgl@sss.pgh.pa.us 1957 [ + + - + ]:CBC 13005 : if (indexInfo->ii_Expressions &&
1958 : : constraintType != CONSTRAINT_EXCLUSION)
5693 tgl@sss.pgh.pa.us 1959 [ # # ]:UBC 0 : elog(ERROR, "constraints cannot have index expressions");
1960 : :
1961 : : /*
1962 : : * If we're manufacturing a constraint for a pre-existing index, we need
1963 : : * to get rid of the existing auto dependencies for the index (the ones
1964 : : * that index_create() would have made instead of calling this function).
1965 : : *
1966 : : * Note: this code would not necessarily do the right thing if the index
1967 : : * has any expressions or predicate, but we'd never be turning such an
1968 : : * index into a UNIQUE or PRIMARY KEY constraint.
1969 : : */
3208 alvherre@alvh.no-ip. 1970 [ + + ]:CBC 13005 : if (constr_flags & INDEX_CONSTR_CREATE_REMOVE_OLD_DEPS)
5129 tgl@sss.pgh.pa.us 1971 : 6405 : deleteDependencyRecordsForClass(RelationRelationId, indexRelationId,
1972 : : RelationRelationId, DEPENDENCY_AUTO);
1973 : :
3111 alvherre@alvh.no-ip. 1974 [ + + ]: 13005 : if (OidIsValid(parentConstraintId))
1975 : : {
1976 : 900 : islocal = false;
1977 : 900 : inhcount = 1;
1978 : 900 : noinherit = false;
1979 : : }
1980 : : else
1981 : : {
1982 : 12105 : islocal = true;
1983 : 12105 : inhcount = 0;
1984 : 12105 : noinherit = true;
1985 : : }
1986 : :
1987 : : /*
1988 : : * Construct a pg_constraint entry.
1989 : : */
5693 tgl@sss.pgh.pa.us 1990 : 13005 : conOid = CreateConstraintEntry(constraintName,
1991 : : namespaceId,
1992 : : constraintType,
1993 : : deferrable,
1994 : : initdeferred,
1995 : : true, /* Is Enforced */
1996 : : true,
1997 : : parentConstraintId,
1998 : : RelationGetRelid(heapRelation),
3059 teodor@sigaev.ru 1999 : 13005 : indexInfo->ii_IndexAttrNumbers,
3064 2000 : 13005 : indexInfo->ii_NumIndexKeyAttrs,
5693 tgl@sss.pgh.pa.us 2001 : 13005 : indexInfo->ii_NumIndexAttrs,
2002 : : InvalidOid, /* no domain */
2003 : : indexRelationId, /* index OID */
2004 : : InvalidOid, /* no foreign key */
2005 : : NULL,
2006 : : NULL,
2007 : : NULL,
2008 : : NULL,
2009 : : 0,
2010 : : ' ',
2011 : : ' ',
2012 : : NULL,
2013 : : 0,
2014 : : ' ',
2015 : 13005 : indexInfo->ii_ExclusionOps,
2016 : : NULL, /* no check constraint */
2017 : : NULL,
2018 : : islocal,
2019 : : inhcount,
2020 : : noinherit,
2021 : : is_without_overlaps,
2022 : : is_internal);
2023 : :
2024 : : /*
2025 : : * Register the index as internally dependent on the constraint.
2026 : : *
2027 : : * Note that the constraint has a dependency on the table, so we don't
2028 : : * need (or want) any direct dependency from the index to the table.
2029 : : */
2716 alvherre@alvh.no-ip. 2030 : 13005 : ObjectAddressSet(myself, ConstraintRelationId, conOid);
2031 : 13005 : ObjectAddressSet(idxaddr, RelationRelationId, indexRelationId);
2032 : 13005 : recordDependencyOn(&idxaddr, &myself, DEPENDENCY_INTERNAL);
2033 : :
2034 : : /*
2035 : : * Also, if this is a constraint on a partition, give it partition-type
2036 : : * dependencies on the parent constraint as well as the table.
2037 : : */
3111 2038 [ + + ]: 13005 : if (OidIsValid(parentConstraintId))
2039 : : {
2040 : : ObjectAddress referenced;
2041 : :
2754 tgl@sss.pgh.pa.us 2042 : 900 : ObjectAddressSet(referenced, ConstraintRelationId, parentConstraintId);
2043 : 900 : recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
2044 : 900 : ObjectAddressSet(referenced, RelationRelationId,
2045 : : RelationGetRelid(heapRelation));
2046 : 900 : recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
2047 : : }
2048 : :
2049 : : /*
2050 : : * If the constraint is deferrable, create the deferred uniqueness
2051 : : * checking trigger. (The trigger will be given an internal dependency on
2052 : : * the constraint by CreateTrigger.)
2053 : : */
5693 2054 [ + + ]: 13005 : if (deferrable)
2055 : : {
2112 2056 : 92 : CreateTrigStmt *trigger = makeNode(CreateTrigStmt);
2057 : :
2058 : 92 : trigger->replace = false;
2059 : 92 : trigger->isconstraint = true;
5693 2060 : 92 : trigger->trigname = (constraintType == CONSTRAINT_PRIMARY) ?
2061 [ + + ]: 92 : "PK_ConstraintTrigger" :
2062 : : "Unique_ConstraintTrigger";
4574 rhaas@postgresql.org 2063 : 92 : trigger->relation = NULL;
5693 tgl@sss.pgh.pa.us 2064 : 92 : trigger->funcname = SystemFuncName("unique_key_recheck");
2065 : 92 : trigger->args = NIL;
2066 : 92 : trigger->row = true;
2067 : 92 : trigger->timing = TRIGGER_TYPE_AFTER;
2068 : 92 : trigger->events = TRIGGER_TYPE_INSERT | TRIGGER_TYPE_UPDATE;
2069 : 92 : trigger->columns = NIL;
2070 : 92 : trigger->whenClause = NULL;
2112 2071 : 92 : trigger->transitionRels = NIL;
5693 2072 : 92 : trigger->deferrable = true;
2073 : 92 : trigger->initdeferred = initdeferred;
2074 : 92 : trigger->constrrel = NULL;
2075 : :
4574 rhaas@postgresql.org 2076 : 92 : (void) CreateTrigger(trigger, NULL, RelationGetRelid(heapRelation),
2077 : : InvalidOid, conOid, indexRelationId, InvalidOid,
2078 : : InvalidOid, NULL, true, false);
2079 : : }
2080 : :
2081 : : /*
2082 : : * If needed, mark the index as primary and/or deferred in pg_index.
2083 : : *
2084 : : * Note: When making an existing index into a constraint, caller must have
2085 : : * a table lock that prevents concurrent table updates; otherwise, there
2086 : : * is a risk that concurrent readers of the table will miss seeing this
2087 : : * index at all.
2088 : : */
3208 alvherre@alvh.no-ip. 2089 [ + + + + ]: 13005 : if ((constr_flags & INDEX_CONSTR_CREATE_UPDATE_INDEX) &&
2090 [ - + ]: 2822 : (mark_as_primary || deferrable))
2091 : : {
2092 : : Relation pg_index;
2093 : : HeapTuple indexTuple;
2094 : : Form_pg_index indexForm;
5618 bruce@momjian.us 2095 : 3583 : bool dirty = false;
1678 tgl@sss.pgh.pa.us 2096 : 3583 : bool marked_as_primary = false;
2097 : :
2775 andres@anarazel.de 2098 : 3583 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
2099 : :
5693 tgl@sss.pgh.pa.us 2100 : 3583 : indexTuple = SearchSysCacheCopy1(INDEXRELID,
2101 : : ObjectIdGetDatum(indexRelationId));
2102 [ - + ]: 3583 : if (!HeapTupleIsValid(indexTuple))
5693 tgl@sss.pgh.pa.us 2103 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for index %u", indexRelationId);
5693 tgl@sss.pgh.pa.us 2104 :CBC 3583 : indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
2105 : :
2106 [ + - + - ]: 3583 : if (mark_as_primary && !indexForm->indisprimary)
2107 : : {
2108 : 3583 : indexForm->indisprimary = true;
2109 : 3583 : dirty = true;
1678 2110 : 3583 : marked_as_primary = true;
2111 : : }
2112 : :
5693 2113 [ - + - - ]: 3583 : if (deferrable && indexForm->indimmediate)
2114 : : {
5693 tgl@sss.pgh.pa.us 2115 :UBC 0 : indexForm->indimmediate = false;
2116 : 0 : dirty = true;
2117 : : }
2118 : :
5693 tgl@sss.pgh.pa.us 2119 [ + - ]:CBC 3583 : if (dirty)
2120 : : {
3495 alvherre@alvh.no-ip. 2121 : 3583 : CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
2122 : :
2123 : : /*
2124 : : * When we mark an existing index as primary, force a relcache
2125 : : * flush on its parent table, so that all sessions will become
2126 : : * aware that the table now has a primary key. This is important
2127 : : * because it affects some replication behaviors.
2128 : : */
1678 tgl@sss.pgh.pa.us 2129 [ + - ]: 3583 : if (marked_as_primary)
2130 : 3583 : CacheInvalidateRelcache(heapRelation);
2131 : :
4911 rhaas@postgresql.org 2132 [ - + ]: 3583 : InvokeObjectPostAlterHookArg(IndexRelationId, indexRelationId, 0,
2133 : : InvalidOid, is_internal);
2134 : : }
2135 : :
5693 tgl@sss.pgh.pa.us 2136 : 3583 : heap_freetuple(indexTuple);
2775 andres@anarazel.de 2137 : 3583 : table_close(pg_index, RowExclusiveLock);
2138 : : }
2139 : :
2716 alvherre@alvh.no-ip. 2140 : 13005 : return myself;
2141 : : }
2142 : :
2143 : : /*
2144 : : * index_drop
2145 : : *
2146 : : * NOTE: this routine should now only be called through performDeletion(),
2147 : : * else associated dependencies won't be cleaned up.
2148 : : *
2149 : : * If concurrent is true, do a DROP INDEX CONCURRENTLY. If concurrent is
2150 : : * false but concurrent_lock_mode is true, then do a normal DROP INDEX but
2151 : : * take a lock for CONCURRENTLY processing. That is used as part of REINDEX
2152 : : * CONCURRENTLY.
2153 : : */
2154 : : void
2708 peter@eisentraut.org 2155 : 15934 : index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
2156 : : {
2157 : : Oid heapId;
2158 : : Relation userHeapRelation;
2159 : : Relation userIndexRelation;
2160 : : Relation indexRelation;
2161 : : HeapTuple tuple;
2162 : : bool hasexprs;
2163 : : LockRelId heaprelid,
2164 : : indexrelid;
2165 : : LOCKTAG heaplocktag;
2166 : : LOCKMODE lockmode;
2167 : :
2168 : : /*
2169 : : * A temporary relation uses a non-concurrent DROP. Other backends can't
2170 : : * access a temporary relation, so there's no harm in grabbing a stronger
2171 : : * lock (see comments in RemoveRelations), and a non-concurrent DROP is
2172 : : * more efficient.
2173 : : */
2409 michael@paquier.xyz 2174 [ + + + - : 15934 : Assert(get_rel_persistence(indexId) != RELPERSISTENCE_TEMP ||
- + ]
2175 : : (!concurrent && !concurrent_lock_mode));
2176 : :
2177 : : /*
2178 : : * To drop an index safely, we must grab exclusive lock on its parent
2179 : : * table. Exclusive lock on the index alone is insufficient because
2180 : : * another backend might be about to execute a query on the parent table.
2181 : : * If it relies on a previously cached list of index OIDs, then it could
2182 : : * attempt to access the just-dropped index. We must therefore take a
2183 : : * table lock strong enough to prevent all queries on the table from
2184 : : * proceeding until we commit and send out a shared-cache-inval notice
2185 : : * that will make them update their index lists.
2186 : : *
2187 : : * In the concurrent case we avoid this requirement by disabling index use
2188 : : * in multiple steps and waiting out any transactions that might be using
2189 : : * the index, so we don't need exclusive lock on the parent table. Instead
2190 : : * we take ShareUpdateExclusiveLock, to ensure that two sessions aren't
2191 : : * doing CREATE/DROP INDEX CONCURRENTLY on the same index. (We will get
2192 : : * AccessExclusiveLock on the index below, once we're sure nobody else is
2193 : : * using it.)
2194 : : */
5384 rhaas@postgresql.org 2195 : 15934 : heapId = IndexGetRelation(indexId, false);
2708 peter@eisentraut.org 2196 [ + + + + ]: 15934 : lockmode = (concurrent || concurrent_lock_mode) ? ShareUpdateExclusiveLock : AccessExclusiveLock;
2775 andres@anarazel.de 2197 : 15934 : userHeapRelation = table_open(heapId, lockmode);
5020 tgl@sss.pgh.pa.us 2198 : 15934 : userIndexRelation = index_open(indexId, lockmode);
2199 : :
2200 : : /*
2201 : : * We might still have open queries using it in our own session, which the
2202 : : * above locking won't prevent, so test explicitly.
2203 : : */
5672 2204 : 15934 : CheckTableNotInUse(userIndexRelation, "DROP INDEX");
2205 : :
2206 : : /*
2207 : : * Drop Index Concurrently is more or less the reverse process of Create
2208 : : * Index Concurrently.
2209 : : *
2210 : : * First we unset indisvalid so queries starting afterwards don't use the
2211 : : * index to answer queries anymore. We have to keep indisready = true so
2212 : : * transactions that are still scanning the index can continue to see
2213 : : * valid index contents. For instance, if they are using READ COMMITTED
2214 : : * mode, and another transaction makes changes and commits, they need to
2215 : : * see those new tuples in the index.
2216 : : *
2217 : : * After all transactions that could possibly have used the index for
2218 : : * queries end, we can unset indisready and indislive, then wait till
2219 : : * nobody could be touching it anymore. (Note: we need indislive because
2220 : : * this state must be distinct from the initial state during CREATE INDEX
2221 : : * CONCURRENTLY, which has indislive true while indisready and indisvalid
2222 : : * are false. That's because in that state, transactions must examine the
2223 : : * index for HOT-safety decisions, while in this state we don't want them
2224 : : * to open it at all.)
2225 : : *
2226 : : * Since all predicate locks on the index are about to be made invalid, we
2227 : : * must promote them to predicate locks on the heap. In the
2228 : : * non-concurrent case we can just do that now. In the concurrent case
2229 : : * it's a bit trickier. The predicate locks must be moved when there are
2230 : : * no index scans in progress on the index and no more can subsequently
2231 : : * start, so that no new predicate locks can be made on the index. Also,
2232 : : * they must be moved before heap inserts stop maintaining the index, else
2233 : : * the conflict with the predicate lock on the index gap could be missed
2234 : : * before the lock on the heap relation is in place to detect a conflict
2235 : : * based on the heap tuple insert.
2236 : : */
5256 simon@2ndQuadrant.co 2237 [ + + ]: 15934 : if (concurrent)
2238 : : {
2239 : : /*
2240 : : * We must commit our transaction in order to make the first pg_index
2241 : : * state update visible to other sessions. If the DROP machinery has
2242 : : * already performed any other actions (removal of other objects,
2243 : : * pg_depend entries, etc), the commit would make those actions
2244 : : * permanent, which would leave us with inconsistent catalog state if
2245 : : * we fail partway through the following sequence. Since DROP INDEX
2246 : : * CONCURRENTLY is restricted to dropping just one index that has no
2247 : : * dependencies, we should get here before anything's been done ---
2248 : : * but let's check that to be sure. We can verify that the current
2249 : : * transaction has not executed any transactional updates by checking
2250 : : * that no XID has been assigned.
2251 : : */
5020 tgl@sss.pgh.pa.us 2252 [ - + ]: 54 : if (GetTopTransactionIdIfAny() != InvalidTransactionId)
5020 tgl@sss.pgh.pa.us 2253 [ # # ]:UBC 0 : ereport(ERROR,
2254 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2255 : : errmsg("DROP INDEX CONCURRENTLY must be first action in transaction")));
2256 : :
2257 : : /*
2258 : : * Mark index invalid by updating its pg_index entry
2259 : : */
5020 tgl@sss.pgh.pa.us 2260 :CBC 54 : index_set_state_flags(indexId, INDEX_DROP_CLEAR_VALID);
2261 : :
2262 : : /*
2263 : : * Invalidate the relcache for the table, so that after this commit
2264 : : * all sessions will refresh any cached plans that might reference the
2265 : : * index.
2266 : : */
2267 : 54 : CacheInvalidateRelcache(userHeapRelation);
2268 : :
2269 : : /* save lockrelid and locktag for below, then close but keep locks */
5256 simon@2ndQuadrant.co 2270 : 54 : heaprelid = userHeapRelation->rd_lockInfo.lockRelId;
2271 : 54 : SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
2272 : 54 : indexrelid = userIndexRelation->rd_lockInfo.lockRelId;
2273 : :
2775 andres@anarazel.de 2274 : 54 : table_close(userHeapRelation, NoLock);
5256 simon@2ndQuadrant.co 2275 : 54 : index_close(userIndexRelation, NoLock);
2276 : :
2277 : : /*
2278 : : * We must commit our current transaction so that the indisvalid
2279 : : * update becomes visible to other transactions; then start another.
2280 : : * Note that any previously-built data structures are lost in the
2281 : : * commit. The only data we keep past here are the relation IDs.
2282 : : *
2283 : : * Before committing, get a session-level lock on the table, to ensure
2284 : : * that neither it nor the index can be dropped before we finish. This
2285 : : * cannot block, even if someone else is waiting for access, because
2286 : : * we already have the same lock within our transaction.
2287 : : */
2288 : 54 : LockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
2289 : 54 : LockRelationIdForSession(&indexrelid, ShareUpdateExclusiveLock);
2290 : :
2291 : 54 : PopActiveSnapshot();
2292 : 54 : CommitTransactionCommand();
2293 : 54 : StartTransactionCommand();
2294 : :
2295 : : /*
2296 : : * Now we must wait until no running transaction could be using the
2297 : : * index for a query. Use AccessExclusiveLock here to check for
2298 : : * running transactions that hold locks of any kind on the table. Note
2299 : : * we do not need to worry about xacts that open the table for reading
2300 : : * after this point; they will see the index as invalid when they open
2301 : : * the relation.
2302 : : *
2303 : : * Note: the reason we use actual lock acquisition here, rather than
2304 : : * just checking the ProcArray and sleeping, is that deadlock is
2305 : : * possible if one of the transactions in question is blocked trying
2306 : : * to acquire an exclusive lock on our table. The lock code will
2307 : : * detect deadlock and error out properly.
2308 : : *
2309 : : * Note: we report progress through WaitForLockers() unconditionally
2310 : : * here, even though it will only be used when we're called by REINDEX
2311 : : * CONCURRENTLY and not when called by DROP INDEX CONCURRENTLY.
2312 : : */
2704 alvherre@alvh.no-ip. 2313 : 54 : WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2314 : :
2315 : : /*
2316 : : * Updating pg_index might involve TOAST table access, so ensure we
2317 : : * have a valid snapshot.
2318 : : */
700 nathan@postgresql.or 2319 : 54 : PushActiveSnapshot(GetTransactionSnapshot());
2320 : :
2321 : : /* Finish invalidation of index and mark it as dead */
2708 peter@eisentraut.org 2322 : 54 : index_concurrently_set_dead(heapId, indexId);
2323 : :
700 nathan@postgresql.or 2324 : 54 : PopActiveSnapshot();
2325 : :
2326 : : /*
2327 : : * Again, commit the transaction to make the pg_index update visible
2328 : : * to other sessions.
2329 : : */
5061 simon@2ndQuadrant.co 2330 : 54 : CommitTransactionCommand();
2331 : 54 : StartTransactionCommand();
2332 : :
2333 : : /*
2334 : : * Wait till every transaction that saw the old index state has
2335 : : * finished. See above about progress reporting.
2336 : : */
2704 alvherre@alvh.no-ip. 2337 : 54 : WaitForLockers(heaplocktag, AccessExclusiveLock, true);
2338 : :
2339 : : /*
2340 : : * Re-open relations to allow us to complete our actions.
2341 : : *
2342 : : * At this point, nothing should be accessing the index, but lets
2343 : : * leave nothing to chance and grab AccessExclusiveLock on the index
2344 : : * before the physical deletion.
2345 : : */
2775 andres@anarazel.de 2346 : 54 : userHeapRelation = table_open(heapId, ShareUpdateExclusiveLock);
5256 simon@2ndQuadrant.co 2347 : 54 : userIndexRelation = index_open(indexId, AccessExclusiveLock);
2348 : : }
2349 : : else
2350 : : {
2351 : : /* Not concurrent, so just transfer predicate locks and we're good */
5058 kgrittn@postgresql.o 2352 : 15880 : TransferPredicateLocksToHeapRelation(userIndexRelation);
2353 : : }
2354 : :
2355 : : /*
2356 : : * Schedule physical removal of the files (if any)
2357 : : */
1728 peter@eisentraut.org 2358 [ + - + + : 15934 : if (RELKIND_HAS_STORAGE(userIndexRelation->rd_rel->relkind))
+ - + - -
+ ]
3142 alvherre@alvh.no-ip. 2359 : 14834 : RelationDropStorage(userIndexRelation);
2360 : :
2361 : : /* ensure that stats are dropped if transaction commits */
1434 andres@anarazel.de 2362 : 15934 : pgstat_drop_relation(userIndexRelation);
2363 : :
2364 : : /*
2365 : : * Close and flush the index's relcache entry, to ensure relcache doesn't
2366 : : * try to rebuild it while we're deleting catalog entries. We keep the
2367 : : * lock though.
2368 : : */
7332 tgl@sss.pgh.pa.us 2369 : 15934 : index_close(userIndexRelation, NoLock);
2370 : :
8034 2371 : 15934 : RelationForgetRelation(indexId);
2372 : :
2373 : : /*
2374 : : * Updating pg_index might involve TOAST table access, so ensure we have a
2375 : : * valid snapshot.
2376 : : */
668 nathan@postgresql.or 2377 : 15934 : PushActiveSnapshot(GetTransactionSnapshot());
2378 : :
2379 : : /*
2380 : : * fix INDEX relation, and check for expressional index
2381 : : */
2775 andres@anarazel.de 2382 : 15934 : indexRelation = table_open(IndexRelationId, RowExclusiveLock);
2383 : :
6038 rhaas@postgresql.org 2384 : 15934 : tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
9415 tgl@sss.pgh.pa.us 2385 [ - + ]: 15934 : if (!HeapTupleIsValid(tuple))
8438 tgl@sss.pgh.pa.us 2386 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for index %u", indexId);
2387 : :
3074 andrew@dunslane.net 2388 :CBC 15934 : hasexprs = !heap_attisnull(tuple, Anum_pg_index_indexprs,
2389 : 15934 : RelationGetDescr(indexRelation));
2390 : :
3494 tgl@sss.pgh.pa.us 2391 : 15934 : CatalogTupleDelete(indexRelation, &tuple->t_self);
2392 : :
8810 2393 : 15934 : ReleaseSysCache(tuple);
2775 andres@anarazel.de 2394 : 15934 : table_close(indexRelation, RowExclusiveLock);
2395 : :
668 nathan@postgresql.or 2396 : 15934 : PopActiveSnapshot();
2397 : :
2398 : : /*
2399 : : * if it has any expression columns, we might have stored statistics about
2400 : : * them.
2401 : : */
8229 tgl@sss.pgh.pa.us 2402 [ + + ]: 15934 : if (hasexprs)
8034 2403 : 634 : RemoveStatistics(indexId, 0);
2404 : :
2405 : : /*
2406 : : * fix ATTRIBUTE relation
2407 : : */
2408 : 15934 : DeleteAttributeTuples(indexId);
2409 : :
2410 : : /*
2411 : : * fix RELATION relation
2412 : : */
2413 : 15934 : DeleteRelationTuple(indexId);
2414 : :
2415 : : /*
2416 : : * fix INHERITS relation
2417 : : */
1981 alvherre@alvh.no-ip. 2418 : 15934 : DeleteInheritsTuple(indexId, InvalidOid, false, NULL);
2419 : :
2420 : : /*
2421 : : * We are presently too lazy to attempt to compute the new correct value
2422 : : * of relhasindex (the next VACUUM will fix it if necessary). So there is
2423 : : * no need to update the pg_class tuple for the owning relation. But we
2424 : : * must send out a shared-cache-inval notice on the owning relation to
2425 : : * ensure other backends update their relcache lists of indexes. (In the
2426 : : * concurrent case, this is redundant but harmless.)
2427 : : */
8234 tgl@sss.pgh.pa.us 2428 : 15934 : CacheInvalidateRelcache(userHeapRelation);
2429 : :
2430 : : /*
2431 : : * Close owning rel, but keep lock
2432 : : */
2775 andres@anarazel.de 2433 : 15934 : table_close(userHeapRelation, NoLock);
2434 : :
2435 : : /*
2436 : : * Release the session locks before we go.
2437 : : */
5256 simon@2ndQuadrant.co 2438 [ + + ]: 15934 : if (concurrent)
2439 : : {
2440 : 54 : UnlockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
2441 : 54 : UnlockRelationIdForSession(&indexrelid, ShareUpdateExclusiveLock);
2442 : : }
11006 scrappy@hub.org 2443 : 15934 : }
2444 : :
2445 : : /* ----------------------------------------------------------------
2446 : : * index_build support
2447 : : * ----------------------------------------------------------------
2448 : : */
2449 : :
2450 : : /* ----------------
2451 : : * BuildIndexInfo
2452 : : * Construct an IndexInfo record for an open index
2453 : : *
2454 : : * IndexInfo stores the information about the index that's needed by
2455 : : * FormIndexDatum, which is used for both index_build() and later insertion
2456 : : * of individual index tuples. Normally we build an IndexInfo for an index
2457 : : * just once per command, and then use it for (potentially) many tuples.
2458 : : * ----------------
2459 : : */
2460 : : IndexInfo *
8492 tgl@sss.pgh.pa.us 2461 : 2272926 : BuildIndexInfo(Relation index)
2462 : : {
2463 : : IndexInfo *ii;
2464 : 2272926 : Form_pg_index indexStruct = index->rd_index;
2465 : : int i;
2466 : : int numAtts;
2467 : :
2468 : : /* check the number of keys, and copy attr numbers into the IndexInfo */
3064 teodor@sigaev.ru 2469 : 2272926 : numAtts = indexStruct->indnatts;
2470 [ + - - + ]: 2272926 : if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
8492 tgl@sss.pgh.pa.us 2471 [ # # ]:UBC 0 : elog(ERROR, "invalid indnatts %d for index %u",
2472 : : numAtts, RelationGetRelid(index));
2473 : :
2474 : : /*
2475 : : * Create the node, fetching any expressions needed for expressional
2476 : : * indexes and index predicate if any.
2477 : : */
2580 michael@paquier.xyz 2478 :CBC 2272926 : ii = makeIndexInfo(indexStruct->indnatts,
2479 : 2272926 : indexStruct->indnkeyatts,
2480 : 2272926 : index->rd_rel->relam,
2481 : : RelationGetIndexExpressions(index),
2482 : : RelationGetIndexPredicate(index),
2483 : 2272926 : indexStruct->indisunique,
1666 peter@eisentraut.org 2484 : 2272926 : indexStruct->indnullsnotdistinct,
2580 michael@paquier.xyz 2485 : 2272926 : indexStruct->indisready,
2486 : : false,
709 peter@eisentraut.org 2487 : 2272926 : index->rd_indam->amsummarizing,
2488 [ + + + + ]: 2272926 : indexStruct->indisexclusion && indexStruct->indisunique);
2489 : :
2490 : : /* fill in attribute numbers */
3064 teodor@sigaev.ru 2491 [ + + ]: 6931025 : for (i = 0; i < numAtts; i++)
3059 2492 : 4658099 : ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2493 : :
2494 : : /* fetch exclusion constraint info if any */
5693 tgl@sss.pgh.pa.us 2495 [ + + ]: 2272926 : if (indexStruct->indisexclusion)
2496 : : {
6107 2497 : 2295 : RelationGetExclusionInfo(index,
2498 : : &ii->ii_ExclusionOps,
2499 : : &ii->ii_ExclusionProcs,
2500 : : &ii->ii_ExclusionStrats);
2501 : : }
2502 : :
9540 2503 : 2272926 : return ii;
2504 : : }
2505 : :
2506 : : /* ----------------
2507 : : * BuildDummyIndexInfo
2508 : : * Construct a dummy IndexInfo record for an open index
2509 : : *
2510 : : * This differs from the real BuildIndexInfo in that it will never run any
2511 : : * user-defined code that might exist in index expressions or predicates.
2512 : : * Instead of the real index expressions, we return null constants that have
2513 : : * the right types/typmods/collations. Predicates and exclusion clauses are
2514 : : * just ignored. This is sufficient for the purpose of truncating an index,
2515 : : * since we will not need to actually evaluate the expressions or predicates;
2516 : : * the only thing that's likely to be done with the data is construction of
2517 : : * a tupdesc describing the index's rowtype.
2518 : : * ----------------
2519 : : */
2520 : : IndexInfo *
2461 2521 : 151 : BuildDummyIndexInfo(Relation index)
2522 : : {
2523 : : IndexInfo *ii;
2524 : 151 : Form_pg_index indexStruct = index->rd_index;
2525 : : int i;
2526 : : int numAtts;
2527 : :
2528 : : /* check the number of keys, and copy attr numbers into the IndexInfo */
2529 : 151 : numAtts = indexStruct->indnatts;
2530 [ + - - + ]: 151 : if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
2461 tgl@sss.pgh.pa.us 2531 [ # # ]:UBC 0 : elog(ERROR, "invalid indnatts %d for index %u",
2532 : : numAtts, RelationGetRelid(index));
2533 : :
2534 : : /*
2535 : : * Create the node, using dummy index expressions, and pretending there is
2536 : : * no predicate.
2537 : : */
2461 tgl@sss.pgh.pa.us 2538 :CBC 302 : ii = makeIndexInfo(indexStruct->indnatts,
2539 : 151 : indexStruct->indnkeyatts,
2540 : 151 : index->rd_rel->relam,
2541 : : RelationGetDummyIndexExpressions(index),
2542 : : NIL,
2543 : 151 : indexStruct->indisunique,
1666 peter@eisentraut.org 2544 : 151 : indexStruct->indnullsnotdistinct,
2461 tgl@sss.pgh.pa.us 2545 : 151 : indexStruct->indisready,
2546 : : false,
709 peter@eisentraut.org 2547 : 151 : index->rd_indam->amsummarizing,
2548 [ - + - - ]: 151 : indexStruct->indisexclusion && indexStruct->indisunique);
2549 : :
2550 : : /* fill in attribute numbers */
2461 tgl@sss.pgh.pa.us 2551 [ + + ]: 375 : for (i = 0; i < numAtts; i++)
2552 : 224 : ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
2553 : :
2554 : : /* We ignore the exclusion constraint if any */
2555 : :
2556 : 151 : return ii;
2557 : : }
2558 : :
2559 : : /*
2560 : : * CompareIndexInfo
2561 : : * Return whether the properties of two indexes (in different tables)
2562 : : * indicate that they have the "same" definitions.
2563 : : *
2564 : : * Note: passing collations and opfamilies separately is a kludge. Adding
2565 : : * them to IndexInfo may result in better coding here and elsewhere.
2566 : : *
2567 : : * Use build_attrmap_by_name(index2, index1) to build the attmap.
2568 : : */
2569 : : bool
1100 peter@eisentraut.org 2570 : 475 : CompareIndexInfo(const IndexInfo *info1, const IndexInfo *info2,
2571 : : const Oid *collations1, const Oid *collations2,
2572 : : const Oid *opfamilies1, const Oid *opfamilies2,
2573 : : const AttrMap *attmap)
2574 : : {
2575 : : int i;
2576 : :
3142 alvherre@alvh.no-ip. 2577 [ - + ]: 475 : if (info1->ii_Unique != info2->ii_Unique)
3142 alvherre@alvh.no-ip. 2578 :UBC 0 : return false;
2579 : :
1666 peter@eisentraut.org 2580 [ - + ]:CBC 475 : if (info1->ii_NullsNotDistinct != info2->ii_NullsNotDistinct)
1666 peter@eisentraut.org 2581 :UBC 0 : return false;
2582 : :
2583 : : /* indexes are only equivalent if they have the same access method */
3142 alvherre@alvh.no-ip. 2584 [ + + ]:CBC 475 : if (info1->ii_Am != info2->ii_Am)
2585 : 8 : return false;
2586 : :
2587 : : /* and same number of attributes */
2588 [ + + ]: 467 : if (info1->ii_NumIndexAttrs != info2->ii_NumIndexAttrs)
2589 : 16 : return false;
2590 : :
2591 : : /* and same number of key attributes */
3059 teodor@sigaev.ru 2592 [ - + ]: 451 : if (info1->ii_NumIndexKeyAttrs != info2->ii_NumIndexKeyAttrs)
3059 teodor@sigaev.ru 2593 :UBC 0 : return false;
2594 : :
2595 : : /*
2596 : : * and columns match through the attribute map (actual attribute numbers
2597 : : * might differ!) Note that this checks that index columns that are
2598 : : * expressions appear in the same positions. We will next compare the
2599 : : * expressions themselves.
2600 : : */
3142 alvherre@alvh.no-ip. 2601 [ + + ]:CBC 930 : for (i = 0; i < info1->ii_NumIndexAttrs; i++)
2602 : : {
2444 michael@paquier.xyz 2603 [ - + ]: 507 : if (attmap->maplen < info2->ii_IndexAttrNumbers[i])
3142 alvherre@alvh.no-ip. 2604 [ # # ]:UBC 0 : elog(ERROR, "incorrect attribute map");
2605 : :
2606 : : /* ignore expressions for now (but check their collation/opfamily) */
1064 tgl@sss.pgh.pa.us 2607 [ + + ]:CBC 507 : if (!(info1->ii_IndexAttrNumbers[i] == InvalidAttrNumber &&
2608 [ + + ]: 52 : info2->ii_IndexAttrNumbers[i] == InvalidAttrNumber))
2609 : : {
2610 : : /* fail if just one index has an expression in this column */
2611 [ + + ]: 459 : if (info1->ii_IndexAttrNumbers[i] == InvalidAttrNumber ||
2612 [ - + ]: 455 : info2->ii_IndexAttrNumbers[i] == InvalidAttrNumber)
2613 : 4 : return false;
2614 : :
2615 : : /* both are columns, so check for match after mapping */
2616 : 455 : if (attmap->attnums[info2->ii_IndexAttrNumbers[i] - 1] !=
2617 [ + + ]: 455 : info1->ii_IndexAttrNumbers[i])
2618 : 8 : return false;
2619 : : }
2620 : :
2621 : : /* collation and opfamily are not valid for included columns */
3059 teodor@sigaev.ru 2622 [ + + ]: 495 : if (i >= info1->ii_NumIndexKeyAttrs)
2623 : 8 : continue;
2624 : :
3142 alvherre@alvh.no-ip. 2625 [ + + ]: 487 : if (collations1[i] != collations2[i])
2626 : 8 : return false;
2627 [ + + ]: 479 : if (opfamilies1[i] != opfamilies2[i])
2628 : 8 : return false;
2629 : : }
2630 : :
2631 : : /*
2632 : : * For expression indexes: either both are expression indexes, or neither
2633 : : * is; if they are, make sure the expressions match.
2634 : : */
2635 [ - + ]: 423 : if ((info1->ii_Expressions != NIL) != (info2->ii_Expressions != NIL))
3142 alvherre@alvh.no-ip. 2636 :UBC 0 : return false;
3142 alvherre@alvh.no-ip. 2637 [ + + ]:CBC 423 : if (info1->ii_Expressions != NIL)
2638 : : {
2639 : : bool found_whole_row;
2640 : : Node *mapped;
2641 : :
2642 : 48 : mapped = map_variable_attnos((Node *) info2->ii_Expressions,
2643 : : 1, 0, attmap,
2644 : : InvalidOid, &found_whole_row);
2645 [ - + ]: 48 : if (found_whole_row)
2646 : : {
2647 : : /*
2648 : : * we could throw an error here, but seems out of scope for this
2649 : : * routine.
2650 : : */
2651 : 4 : return false;
2652 : : }
2653 : :
2654 [ + + ]: 48 : if (!equal(info1->ii_Expressions, mapped))
2655 : 4 : return false;
2656 : : }
2657 : :
2658 : : /* Partial index predicates must be identical, if they exist */
2659 [ + + ]: 419 : if ((info1->ii_Predicate == NULL) != (info2->ii_Predicate == NULL))
2660 : 8 : return false;
2661 [ + + ]: 411 : if (info1->ii_Predicate != NULL)
2662 : : {
2663 : : bool found_whole_row;
2664 : : Node *mapped;
2665 : :
2666 : 16 : mapped = map_variable_attnos((Node *) info2->ii_Predicate,
2667 : : 1, 0, attmap,
2668 : : InvalidOid, &found_whole_row);
2669 [ - + ]: 16 : if (found_whole_row)
2670 : : {
2671 : : /*
2672 : : * we could throw an error here, but seems out of scope for this
2673 : : * routine.
2674 : : */
2675 : 4 : return false;
2676 : : }
2677 [ + + ]: 16 : if (!equal(info1->ii_Predicate, mapped))
2678 : 4 : return false;
2679 : : }
2680 : :
2681 : : /* If they're exclusion indexes, their properties must be identical */
38 alvherre@kurilemu.de 2682 [ - + ]: 407 : if ((info1->ii_ExclusionOps == NULL) != (info2->ii_ExclusionOps == NULL))
3142 alvherre@alvh.no-ip. 2683 :UBC 0 : return false;
38 alvherre@kurilemu.de 2684 [ + + ]:CBC 407 : if (info1->ii_ExclusionOps != NULL)
2685 : : {
2686 [ + + ]: 19 : for (i = 0; i < info1->ii_NumIndexKeyAttrs; i++)
2687 : : {
2688 [ + + ]: 14 : if (info1->ii_ExclusionOps[i] != info2->ii_ExclusionOps[i])
2689 : 4 : return false;
2690 [ - + ]: 10 : if (info1->ii_ExclusionProcs[i] != info2->ii_ExclusionProcs[i])
38 alvherre@kurilemu.de 2691 :UBC 0 : return false;
38 alvherre@kurilemu.de 2692 [ - + ]:CBC 10 : if (info1->ii_ExclusionStrats[i] != info2->ii_ExclusionStrats[i])
38 alvherre@kurilemu.de 2693 :UBC 0 : return false;
2694 : : }
2695 : : }
2696 : :
3142 alvherre@alvh.no-ip. 2697 :CBC 403 : return true;
2698 : : }
2699 : :
2700 : : /* ----------------
2701 : : * BuildSpeculativeIndexInfo
2702 : : * Add extra state to IndexInfo record
2703 : : *
2704 : : * For unique indexes, we usually don't want to add info to the IndexInfo for
2705 : : * checking uniqueness, since the B-Tree AM handles that directly. However, in
2706 : : * the case of speculative insertion and conflict detection in logical
2707 : : * replication, additional support is required.
2708 : : *
2709 : : * Do this processing here rather than in BuildIndexInfo() to not incur the
2710 : : * overhead in the common non-speculative cases.
2711 : : * ----------------
2712 : : */
2713 : : void
4129 andres@anarazel.de 2714 : 1196 : BuildSpeculativeIndexInfo(Relation index, IndexInfo *ii)
2715 : : {
2716 : : int indnkeyatts;
2717 : : int i;
2718 : :
3064 teodor@sigaev.ru 2719 : 1196 : indnkeyatts = IndexRelationGetNumberOfKeyAttributes(index);
2720 : :
2721 : : /*
2722 : : * fetch info for checking unique indexes
2723 : : */
4129 andres@anarazel.de 2724 [ - + ]: 1196 : Assert(ii->ii_Unique);
2725 : :
260 michael@paquier.xyz 2726 : 1196 : ii->ii_UniqueOps = palloc_array(Oid, indnkeyatts);
2727 : 1196 : ii->ii_UniqueProcs = palloc_array(Oid, indnkeyatts);
2728 : 1196 : ii->ii_UniqueStrats = palloc_array(uint16, indnkeyatts);
2729 : :
2730 : : /*
2731 : : * We have to look up the operator's strategy number. This provides a
2732 : : * cross-check that the operator does match the index.
2733 : : */
2734 : : /* We need the func OIDs and strategy numbers too */
3064 teodor@sigaev.ru 2735 [ + + ]: 2475 : for (i = 0; i < indnkeyatts; i++)
2736 : : {
566 peter@eisentraut.org 2737 : 2558 : ii->ii_UniqueStrats[i] =
2738 : 1279 : IndexAmTranslateCompareType(COMPARE_EQ,
2739 : 1279 : index->rd_rel->relam,
2740 : 1279 : index->rd_opfamily[i],
2741 : : false);
4129 andres@anarazel.de 2742 : 2558 : ii->ii_UniqueOps[i] =
2743 : 1279 : get_opfamily_member(index->rd_opfamily[i],
2744 : 1279 : index->rd_opcintype[i],
2745 : 1279 : index->rd_opcintype[i],
2746 : 1279 : ii->ii_UniqueStrats[i]);
3321 tgl@sss.pgh.pa.us 2747 [ - + ]: 1279 : if (!OidIsValid(ii->ii_UniqueOps[i]))
3321 tgl@sss.pgh.pa.us 2748 [ # # ]:UBC 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2749 : : ii->ii_UniqueStrats[i], index->rd_opcintype[i],
2750 : : index->rd_opcintype[i], index->rd_opfamily[i]);
4129 andres@anarazel.de 2751 :CBC 1279 : ii->ii_UniqueProcs[i] = get_opcode(ii->ii_UniqueOps[i]);
2752 : : }
2753 : 1196 : }
2754 : :
2755 : : /* ----------------
2756 : : * FormIndexDatum
2757 : : * Construct values[] and isnull[] arrays for a new index tuple.
2758 : : *
2759 : : * indexInfo Info about the index
2760 : : * slot Heap tuple for which we must prepare an index entry
2761 : : * estate executor state for evaluating any index expressions
2762 : : * values Array of index Datums (output area)
2763 : : * isnull Array of is-null indicators (output area)
2764 : : *
2765 : : * When there are no index expressions, estate may be NULL. Otherwise it
2766 : : * must be supplied, *and* the ecxt_scantuple slot of its per-tuple expr
2767 : : * context must point to the heap tuple passed in.
2768 : : *
2769 : : * Notice we don't actually call index_form_tuple() here; we just prepare
2770 : : * its input arrays values[] and isnull[]. This is because the index AM
2771 : : * may wish to alter the data before storage.
2772 : : * ----------------
2773 : : */
2774 : : void
9540 tgl@sss.pgh.pa.us 2775 : 17384695 : FormIndexDatum(IndexInfo *indexInfo,
2776 : : TupleTableSlot *slot,
2777 : : EState *estate,
2778 : : Datum *values,
2779 : : bool *isnull)
2780 : : {
2781 : : ListCell *indexpr_item;
2782 : : int i;
2783 : :
8492 2784 [ + + ]: 17384695 : if (indexInfo->ii_Expressions != NIL &&
2785 [ + + ]: 320949 : indexInfo->ii_ExpressionsState == NIL)
2786 : : {
2787 : : /* First time through, set up expression evaluation state */
3453 andres@anarazel.de 2788 : 588 : indexInfo->ii_ExpressionsState =
2789 : 588 : ExecPrepareExprList(indexInfo->ii_Expressions, estate);
2790 : : /* Check caller has set up context correctly */
7834 tgl@sss.pgh.pa.us 2791 [ + - - + ]: 588 : Assert(GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
2792 : : }
8128 neilc@samurai.com 2793 : 17384695 : indexpr_item = list_head(indexInfo->ii_ExpressionsState);
2794 : :
8492 tgl@sss.pgh.pa.us 2795 [ + + ]: 43664489 : for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
2796 : : {
3059 teodor@sigaev.ru 2797 : 26279819 : int keycol = indexInfo->ii_IndexAttrNumbers[i];
2798 : : Datum iDatum;
2799 : : bool isNull;
2800 : :
2841 andres@anarazel.de 2801 [ - + ]: 26279819 : if (keycol < 0)
2841 andres@anarazel.de 2802 :UBC 0 : iDatum = slot_getsysattr(slot, keycol, &isNull);
2841 andres@anarazel.de 2803 [ + + ]:CBC 26279819 : else if (keycol != 0)
2804 : : {
2805 : : /*
2806 : : * Plain index column; get the value we need directly from the
2807 : : * heap tuple.
2808 : : */
7834 tgl@sss.pgh.pa.us 2809 : 25958834 : iDatum = slot_getattr(slot, keycol, &isNull);
2810 : : }
2811 : : else
2812 : : {
2813 : : /*
2814 : : * Index expression --- need to evaluate it.
2815 : : */
8128 neilc@samurai.com 2816 [ - + ]: 320985 : if (indexpr_item == NULL)
8492 tgl@sss.pgh.pa.us 2817 [ # # ]:UBC 0 : elog(ERROR, "wrong number of index expressions");
8128 neilc@samurai.com 2818 :CBC 320985 : iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item),
7621 bruce@momjian.us 2819 [ + - ]: 320985 : GetPerTupleExprContext(estate),
2820 : : &isNull);
2600 tgl@sss.pgh.pa.us 2821 : 320960 : indexpr_item = lnext(indexInfo->ii_ExpressionsState, indexpr_item);
2822 : : }
7829 2823 : 26279794 : values[i] = iDatum;
2824 : 26279794 : isnull[i] = isNull;
2825 : : }
2826 : :
8128 neilc@samurai.com 2827 [ - + ]: 17384670 : if (indexpr_item != NULL)
8492 tgl@sss.pgh.pa.us 2828 [ # # ]:UBC 0 : elog(ERROR, "wrong number of index expressions");
11006 scrappy@hub.org 2829 :CBC 17384670 : }
2830 : :
2831 : :
2832 : : /*
2833 : : * index_update_stats --- update pg_class entry after CREATE INDEX or REINDEX
2834 : : *
2835 : : * This routine updates the pg_class row of either an index or its parent
2836 : : * relation after CREATE INDEX or REINDEX. Its rather bizarre API is designed
2837 : : * to ensure we can do all the necessary work in just one update.
2838 : : *
2839 : : * hasindex: set relhasindex to this value
2840 : : * reltuples: if >= 0, set reltuples to this value; else no change
2841 : : *
2842 : : * If reltuples >= 0, relpages, relallvisible, and relallfrozen are also
2843 : : * updated (using RelationGetNumberOfBlocks() and visibilitymap_count()).
2844 : : *
2845 : : * NOTE: an important side-effect of this operation is that an SI invalidation
2846 : : * message is sent out to all backends --- including me --- causing relcache
2847 : : * entries to be flushed or updated with the new data. This must happen even
2848 : : * if we find that no change is needed in the pg_class row. When updating
2849 : : * a heap entry, this ensures that other backends find out about the new
2850 : : * index. When updating an index, it's important because some index AMs
2851 : : * expect a relcache flush to occur after REINDEX.
2852 : : */
2853 : : static void
6107 tgl@sss.pgh.pa.us 2854 : 69792 : index_update_stats(Relation rel,
2855 : : bool hasindex,
2856 : : double reltuples)
2857 : : {
2858 : : bool update_stats;
663 noah@leadboat.com 2859 : 69792 : BlockNumber relpages = 0; /* keep compiler quiet */
2860 : 69792 : BlockNumber relallvisible = 0;
542 melanieplageman@gmai 2861 : 69792 : BlockNumber relallfrozen = 0;
7414 tgl@sss.pgh.pa.us 2862 : 69792 : Oid relid = RelationGetRelid(rel);
2863 : : Relation pg_class;
2864 : : ScanKeyData key[1];
2865 : : HeapTuple tuple;
2866 : : void *state;
2867 : : Form_pg_class rd_rel;
2868 : : bool dirty;
2869 : :
2870 : : /*
2871 : : * As a special hack, if we are dealing with an empty table and the
2872 : : * existing reltuples is -1, we leave that alone. This ensures that
2873 : : * creating an index as part of CREATE TABLE doesn't cause the table to
2874 : : * prematurely look like it's been vacuumed. The rd_rel we modify may
2875 : : * differ from rel->rd_rel due to e.g. commit of concurrent GRANT, but the
2876 : : * commands that change reltuples take locks conflicting with ours. (Even
2877 : : * if a command changed reltuples under a weaker lock, this affects only
2878 : : * statistics for an empty table.)
2879 : : */
663 noah@leadboat.com 2880 [ + + + + ]: 69792 : if (reltuples == 0 && rel->rd_rel->reltuples < 0)
2881 : 28945 : reltuples = -1;
2882 : :
2883 : : /*
2884 : : * Don't update statistics during binary upgrade, because the indexes are
2885 : : * created before the data is moved into place.
2886 : : */
2887 [ + + + + ]: 69792 : update_stats = reltuples >= 0 && !IsBinaryUpgrade;
2888 : :
2889 : : /*
2890 : : * If autovacuum is off, user may not be expecting table relstats to
2891 : : * change. This can be important when restoring a dump that includes
2892 : : * statistics, as the table statistics may be restored before the index is
2893 : : * created, and we want to preserve the restored table statistics.
2894 : : */
535 tgl@sss.pgh.pa.us 2895 [ + + ]: 69792 : if (rel->rd_rel->relkind == RELKIND_RELATION ||
2896 [ + + ]: 48513 : rel->rd_rel->relkind == RELKIND_TOASTVALUE ||
2897 [ + + ]: 35315 : rel->rd_rel->relkind == RELKIND_MATVIEW)
2898 : : {
2899 [ + + ]: 34606 : if (AutoVacuumingActive())
2900 : : {
539 jdavis@postgresql.or 2901 : 33620 : StdRdOptions *options = (StdRdOptions *) rel->rd_options;
2902 : :
10 nathan@postgresql.or 2903 [ + + ]:GNC 33620 : if (options != NULL &&
2904 [ + + ]: 386 : options->autovacuum.enabled == PG_TERNARY_FALSE)
539 jdavis@postgresql.or 2905 :CBC 218 : update_stats = false;
2906 : : }
2907 : : else
535 tgl@sss.pgh.pa.us 2908 : 986 : update_stats = false;
2909 : : }
2910 : :
2911 : : /*
2912 : : * Finish I/O and visibility map buffer locks before
2913 : : * systable_inplace_update_begin() locks the pg_class buffer. The rd_rel
2914 : : * we modify may differ from rel->rd_rel due to e.g. commit of concurrent
2915 : : * GRANT, but no command changes a relkind from non-index to index. (Even
2916 : : * if one did, relallvisible doesn't break functionality.)
2917 : : */
663 noah@leadboat.com 2918 [ + + ]: 69792 : if (update_stats)
2919 : : {
2920 : 37736 : relpages = RelationGetNumberOfBlocks(rel);
2921 : :
2922 [ + + ]: 37736 : if (rel->rd_rel->relkind != RELKIND_INDEX)
542 melanieplageman@gmai 2923 : 7741 : visibilitymap_count(rel, &relallvisible, &relallfrozen);
2924 : : }
2925 : :
2926 : : /*
2927 : : * We always update the pg_class row using a non-transactional,
2928 : : * overwrite-in-place update. There are several reasons for this:
2929 : : *
2930 : : * 1. In bootstrap mode, we have no choice --- UPDATE wouldn't work.
2931 : : *
2932 : : * 2. We could be reindexing pg_class itself, in which case we can't move
2933 : : * its pg_class row because CatalogTupleInsert/CatalogTupleUpdate might
2934 : : * not know about all the indexes yet (see reindex_relation).
2935 : : *
2936 : : * 3. Because we execute CREATE INDEX with just share lock on the parent
2937 : : * rel (to allow concurrent index creations), an ordinary update could
2938 : : * suffer a tuple-concurrently-updated failure against another CREATE
2939 : : * INDEX committing at about the same time. We can avoid that by having
2940 : : * them both do nontransactional updates (we assume they will both be
2941 : : * trying to change the pg_class row to the same thing, so it doesn't
2942 : : * matter which goes first).
2943 : : *
2944 : : * It is safe to use a non-transactional update even though our
2945 : : * transaction could still fail before committing. Setting relhasindex
2946 : : * true is safe even if there are no indexes (VACUUM will eventually fix
2947 : : * it). And of course the new relpages and reltuples counts are correct
2948 : : * regardless. However, we don't want to change relpages (or
2949 : : * relallvisible) if the caller isn't providing an updated reltuples
2950 : : * count, because that would bollix the reltuples/relpages ratio which is
2951 : : * what's really important.
2952 : : */
2953 : :
2775 andres@anarazel.de 2954 : 69792 : pg_class = table_open(RelationRelationId, RowExclusiveLock);
2955 : :
702 noah@leadboat.com 2956 : 69792 : ScanKeyInit(&key[0],
2957 : : Anum_pg_class_oid,
2958 : : BTEqualStrategyNumber, F_OIDEQ,
2959 : : ObjectIdGetDatum(relid));
2960 : 69792 : systable_inplace_update_begin(pg_class, ClassOidIndexId, true, NULL,
2961 : : 1, key, &tuple, &state);
2962 : :
9687 inoue@tpf.co.jp 2963 [ - + ]: 69792 : if (!HeapTupleIsValid(tuple))
8438 tgl@sss.pgh.pa.us 2964 [ # # ]:UBC 0 : elog(ERROR, "could not find tuple for relation %u", relid);
7414 tgl@sss.pgh.pa.us 2965 :CBC 69792 : rd_rel = (Form_pg_class) GETSTRUCT(tuple);
2966 : :
2967 : : /* Should this be a more comprehensive test? */
3142 alvherre@alvh.no-ip. 2968 [ - + ]: 69792 : Assert(rd_rel->relkind != RELKIND_PARTITIONED_INDEX);
2969 : :
2970 : : /* Apply required updates, if any, to copied tuple */
2971 : :
7414 tgl@sss.pgh.pa.us 2972 : 69792 : dirty = false;
2973 [ + + ]: 69792 : if (rd_rel->relhasindex != hasindex)
2974 : : {
2975 : 24164 : rd_rel->relhasindex = hasindex;
8943 2976 : 24164 : dirty = true;
2977 : : }
2978 : :
663 noah@leadboat.com 2979 [ + + ]: 69792 : if (update_stats)
2980 : : {
5431 tgl@sss.pgh.pa.us 2981 [ + + ]: 37736 : if (rd_rel->relpages != (int32) relpages)
2982 : : {
2983 : 32407 : rd_rel->relpages = (int32) relpages;
2984 : 32407 : dirty = true;
2985 : : }
2986 [ + + ]: 37736 : if (rd_rel->reltuples != (float4) reltuples)
2987 : : {
2988 : 9969 : rd_rel->reltuples = (float4) reltuples;
2989 : 9969 : dirty = true;
2990 : : }
2991 [ + + ]: 37736 : if (rd_rel->relallvisible != (int32) relallvisible)
2992 : : {
2993 : 118 : rd_rel->relallvisible = (int32) relallvisible;
2994 : 118 : dirty = true;
2995 : : }
542 melanieplageman@gmai 2996 [ + + ]: 37736 : if (rd_rel->relallfrozen != (int32) relallfrozen)
2997 : : {
2998 : 51 : rd_rel->relallfrozen = (int32) relallfrozen;
2999 : 51 : dirty = true;
3000 : : }
3001 : : }
3002 : :
3003 : : /*
3004 : : * If anything changed, write out the tuple
3005 : : */
7414 tgl@sss.pgh.pa.us 3006 [ + + ]: 69792 : if (dirty)
3007 : : {
702 noah@leadboat.com 3008 : 54312 : systable_inplace_update_finish(state, tuple);
3009 : : /* the above sends transactional and immediate cache inval messages */
3010 : : }
3011 : : else
3012 : : {
3013 : 15480 : systable_inplace_update_cancel(state);
3014 : :
3015 : : /*
3016 : : * While we didn't change relhasindex, CREATE INDEX needs a
3017 : : * transactional inval for when the new index's catalog rows become
3018 : : * visible. Other CREATE INDEX and REINDEX code happens to also queue
3019 : : * this inval, but keep this in case rare callers rely on this part of
3020 : : * our API contract.
3021 : : */
8234 tgl@sss.pgh.pa.us 3022 : 15480 : CacheInvalidateRelcacheByTuple(tuple);
3023 : : }
3024 : :
7414 3025 : 69792 : heap_freetuple(tuple);
3026 : :
2775 andres@anarazel.de 3027 : 69792 : table_close(pg_class, RowExclusiveLock);
9687 inoue@tpf.co.jp 3028 : 69792 : }
3029 : :
3030 : :
3031 : : /*
3032 : : * index_build - invoke access-method-specific index build procedure
3033 : : *
3034 : : * On entry, the index's catalog entries are valid, and its physical disk
3035 : : * file has been created but is empty. We call the AM-specific build
3036 : : * procedure to fill in the index contents. We then update the pg_class
3037 : : * entries of the index and heap relation as needed, using statistics
3038 : : * returned by ambuild as well as data passed by the caller.
3039 : : *
3040 : : * isreindex indicates we are recreating a previously-existing index.
3041 : : * parallel indicates if parallelism may be useful.
3042 : : * progress indicates if the backend should update its progress info.
3043 : : *
3044 : : * Note: before Postgres 8.2, the passed-in heap and index Relations
3045 : : * were automatically closed by this routine. This is no longer the case.
3046 : : * The caller opened 'em, and the caller should close 'em.
3047 : : */
3048 : : void
9174 tgl@sss.pgh.pa.us 3049 : 33949 : index_build(Relation heapRelation,
3050 : : Relation indexRelation,
3051 : : IndexInfo *indexInfo,
3052 : : bool isreindex,
3053 : : bool parallel,
3054 : : bool progress)
3055 : : {
3056 : : IndexBuildResult *stats;
3057 : : Oid save_userid;
3058 : : int save_sec_context;
3059 : : int save_nestlevel;
3060 : :
3061 : : /*
3062 : : * sanity checks
3063 : : */
3064 [ - + ]: 33949 : Assert(RelationIsValid(indexRelation));
337 peter@eisentraut.org 3065 [ - + ]: 33949 : Assert(indexRelation->rd_indam);
3066 [ - + ]: 33949 : Assert(indexRelation->rd_indam->ambuild);
3067 [ - + ]: 33949 : Assert(indexRelation->rd_indam->ambuildempty);
3068 : :
3069 : : /*
3070 : : * Determine worker process details for parallel CREATE INDEX. Currently,
3071 : : * only btree, GIN, and BRIN have support for parallel builds.
3072 : : *
3073 : : * Note that planner considers parallel safety for us.
3074 : : */
3128 rhaas@postgresql.org 3075 [ + + + - ]: 33949 : if (parallel && IsNormalProcessingMode() &&
993 tomas.vondra@postgre 3076 [ + + ]: 24338 : indexRelation->rd_indam->amcanbuildparallel)
3128 rhaas@postgresql.org 3077 : 22814 : indexInfo->ii_ParallelWorkers =
3078 : 22814 : plan_create_index_workers(RelationGetRelid(heapRelation),
3079 : : RelationGetRelid(indexRelation));
3080 : :
3081 [ + + ]: 33949 : if (indexInfo->ii_ParallelWorkers == 0)
3082 [ + + ]: 33818 : ereport(DEBUG1,
3083 : : (errmsg_internal("building index \"%s\" on table \"%s\" serially",
3084 : : RelationGetRelationName(indexRelation),
3085 : : RelationGetRelationName(heapRelation))));
3086 : : else
3087 [ - + ]: 131 : ereport(DEBUG1,
3088 : : (errmsg_internal("building index \"%s\" on table \"%s\" with request for %d parallel workers",
3089 : : RelationGetRelationName(indexRelation),
3090 : : RelationGetRelationName(heapRelation),
3091 : : indexInfo->ii_ParallelWorkers)));
3092 : :
3093 : : /*
3094 : : * Switch to the table owner's userid, so that any index functions are run
3095 : : * as that user. Also lock down security-restricted operations and
3096 : : * arrange to make GUC variable changes local to this command.
3097 : : */
6105 tgl@sss.pgh.pa.us 3098 : 33949 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
3099 : 33949 : SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3100 : : save_sec_context | SECURITY_RESTRICTED_OPERATION);
3101 : 33949 : save_nestlevel = NewGUCNestLevel();
906 jdavis@postgresql.or 3102 : 33949 : RestrictSearchPath();
3103 : :
3104 : : /* Set up initial progress report status */
144 alvherre@kurilemu.de 3105 [ + + ]: 33949 : if (progress)
3106 : : {
2032 peter@eisentraut.org 3107 : 21311 : const int progress_index[] = {
3108 : : PROGRESS_CREATEIDX_PHASE,
3109 : : PROGRESS_CREATEIDX_SUBPHASE,
3110 : : PROGRESS_CREATEIDX_TUPLES_DONE,
3111 : : PROGRESS_CREATEIDX_TUPLES_TOTAL,
3112 : : PROGRESS_SCAN_BLOCKS_DONE,
3113 : : PROGRESS_SCAN_BLOCKS_TOTAL
3114 : : };
3115 : 21311 : const int64 progress_vals[] = {
3116 : : PROGRESS_CREATEIDX_PHASE_BUILD,
3117 : : PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE,
3118 : : 0, 0, 0, 0
3119 : : };
3120 : :
3121 : 21311 : pgstat_progress_update_multi_param(6, progress_index, progress_vals);
3122 : : }
3123 : :
3124 : : /*
3125 : : * Call the access method's build procedure
3126 : : */
2775 andres@anarazel.de 3127 : 33949 : stats = indexRelation->rd_indam->ambuild(heapRelation, indexRelation,
3128 : : indexInfo);
337 peter@eisentraut.org 3129 [ - + ]: 33872 : Assert(stats);
3130 : :
3131 : : /*
3132 : : * If this is an unlogged index, we may need to write out an init fork for
3133 : : * it -- but we must first check whether one already exists. If, for
3134 : : * example, an unlogged relation is truncated in the transaction that
3135 : : * created it, or truncated twice in a subsequent transaction, the
3136 : : * relfilenumber won't change, and nothing needs to be done here.
3137 : : */
4303 alvherre@alvh.no-ip. 3138 [ + + ]: 33872 : if (indexRelation->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
1872 tgl@sss.pgh.pa.us 3139 [ + - ]: 146 : !smgrexists(RelationGetSmgr(indexRelation), INIT_FORKNUM))
3140 : : {
3141 : 146 : smgrcreate(RelationGetSmgr(indexRelation), INIT_FORKNUM, false);
1148 heikki.linnakangas@i 3142 : 146 : log_smgrcreate(&indexRelation->rd_locator, INIT_FORKNUM);
2775 andres@anarazel.de 3143 : 146 : indexRelation->rd_indam->ambuildempty(indexRelation);
3144 : : }
3145 : :
3146 : : /*
3147 : : * If we found any potentially broken HOT chains, mark the index as not
3148 : : * being usable until the current transaction is below the event horizon.
3149 : : * See src/backend/access/heap/README.HOT for discussion. While it might
3150 : : * become safe to use the index earlier based on actual cleanup activity
3151 : : * and other active transactions, the test for that would be much more
3152 : : * complex and would require some form of blocking, so keep it simple and
3153 : : * fast by just using the current transaction.
3154 : : *
3155 : : * However, when reindexing an existing index, we should do nothing here.
3156 : : * Any HOT chains that are broken with respect to the index must predate
3157 : : * the index's original creation, so there is no need to change the
3158 : : * index's usability horizon. Moreover, we *must not* try to change the
3159 : : * index's pg_index entry while reindexing pg_index itself, and this
3160 : : * optimization nicely prevents that. The more complex rules needed for a
3161 : : * reindex are handled separately after this function returns.
3162 : : *
3163 : : * We also need not set indcheckxmin during a concurrent index build,
3164 : : * because we won't set indisvalid true until all transactions that care
3165 : : * about the broken HOT chains are gone.
3166 : : *
3167 : : * Therefore, this code path can only be taken during non-concurrent
3168 : : * CREATE INDEX. Thus the fact that heap_update will set the pg_index
3169 : : * tuple's xmin doesn't matter, because that tuple was created in the
3170 : : * current transaction anyway. That also means we don't need to worry
3171 : : * about any concurrent readers of the tuple; no other transaction can see
3172 : : * it yet.
3173 : : */
1087 tmunro@postgresql.or 3174 [ + + ]: 33872 : if (indexInfo->ii_BrokenHotChain &&
3730 kgrittn@postgresql.o 3175 [ + + ]: 25 : !isreindex &&
5020 tgl@sss.pgh.pa.us 3176 [ + - ]: 20 : !indexInfo->ii_Concurrent)
3177 : : {
6860 bruce@momjian.us 3178 : 20 : Oid indexId = RelationGetRelid(indexRelation);
3179 : : Relation pg_index;
3180 : : HeapTuple indexTuple;
3181 : : Form_pg_index indexForm;
3182 : :
2775 andres@anarazel.de 3183 : 20 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
3184 : :
6038 rhaas@postgresql.org 3185 : 20 : indexTuple = SearchSysCacheCopy1(INDEXRELID,
3186 : : ObjectIdGetDatum(indexId));
6916 tgl@sss.pgh.pa.us 3187 [ - + ]: 20 : if (!HeapTupleIsValid(indexTuple))
6916 tgl@sss.pgh.pa.us 3188 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for index %u", indexId);
6916 tgl@sss.pgh.pa.us 3189 :CBC 20 : indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3190 : :
3191 : : /* If it's a new index, indcheckxmin shouldn't be set ... */
5609 3192 [ - + ]: 20 : Assert(!indexForm->indcheckxmin);
3193 : :
6916 3194 : 20 : indexForm->indcheckxmin = true;
3495 alvherre@alvh.no-ip. 3195 : 20 : CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3196 : :
6916 tgl@sss.pgh.pa.us 3197 : 20 : heap_freetuple(indexTuple);
2775 andres@anarazel.de 3198 : 20 : table_close(pg_index, RowExclusiveLock);
3199 : : }
3200 : :
3201 : : /*
3202 : : * Update heap and index pg_class rows
3203 : : */
7414 tgl@sss.pgh.pa.us 3204 : 33872 : index_update_stats(heapRelation,
3205 : : true,
3206 : : stats->heap_tuples);
3207 : :
3208 : 33872 : index_update_stats(indexRelation,
3209 : : false,
3210 : : stats->index_tuples);
3211 : :
3212 : : /* Make the updated catalog row versions visible */
3213 : 33872 : CommandCounterIncrement();
3214 : :
3215 : : /*
3216 : : * If it's for an exclusion constraint, make a second pass over the heap
3217 : : * to verify that the constraint is satisfied. We must not do this until
3218 : : * the index is fully valid. (Broken HOT chains shouldn't matter, though;
3219 : : * see comments for IndexCheckExclusion.)
3220 : : */
5562 3221 [ + + ]: 33872 : if (indexInfo->ii_ExclusionOps != NULL)
3222 : 691 : IndexCheckExclusion(heapRelation, indexRelation, indexInfo);
3223 : :
3224 : : /* Roll back any GUC changes executed by index functions */
3225 : 33832 : AtEOXact_GUC(false, save_nestlevel);
3226 : :
3227 : : /* Restore userid and security context */
3228 : 33832 : SetUserIdAndSecContext(save_userid, save_sec_context);
9174 3229 : 33832 : }
3230 : :
3231 : : /*
3232 : : * IndexCheckExclusion - verify that a new exclusion constraint is satisfied
3233 : : *
3234 : : * When creating an exclusion constraint, we first build the index normally
3235 : : * and then rescan the heap to check for conflicts. We assume that we only
3236 : : * need to validate tuples that are live according to an up-to-date snapshot,
3237 : : * and that these were correctly indexed even in the presence of broken HOT
3238 : : * chains. This should be OK since we are holding at least ShareLock on the
3239 : : * table, meaning there can be no uncommitted updates from other transactions.
3240 : : * (Note: that wouldn't necessarily work for system catalogs, since many
3241 : : * operations release write lock early on the system catalogs.)
3242 : : */
3243 : : static void
6107 3244 : 691 : IndexCheckExclusion(Relation heapRelation,
3245 : : Relation indexRelation,
3246 : : IndexInfo *indexInfo)
3247 : : {
3248 : : TableScanDesc scan;
3249 : : Datum values[INDEX_MAX_KEYS];
3250 : : bool isnull[INDEX_MAX_KEYS];
3251 : : ExprState *predicate;
3252 : : TupleTableSlot *slot;
3253 : : EState *estate;
3254 : : ExprContext *econtext;
3255 : : Snapshot snapshot;
3256 : :
3257 : : /*
3258 : : * If we are reindexing the target index, mark it as no longer being
3259 : : * reindexed, to forestall an Assert in index_beginscan when we try to use
3260 : : * the index for probes. This is OK because the index is now fully valid.
3261 : : */
5562 3262 [ + + ]: 691 : if (ReindexIsCurrentlyProcessingIndex(RelationGetRelid(indexRelation)))
3263 : 52 : ResetReindexProcessing();
3264 : :
3265 : : /*
3266 : : * Need an EState for evaluation of index expressions and partial-index
3267 : : * predicates. Also a slot to hold the current tuple.
3268 : : */
6107 3269 : 691 : estate = CreateExecutorState();
3270 [ - + ]: 691 : econtext = GetPerTupleExprContext(estate);
2726 andres@anarazel.de 3271 : 691 : slot = table_slot_create(heapRelation, NULL);
3272 : :
3273 : : /* Arrange for econtext's scan tuple to be the tuple under test */
6107 tgl@sss.pgh.pa.us 3274 : 691 : econtext->ecxt_scantuple = slot;
3275 : :
3276 : : /* Set up execution state for predicate, if any. */
3453 andres@anarazel.de 3277 : 691 : predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
3278 : :
3279 : : /*
3280 : : * Scan all live tuples in the base relation.
3281 : : */
4804 rhaas@postgresql.org 3282 : 691 : snapshot = RegisterSnapshot(GetLatestSnapshot());
2726 andres@anarazel.de 3283 : 691 : scan = table_beginscan_strat(heapRelation, /* relation */
3284 : : snapshot, /* snapshot */
3285 : : 0, /* number of keys */
3286 : : NULL, /* scan key */
3287 : : true, /* buffer access strategy OK */
3288 : : true); /* syncscan OK */
3289 : :
3290 [ + + ]: 965 : while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
3291 : : {
6107 tgl@sss.pgh.pa.us 3292 [ - + ]: 314 : CHECK_FOR_INTERRUPTS();
3293 : :
3294 : : /*
3295 : : * In a partial index, ignore tuples that don't satisfy the predicate.
3296 : : */
3453 andres@anarazel.de 3297 [ + + ]: 314 : if (predicate != NULL)
3298 : : {
3299 [ + + ]: 22 : if (!ExecQual(predicate, econtext))
6107 tgl@sss.pgh.pa.us 3300 : 8 : continue;
3301 : : }
3302 : :
3303 : : /*
3304 : : * Extract index column values, including computing expressions.
3305 : : */
3306 : 306 : FormIndexDatum(indexInfo,
3307 : : slot,
3308 : : estate,
3309 : : values,
3310 : : isnull);
3311 : :
3312 : : /*
3313 : : * Check that this tuple has no conflicts.
3314 : : */
3315 : 306 : check_exclusion_constraint(heapRelation,
3316 : : indexRelation, indexInfo,
2726 andres@anarazel.de 3317 : 306 : &(slot->tts_tid), values, isnull,
3318 : : estate, true);
3319 : :
3320 : 266 : MemoryContextReset(econtext->ecxt_per_tuple_memory);
3321 : : }
3322 : :
3323 : 651 : table_endscan(scan);
4804 rhaas@postgresql.org 3324 : 651 : UnregisterSnapshot(snapshot);
3325 : :
6107 tgl@sss.pgh.pa.us 3326 : 651 : ExecDropSingleTupleTableSlot(slot);
3327 : :
3328 : 651 : FreeExecutorState(estate);
3329 : :
3330 : : /* These may have been pointing to the now-gone estate */
3331 : 651 : indexInfo->ii_ExpressionsState = NIL;
3453 andres@anarazel.de 3332 : 651 : indexInfo->ii_PredicateState = NULL;
6107 tgl@sss.pgh.pa.us 3333 : 651 : }
3334 : :
3335 : : /*
3336 : : * validate_index - support code for concurrent index builds
3337 : : *
3338 : : * We do a concurrent index build by first inserting the catalog entry for the
3339 : : * index via index_create(), marking it not indisready and not indisvalid.
3340 : : * Then we commit our transaction and start a new one, then we wait for all
3341 : : * transactions that could have been modifying the table to terminate. Now
3342 : : * we know that any subsequently-started transactions will see the index and
3343 : : * honor its constraints on HOT updates; so while existing HOT-chains might
3344 : : * be broken with respect to the index, no currently live tuple will have an
3345 : : * incompatible HOT update done to it. We now build the index normally via
3346 : : * index_build(), while holding a weak lock that allows concurrent
3347 : : * insert/update/delete. Also, we index only tuples that are valid
3348 : : * as of the start of the scan (see table_index_build_scan), whereas a normal
3349 : : * build takes care to include recently-dead tuples. This is OK because
3350 : : * we won't mark the index valid until all transactions that might be able
3351 : : * to see those tuples are gone. The reason for doing that is to avoid
3352 : : * bogus unique-index failures due to concurrent UPDATEs (we might see
3353 : : * different versions of the same row as being valid when we pass over them,
3354 : : * if we used HeapTupleSatisfiesVacuum). This leaves us with an index that
3355 : : * does not contain any tuples added to the table while we built the index.
3356 : : *
3357 : : * Next, we mark the index "indisready" (but still not "indisvalid") and
3358 : : * commit the second transaction and start a third. Again we wait for all
3359 : : * transactions that could have been modifying the table to terminate. Now
3360 : : * we know that any subsequently-started transactions will see the index and
3361 : : * insert their new tuples into it. We then take a new reference snapshot
3362 : : * which is passed to validate_index(). Any tuples that are valid according
3363 : : * to this snap, but are not in the index, must be added to the index.
3364 : : * (Any tuples committed live after the snap will be inserted into the
3365 : : * index by their originating transaction. Any tuples committed dead before
3366 : : * the snap need not be indexed, because we will wait out all transactions
3367 : : * that might care about them before we mark the index valid.)
3368 : : *
3369 : : * validate_index() works by first gathering all the TIDs currently in the
3370 : : * index, using a bulkdelete callback that just stores the TIDs and doesn't
3371 : : * ever say "delete it". (This should be faster than a plain indexscan;
3372 : : * also, not all index AMs support full-index indexscan.) Then we sort the
3373 : : * TIDs, and finally scan the table doing a "merge join" against the TID list
3374 : : * to see which tuples are missing from the index. Thus we will ensure that
3375 : : * all tuples valid according to the reference snapshot are in the index.
3376 : : *
3377 : : * Building a unique index this way is tricky: we might try to insert a
3378 : : * tuple that is already dead or is in process of being deleted, and we
3379 : : * mustn't have a uniqueness failure against an updated version of the same
3380 : : * row. We could try to check the tuple to see if it's already dead and tell
3381 : : * index_insert() not to do the uniqueness check, but that still leaves us
3382 : : * with a race condition against an in-progress update. To handle that,
3383 : : * we expect the index AM to recheck liveness of the to-be-inserted tuple
3384 : : * before it declares a uniqueness error.
3385 : : *
3386 : : * After completing validate_index(), we wait until all transactions that
3387 : : * were alive at the time of the reference snapshot are gone; this is
3388 : : * necessary to be sure there are none left with a transaction snapshot
3389 : : * older than the reference (and hence possibly able to see tuples we did
3390 : : * not index). Then we mark the index "indisvalid" and commit. Subsequent
3391 : : * transactions will be able to use it for queries.
3392 : : *
3393 : : * Doing two full table scans is a brute-force strategy. We could try to be
3394 : : * cleverer, eg storing new tuples in a special area of the table (perhaps
3395 : : * making the table append-only by setting use_fsm). However that would
3396 : : * add yet more locking issues.
3397 : : */
3398 : : void
7307 3399 : 404 : validate_index(Oid heapId, Oid indexId, Snapshot snapshot)
3400 : : {
3401 : : Relation heapRelation,
3402 : : indexRelation;
3403 : : IndexInfo *indexInfo;
3404 : : IndexVacuumInfo ivinfo;
3405 : : ValidateIndexState state;
3406 : : Oid save_userid;
3407 : : int save_sec_context;
3408 : : int save_nestlevel;
3409 : :
3410 : : {
2032 peter@eisentraut.org 3411 : 404 : const int progress_index[] = {
3412 : : PROGRESS_CREATEIDX_PHASE,
3413 : : PROGRESS_CREATEIDX_TUPLES_DONE,
3414 : : PROGRESS_CREATEIDX_TUPLES_TOTAL,
3415 : : PROGRESS_SCAN_BLOCKS_DONE,
3416 : : PROGRESS_SCAN_BLOCKS_TOTAL
3417 : : };
3418 : 404 : const int64 progress_vals[] = {
3419 : : PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN,
3420 : : 0, 0, 0, 0
3421 : : };
3422 : :
3423 : 404 : pgstat_progress_update_multi_param(5, progress_index, progress_vals);
3424 : : }
3425 : :
3426 : : /* Open and lock the parent heap relation */
2775 andres@anarazel.de 3427 : 404 : heapRelation = table_open(heapId, ShareUpdateExclusiveLock);
3428 : :
3429 : : /*
3430 : : * Switch to the table owner's userid, so that any index functions are run
3431 : : * as that user. Also lock down security-restricted operations and
3432 : : * arrange to make GUC variable changes local to this command.
3433 : : */
1571 noah@leadboat.com 3434 : 404 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
3435 : 404 : SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3436 : : save_sec_context | SECURITY_RESTRICTED_OPERATION);
3437 : 404 : save_nestlevel = NewGUCNestLevel();
906 jdavis@postgresql.or 3438 : 404 : RestrictSearchPath();
3439 : :
7307 tgl@sss.pgh.pa.us 3440 : 404 : indexRelation = index_open(indexId, RowExclusiveLock);
3441 : :
3442 : : /*
3443 : : * Fetch info needed for index_insert. (You might think this should be
3444 : : * passed in from DefineIndex, but its copy is long gone due to having
3445 : : * been built in a previous transaction.)
3446 : : */
3447 : 404 : indexInfo = BuildIndexInfo(indexRelation);
3448 : :
3449 : : /* mark build is concurrent just for consistency */
3450 : 404 : indexInfo->ii_Concurrent = true;
3451 : :
3452 : : /*
3453 : : * Scan the index and gather up all the TIDs into a tuplesort object.
3454 : : */
3455 : 404 : ivinfo.index = indexRelation;
1242 pg@bowt.ie 3456 : 404 : ivinfo.heaprel = heapRelation;
6365 tgl@sss.pgh.pa.us 3457 : 404 : ivinfo.analyze_only = false;
2704 alvherre@alvh.no-ip. 3458 : 404 : ivinfo.report_progress = true;
6291 tgl@sss.pgh.pa.us 3459 : 404 : ivinfo.estimated_count = true;
7307 3460 : 404 : ivinfo.message_level = DEBUG2;
6291 3461 : 404 : ivinfo.num_heap_tuples = heapRelation->rd_rel->reltuples;
7029 3462 : 404 : ivinfo.strategy = NULL;
3463 : :
3464 : : /*
3465 : : * Encode TIDs as int8 values for the sort, rather than directly sorting
3466 : : * item pointers. This can be significantly faster, primarily because TID
3467 : : * is a pass-by-reference type on all platforms, whereas int8 is
3468 : : * pass-by-value on most platforms.
3469 : : */
3907 rhaas@postgresql.org 3470 : 404 : state.tuplesort = tuplesort_begin_datum(INT8OID, Int8LessOperator,
3471 : : InvalidOid, false,
3472 : : maintenance_work_mem,
3473 : : NULL, TUPLESORT_NONE);
7307 tgl@sss.pgh.pa.us 3474 : 404 : state.htups = state.itups = state.tups_inserted = 0;
3475 : :
3476 : : /* ambulkdelete updates progress metrics */
3477 : 404 : (void) index_bulk_delete(&ivinfo, NULL,
3478 : : validate_index_callback, &state);
3479 : :
3480 : : /* Execute the sort */
3481 : : {
2032 peter@eisentraut.org 3482 : 404 : const int progress_index[] = {
3483 : : PROGRESS_CREATEIDX_PHASE,
3484 : : PROGRESS_SCAN_BLOCKS_DONE,
3485 : : PROGRESS_SCAN_BLOCKS_TOTAL
3486 : : };
3487 : 404 : const int64 progress_vals[] = {
3488 : : PROGRESS_CREATEIDX_PHASE_VALIDATE_SORT,
3489 : : 0, 0
3490 : : };
3491 : :
3492 : 404 : pgstat_progress_update_multi_param(3, progress_index, progress_vals);
3493 : : }
7307 tgl@sss.pgh.pa.us 3494 : 404 : tuplesort_performsort(state.tuplesort);
3495 : :
3496 : : /*
3497 : : * Now scan the heap and "merge" it with the index
3498 : : */
2704 alvherre@alvh.no-ip. 3499 : 404 : pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
3500 : : PROGRESS_CREATEIDX_PHASE_VALIDATE_TABLESCAN);
2710 andres@anarazel.de 3501 : 404 : table_index_validate_scan(heapRelation,
3502 : : indexRelation,
3503 : : indexInfo,
3504 : : snapshot,
3505 : : &state);
3506 : :
3507 : : /* Done with tuplesort object */
7307 tgl@sss.pgh.pa.us 3508 : 404 : tuplesort_end(state.tuplesort);
3509 : :
3510 : : /* Make sure to release resources cached in indexInfo (if needed). */
860 tomas.vondra@postgre 3511 : 404 : index_insert_cleanup(indexRelation, indexInfo);
3512 : :
7307 tgl@sss.pgh.pa.us 3513 [ - + ]: 404 : elog(DEBUG2,
3514 : : "validate_index found %.0f heap tuples, %.0f index tuples; inserted %.0f missing tuples",
3515 : : state.htups, state.itups, state.tups_inserted);
3516 : :
3517 : : /* Roll back any GUC changes executed by index functions */
6105 3518 : 404 : AtEOXact_GUC(false, save_nestlevel);
3519 : :
3520 : : /* Restore userid and security context */
3521 : 404 : SetUserIdAndSecContext(save_userid, save_sec_context);
3522 : :
3523 : : /* Close rels, but keep locks */
7307 3524 : 404 : index_close(indexRelation, NoLock);
2775 andres@anarazel.de 3525 : 404 : table_close(heapRelation, NoLock);
7307 tgl@sss.pgh.pa.us 3526 : 404 : }
3527 : :
3528 : : /*
3529 : : * validate_index_callback - bulkdelete callback to collect the index TIDs
3530 : : */
3531 : : static bool
3532 : 144661 : validate_index_callback(ItemPointer itemptr, void *opaque)
3533 : : {
2710 andres@anarazel.de 3534 : 144661 : ValidateIndexState *state = (ValidateIndexState *) opaque;
3907 rhaas@postgresql.org 3535 : 144661 : int64 encoded = itemptr_encode(itemptr);
3536 : :
3537 : 144661 : tuplesort_putdatum(state->tuplesort, Int64GetDatum(encoded), false);
7307 tgl@sss.pgh.pa.us 3538 : 144661 : state->itups += 1;
3539 : 144661 : return false; /* never actually delete anything */
3540 : : }
3541 : :
3542 : : /*
3543 : : * index_set_state_flags - adjust pg_index state flags
3544 : : *
3545 : : * This is used during CREATE/DROP INDEX CONCURRENTLY to adjust the pg_index
3546 : : * flags that denote the index's state.
3547 : : *
3548 : : * Note that CatalogTupleUpdate() sends a cache invalidation message for the
3549 : : * tuple, so other sessions will hear about the update as soon as we commit.
3550 : : */
3551 : : void
5020 3552 : 916 : index_set_state_flags(Oid indexId, IndexStateFlagsAction action)
3553 : : {
3554 : : Relation pg_index;
3555 : : HeapTuple indexTuple;
3556 : : Form_pg_index indexForm;
3557 : :
3558 : : /* Open pg_index and fetch a writable copy of the index's tuple */
2775 andres@anarazel.de 3559 : 916 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
3560 : :
5020 tgl@sss.pgh.pa.us 3561 : 916 : indexTuple = SearchSysCacheCopy1(INDEXRELID,
3562 : : ObjectIdGetDatum(indexId));
3563 [ - + ]: 916 : if (!HeapTupleIsValid(indexTuple))
5020 tgl@sss.pgh.pa.us 3564 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for index %u", indexId);
5020 tgl@sss.pgh.pa.us 3565 :CBC 916 : indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3566 : :
3567 : : /* Perform the requested state change on the copy */
3568 [ + + + + : 916 : switch (action)
- ]
3569 : : {
3570 : 404 : case INDEX_CREATE_SET_READY:
3571 : : /* Set indisready during a CREATE INDEX CONCURRENTLY sequence */
3572 [ - + ]: 404 : Assert(indexForm->indislive);
3573 [ - + ]: 404 : Assert(!indexForm->indisready);
3574 [ - + ]: 404 : Assert(!indexForm->indisvalid);
3575 : 404 : indexForm->indisready = true;
3576 : 404 : break;
3577 : 78 : case INDEX_CREATE_SET_VALID:
3578 : : /* Set indisvalid during a CREATE INDEX CONCURRENTLY sequence */
3579 [ - + ]: 78 : Assert(indexForm->indislive);
3580 [ - + ]: 78 : Assert(indexForm->indisready);
3581 [ - + ]: 78 : Assert(!indexForm->indisvalid);
3582 : 78 : indexForm->indisvalid = true;
3583 : 78 : break;
3584 : 54 : case INDEX_DROP_CLEAR_VALID:
3585 : :
3586 : : /*
3587 : : * Clear indisvalid during a DROP INDEX CONCURRENTLY sequence
3588 : : *
3589 : : * If indisready == true we leave it set so the index still gets
3590 : : * maintained by active transactions. We only need to ensure that
3591 : : * indisvalid is false. (We don't assert that either is initially
3592 : : * true, though, since we want to be able to retry a DROP INDEX
3593 : : * CONCURRENTLY that failed partway through.)
3594 : : *
3595 : : * Note: the CLUSTER logic assumes that indisclustered cannot be
3596 : : * set on any invalid index, so clear that flag too. For
3597 : : * cleanliness, also clear indisreplident.
3598 : : */
3599 : 54 : indexForm->indisvalid = false;
3600 : 54 : indexForm->indisclustered = false;
2188 michael@paquier.xyz 3601 : 54 : indexForm->indisreplident = false;
5020 tgl@sss.pgh.pa.us 3602 : 54 : break;
3603 : 380 : case INDEX_DROP_SET_DEAD:
3604 : :
3605 : : /*
3606 : : * Clear indisready/indislive during DROP INDEX CONCURRENTLY
3607 : : *
3608 : : * We clear both indisready and indislive, because we not only
3609 : : * want to stop updates, we want to prevent sessions from touching
3610 : : * the index at all.
3611 : : */
3612 [ - + ]: 380 : Assert(!indexForm->indisvalid);
2188 michael@paquier.xyz 3613 [ - + ]: 380 : Assert(!indexForm->indisclustered);
3614 [ - + ]: 380 : Assert(!indexForm->indisreplident);
5020 tgl@sss.pgh.pa.us 3615 : 380 : indexForm->indisready = false;
3616 : 380 : indexForm->indislive = false;
3617 : 380 : break;
3618 : : }
3619 : :
3620 : : /* ... and update it */
2173 michael@paquier.xyz 3621 : 916 : CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3622 : :
2775 andres@anarazel.de 3623 : 916 : table_close(pg_index, RowExclusiveLock);
5020 tgl@sss.pgh.pa.us 3624 : 916 : }
3625 : :
3626 : :
3627 : : /*
3628 : : * IndexGetRelation: given an index's relation OID, get the OID of the
3629 : : * relation it is an index on. Uses the system cache.
3630 : : */
3631 : : Oid
5384 rhaas@postgresql.org 3632 : 37324 : IndexGetRelation(Oid indexId, bool missing_ok)
3633 : : {
3634 : : HeapTuple tuple;
3635 : : Form_pg_index index;
3636 : : Oid result;
3637 : :
6038 3638 : 37324 : tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexId));
9776 tgl@sss.pgh.pa.us 3639 [ + + ]: 37324 : if (!HeapTupleIsValid(tuple))
3640 : : {
5384 rhaas@postgresql.org 3641 [ + - ]: 16 : if (missing_ok)
3642 : 16 : return InvalidOid;
8438 tgl@sss.pgh.pa.us 3643 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for index %u", indexId);
3644 : : }
9776 tgl@sss.pgh.pa.us 3645 :CBC 37308 : index = (Form_pg_index) GETSTRUCT(tuple);
3646 [ - + ]: 37308 : Assert(index->indexrelid == indexId);
3647 : :
9415 3648 : 37308 : result = index->indrelid;
3649 : 37308 : ReleaseSysCache(tuple);
3650 : 37308 : return result;
3651 : : }
3652 : :
3653 : : /*
3654 : : * reindex_index - This routine is used to recreate a single index
3655 : : */
3656 : : void
997 michael@paquier.xyz 3657 : 4963 : reindex_index(const ReindexStmt *stmt, Oid indexId,
3658 : : bool skip_constraint_checks, char persistence,
3659 : : const ReindexParams *params)
3660 : : {
3661 : : Relation iRel,
3662 : : heapRelation;
3663 : : Oid heapId;
3664 : : Oid save_userid;
3665 : : int save_sec_context;
3666 : : int save_nestlevel;
3667 : : IndexInfo *indexInfo;
51 nathan@postgresql.or 3668 :GNC 4963 : bool skipped_constraint = false;
3669 : : PGRUsage ru0;
2047 michael@paquier.xyz 3670 :CBC 4963 : bool progress = ((params->options & REINDEXOPT_REPORT_PROGRESS) != 0);
2030 3671 : 4963 : bool set_tablespace = false;
3672 : :
4122 fujii@postgresql.org 3673 : 4963 : pg_rusage_init(&ru0);
3674 : :
3675 : : /*
3676 : : * Open and lock the parent heap relation. ShareLock is sufficient since
3677 : : * we only need to be sure no schema or data changes are going on.
3678 : : */
2185 michael@paquier.xyz 3679 : 4963 : heapId = IndexGetRelation(indexId,
2047 3680 : 4963 : (params->options & REINDEXOPT_MISSING_OK) != 0);
3681 : : /* if relation is missing, leave */
2185 3682 [ - + ]: 4963 : if (!OidIsValid(heapId))
2185 michael@paquier.xyz 3683 :UBC 0 : return;
3684 : :
2047 michael@paquier.xyz 3685 [ + + ]:CBC 4963 : if ((params->options & REINDEXOPT_MISSING_OK) != 0)
2185 3686 : 1175 : heapRelation = try_table_open(heapId, ShareLock);
3687 : : else
3688 : 3788 : heapRelation = table_open(heapId, ShareLock);
3689 : :
3690 : : /* if relation is gone, leave */
3691 [ - + ]: 4963 : if (!heapRelation)
2185 michael@paquier.xyz 3692 :UBC 0 : return;
3693 : :
3694 : : /*
3695 : : * Switch to the table owner's userid, so that any index functions are run
3696 : : * as that user. Also lock down security-restricted operations and
3697 : : * arrange to make GUC variable changes local to this command.
3698 : : */
1571 noah@leadboat.com 3699 :CBC 4963 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
3700 : 4963 : SetUserIdAndSecContext(heapRelation->rd_rel->relowner,
3701 : : save_sec_context | SECURITY_RESTRICTED_OPERATION);
3702 : 4963 : save_nestlevel = NewGUCNestLevel();
906 jdavis@postgresql.or 3703 : 4963 : RestrictSearchPath();
3704 : :
2540 alvherre@alvh.no-ip. 3705 [ + + ]: 4963 : if (progress)
3706 : : {
2012 michael@paquier.xyz 3707 : 1793 : const int progress_cols[] = {
3708 : : PROGRESS_CREATEIDX_COMMAND,
3709 : : PROGRESS_CREATEIDX_INDEX_OID
3710 : : };
3711 : 1793 : const int64 progress_vals[] = {
3712 : : PROGRESS_CREATEIDX_COMMAND_REINDEX,
3713 : : indexId
3714 : : };
3715 : :
2540 alvherre@alvh.no-ip. 3716 : 1793 : pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX,
3717 : : heapId);
2012 michael@paquier.xyz 3718 : 1793 : pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
3719 : : }
3720 : :
3721 : : /*
3722 : : * Open the target index relation and get an exclusive lock on it, to
3723 : : * ensure that no one else is touching this particular index.
3724 : : */
952 3725 [ + + ]: 4963 : if ((params->options & REINDEXOPT_MISSING_OK) != 0)
3726 : 1175 : iRel = try_index_open(indexId, AccessExclusiveLock);
3727 : : else
3728 : 3788 : iRel = index_open(indexId, AccessExclusiveLock);
3729 : :
3730 : : /* if index relation is gone, leave */
3731 [ - + ]: 4963 : if (!iRel)
3732 : : {
3733 : : /* Roll back any GUC changes */
952 michael@paquier.xyz 3734 :UBC 0 : AtEOXact_GUC(false, save_nestlevel);
3735 : :
3736 : : /* Restore userid and security context */
3737 : 0 : SetUserIdAndSecContext(save_userid, save_sec_context);
3738 : :
3739 : : /* Close parent heap relation, but keep locks */
3740 : 0 : table_close(heapRelation, NoLock);
3741 : 0 : return;
3742 : : }
3743 : :
2540 alvherre@alvh.no-ip. 3744 [ + + ]:CBC 4963 : if (progress)
3745 : 1793 : pgstat_progress_update_param(PROGRESS_CREATEIDX_ACCESS_METHOD_OID,
3746 : 1793 : iRel->rd_rel->relam);
3747 : :
3748 : : /*
3749 : : * If a statement is available, telling that this comes from a REINDEX
3750 : : * command, collect the index for event triggers.
3751 : : */
997 michael@paquier.xyz 3752 [ + + ]: 4963 : if (stmt)
3753 : : {
3754 : : ObjectAddress address;
3755 : :
3756 : 1793 : ObjectAddressSet(address, RelationRelationId, indexId);
3757 : 1793 : EventTriggerCollectSimpleCommand(address,
3758 : : InvalidObjectAddress,
3759 : : (const Node *) stmt);
3760 : : }
3761 : :
3762 : : /*
3763 : : * Partitioned indexes should never get processed here, as they have no
3764 : : * physical storage.
3765 : : */
3142 alvherre@alvh.no-ip. 3766 [ - + ]: 4963 : if (iRel->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
2179 michael@paquier.xyz 3767 [ # # ]:UBC 0 : elog(ERROR, "cannot reindex partitioned index \"%s.%s\"",
3768 : : get_namespace_name(RelationGetNamespace(iRel)),
3769 : : RelationGetRelationName(iRel));
3770 : :
3771 : : /*
3772 : : * Don't allow reindex on temp tables of other backends ... their local
3773 : : * buffer manager is not going to cope.
3774 : : */
6358 tgl@sss.pgh.pa.us 3775 [ + + - + ]:CBC 4963 : if (RELATION_IS_OTHER_TEMP(iRel))
6784 tgl@sss.pgh.pa.us 3776 [ # # ]:UBC 0 : ereport(ERROR,
3777 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3778 : : errmsg("cannot reindex temporary tables of other sessions")));
3779 : :
3780 : : /*
3781 : : * Don't allow reindex of an invalid index on TOAST table. This is a
3782 : : * leftover from a failed REINDEX CONCURRENTLY, and if rebuilt it would
3783 : : * not be possible to drop it anymore.
3784 : : */
2361 michael@paquier.xyz 3785 [ + + ]:CBC 4963 : if (IsToastNamespace(RelationGetNamespace(iRel)) &&
3786 [ - + ]: 1648 : !get_index_isvalid(indexId))
2361 michael@paquier.xyz 3787 [ # # ]:UBC 0 : ereport(ERROR,
3788 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3789 : : errmsg("cannot reindex invalid index on TOAST table")));
3790 : :
3791 : : /*
3792 : : * System relations cannot be moved even if allow_system_table_mods is
3793 : : * enabled to keep things consistent with the concurrent case where all
3794 : : * the indexes of a relation are processed in series, including indexes of
3795 : : * toast relations.
3796 : : *
3797 : : * Note that this check is not part of CheckRelationTableSpaceMove() as it
3798 : : * gets used for ALTER TABLE SET TABLESPACE that could cascade across
3799 : : * toast relations.
3800 : : */
2030 michael@paquier.xyz 3801 [ + + + + ]:CBC 5003 : if (OidIsValid(params->tablespaceOid) &&
3802 : 40 : IsSystemRelation(iRel))
3803 [ + - ]: 22 : ereport(ERROR,
3804 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3805 : : errmsg("cannot move system relation \"%s\"",
3806 : : RelationGetRelationName(iRel))));
3807 : :
3808 : : /* Check if the tablespace of this index needs to be changed */
3809 [ + + + + ]: 4955 : if (OidIsValid(params->tablespaceOid) &&
3810 : 18 : CheckRelationTableSpaceMove(iRel, params->tablespaceOid))
3811 : 9 : set_tablespace = true;
3812 : :
3813 : : /*
3814 : : * Also check for active uses of the index in the current transaction; we
3815 : : * don't want to reindex underneath an open indexscan.
3816 : : */
6784 tgl@sss.pgh.pa.us 3817 : 4937 : CheckTableNotInUse(iRel, "REINDEX INDEX");
3818 : :
3819 : : /* Set new tablespace, if requested */
2030 michael@paquier.xyz 3820 [ + + ]: 4937 : if (set_tablespace)
3821 : : {
3822 : : /* Update its pg_class row */
3823 : 9 : SetRelationTableSpace(iRel, params->tablespaceOid, InvalidOid);
3824 : :
3825 : : /*
3826 : : * Schedule unlinking of the old index storage at transaction commit.
3827 : : */
3828 : 9 : RelationDropStorage(iRel);
1513 rhaas@postgresql.org 3829 : 9 : RelationAssumeNewRelfilelocator(iRel);
3830 : :
3831 : : /* Make sure the reltablespace change is visible */
2030 michael@paquier.xyz 3832 : 9 : CommandCounterIncrement();
3833 : : }
3834 : :
3835 : : /*
3836 : : * All predicate locks on the index are about to be made invalid. Promote
3837 : : * them to relation locks on the heap.
3838 : : */
5559 heikki.linnakangas@i 3839 : 4937 : TransferPredicateLocksToHeapRelation(iRel);
3840 : :
3841 : : /* Fetch info needed for index_build */
2677 andres@anarazel.de 3842 : 4937 : indexInfo = BuildIndexInfo(iRel);
3843 : :
3844 : : /* If requested, skip checking uniqueness/exclusion constraints */
3845 [ + + ]: 4937 : if (skip_constraint_checks)
3846 : : {
3847 [ + + - + ]: 2668 : if (indexInfo->ii_Unique || indexInfo->ii_ExclusionOps != NULL)
3848 : 2240 : skipped_constraint = true;
3849 : 2668 : indexInfo->ii_Unique = false;
3850 : 2668 : indexInfo->ii_ExclusionOps = NULL;
3851 : 2668 : indexInfo->ii_ExclusionProcs = NULL;
3852 : 2668 : indexInfo->ii_ExclusionStrats = NULL;
3853 : : }
3854 : :
3855 : : /* Suppress use of the target index while rebuilding it */
2319 tgl@sss.pgh.pa.us 3856 : 4937 : SetReindexProcessing(heapId, indexId);
3857 : :
3858 : : /* Create a new physical relation for the index */
1513 rhaas@postgresql.org 3859 : 4937 : RelationSetNewRelfilenumber(iRel, persistence);
3860 : :
3861 : : /* Initialize the index and rebuild */
3862 : : /* Note: we do not need to re-establish pkey setting */
144 alvherre@kurilemu.de 3863 : 4937 : index_build(heapRelation, iRel, indexInfo, true, true, progress);
3864 : :
3865 : : /* Re-allow use of target index */
2319 tgl@sss.pgh.pa.us 3866 : 4921 : ResetReindexProcessing();
3867 : :
3868 : : /*
3869 : : * If the index is marked invalid/not-ready/dead (ie, it's from a failed
3870 : : * CREATE INDEX CONCURRENTLY, or a DROP INDEX CONCURRENTLY failed midway),
3871 : : * and we didn't skip a uniqueness check, we can now mark it valid. This
3872 : : * allows REINDEX to be used to clean up in such cases.
3873 : : *
3874 : : * We can also reset indcheckxmin, because we have now done a
3875 : : * non-concurrent index build, *except* in the case where index_build
3876 : : * found some still-broken HOT chains. If it did, and we don't have to
3877 : : * change any of the other flags, we just leave indcheckxmin alone (note
3878 : : * that index_build won't have changed it, because this is a reindex).
3879 : : * This is okay and desirable because not updating the tuple leaves the
3880 : : * index's usability horizon (recorded as the tuple's xmin value) the same
3881 : : * as it was.
3882 : : *
3883 : : * But, if the index was invalid/not-ready/dead and there were broken HOT
3884 : : * chains, we had better force indcheckxmin true, because the normal
3885 : : * argument that the HOT chains couldn't conflict with the index is
3886 : : * suspect for an invalid index. (A conflict is definitely possible if
3887 : : * the index was dead. It probably shouldn't happen otherwise, but let's
3888 : : * be conservative.) In this case advancing the usability horizon is
3889 : : * appropriate.
3890 : : *
3891 : : * Another reason for avoiding unnecessary updates here is that while
3892 : : * reindexing pg_index itself, we must not try to update tuples in it.
3893 : : * pg_index's indexes should always have these flags in their clean state,
3894 : : * so that won't happen.
3895 : : */
5609 3896 [ + + ]: 4921 : if (!skipped_constraint)
3897 : : {
3898 : : Relation pg_index;
3899 : : HeapTuple indexTuple;
3900 : : Form_pg_index indexForm;
3901 : : bool index_bad;
3902 : :
2775 andres@anarazel.de 3903 : 2681 : pg_index = table_open(IndexRelationId, RowExclusiveLock);
3904 : :
6038 rhaas@postgresql.org 3905 : 2681 : indexTuple = SearchSysCacheCopy1(INDEXRELID,
3906 : : ObjectIdGetDatum(indexId));
6045 tgl@sss.pgh.pa.us 3907 [ - + ]: 2681 : if (!HeapTupleIsValid(indexTuple))
6045 tgl@sss.pgh.pa.us 3908 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for index %u", indexId);
6045 tgl@sss.pgh.pa.us 3909 :CBC 2681 : indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
3910 : :
5020 3911 : 8039 : index_bad = (!indexForm->indisvalid ||
3912 [ + + + - ]: 5358 : !indexForm->indisready ||
3913 [ - + ]: 2677 : !indexForm->indislive);
3914 [ + + ]: 2681 : if (index_bad ||
1087 tmunro@postgresql.or 3915 [ - + - - ]: 2677 : (indexForm->indcheckxmin && !indexInfo->ii_BrokenHotChain))
3916 : : {
3917 [ + - ]: 4 : if (!indexInfo->ii_BrokenHotChain)
6045 tgl@sss.pgh.pa.us 3918 : 4 : indexForm->indcheckxmin = false;
1087 tmunro@postgresql.or 3919 [ # # ]:UBC 0 : else if (index_bad)
5608 tgl@sss.pgh.pa.us 3920 : 0 : indexForm->indcheckxmin = true;
5608 tgl@sss.pgh.pa.us 3921 :CBC 4 : indexForm->indisvalid = true;
3922 : 4 : indexForm->indisready = true;
5020 3923 : 4 : indexForm->indislive = true;
3495 alvherre@alvh.no-ip. 3924 : 4 : CatalogTupleUpdate(pg_index, &indexTuple->t_self, indexTuple);
3925 : :
3926 : : /*
3927 : : * Invalidate the relcache for the table, so that after we commit
3928 : : * all sessions will refresh the table's index list. This ensures
3929 : : * that if anyone misses seeing the pg_index row during this
3930 : : * update, they'll refresh their list before attempting any update
3931 : : * on the table.
3932 : : */
5020 tgl@sss.pgh.pa.us 3933 : 4 : CacheInvalidateRelcache(heapRelation);
3934 : : }
3935 : :
2775 andres@anarazel.de 3936 : 2681 : table_close(pg_index, RowExclusiveLock);
3937 : : }
3938 : :
3939 : : /* Log what we did */
2047 michael@paquier.xyz 3940 [ + + ]: 4921 : if ((params->options & REINDEXOPT_VERBOSE) != 0)
4122 fujii@postgresql.org 3941 [ + - ]: 8 : ereport(INFO,
3942 : : (errmsg("index \"%s\" was reindexed",
3943 : : get_rel_name(indexId)),
3944 : : errdetail_internal("%s",
3945 : : pg_rusage_show(&ru0))));
3946 : :
3947 : : /* Roll back any GUC changes executed by index functions */
1571 noah@leadboat.com 3948 : 4921 : AtEOXact_GUC(false, save_nestlevel);
3949 : :
3950 : : /* Restore userid and security context */
3951 : 4921 : SetUserIdAndSecContext(save_userid, save_sec_context);
3952 : :
3953 : : /* Close rels, but keep locks */
7332 tgl@sss.pgh.pa.us 3954 : 4921 : index_close(iRel, NoLock);
2775 andres@anarazel.de 3955 : 4921 : table_close(heapRelation, NoLock);
3956 : :
1571 noah@leadboat.com 3957 [ + + ]: 4921 : if (progress)
3958 : 1763 : pgstat_progress_end_command();
3959 : : }
3960 : :
3961 : : /*
3962 : : * reindex_relation - This routine is used to recreate all indexes
3963 : : * of a relation (and optionally its toast relation too, if any).
3964 : : *
3965 : : * "flags" is a bitmask that can include any combination of these bits:
3966 : : *
3967 : : * REINDEX_REL_PROCESS_TOAST: if true, process the toast table too (if any).
3968 : : *
3969 : : * REINDEX_REL_SUPPRESS_INDEX_USE: if true, the relation was just completely
3970 : : * rebuilt by an operation such as VACUUM FULL or CLUSTER, and therefore its
3971 : : * indexes are inconsistent with it. This makes things tricky if the relation
3972 : : * is a system catalog that we might consult during the reindexing. To deal
3973 : : * with that case, we mark all of the indexes as pending rebuild so that they
3974 : : * won't be trusted until rebuilt. The caller is required to call us *without*
3975 : : * having made the rebuilt table visible by doing CommandCounterIncrement;
3976 : : * we'll do CCI after having collected the index list. (This way we can still
3977 : : * use catalog indexes while collecting the list.)
3978 : : *
3979 : : * REINDEX_REL_CHECK_CONSTRAINTS: if true, recheck unique and exclusion
3980 : : * constraint conditions, else don't. To avoid deadlocks, VACUUM FULL or
3981 : : * CLUSTER on a system catalog must omit this flag. REINDEX should be used to
3982 : : * rebuild an index if constraint inconsistency is suspected. For optimal
3983 : : * performance, other callers should include the flag only after transforming
3984 : : * the data in a manner that risks a change in constraint validity.
3985 : : *
3986 : : * REINDEX_REL_FORCE_INDEXES_UNLOGGED: if true, set the persistence of the
3987 : : * rebuilt indexes to unlogged.
3988 : : *
3989 : : * REINDEX_REL_FORCE_INDEXES_PERMANENT: if true, set the persistence of the
3990 : : * rebuilt indexes to permanent.
3991 : : *
3992 : : * Returns true if any indexes were rebuilt (including toast table's index
3993 : : * when relevant). Note that a CommandCounterIncrement will occur after each
3994 : : * index rebuild.
3995 : : */
3996 : : bool
997 michael@paquier.xyz 3997 : 5877 : reindex_relation(const ReindexStmt *stmt, Oid relid, int flags,
3998 : : const ReindexParams *params)
3999 : : {
4000 : : Relation rel;
4001 : : Oid toast_relid;
4002 : : List *indexIds;
4003 : : char persistence;
944 4004 : 5877 : bool result = false;
4005 : : ListCell *indexId;
4006 : : int i;
4007 : :
4008 : : /*
4009 : : * Open and lock the relation. ShareLock is sufficient since we only need
4010 : : * to prevent schema and data changes in it. The lock level used here
4011 : : * should match ReindexTable().
4012 : : */
2047 4013 [ + + ]: 5877 : if ((params->options & REINDEXOPT_MISSING_OK) != 0)
2185 4014 : 693 : rel = try_table_open(relid, ShareLock);
4015 : : else
4016 : 5184 : rel = table_open(relid, ShareLock);
4017 : :
4018 : : /* if relation is gone, leave */
4019 [ - + ]: 5877 : if (!rel)
2185 michael@paquier.xyz 4020 :UBC 0 : return false;
4021 : :
4022 : : /*
4023 : : * Partitioned tables should never get processed here, as they have no
4024 : : * physical storage.
4025 : : */
3142 alvherre@alvh.no-ip. 4026 [ - + ]:CBC 5877 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2179 michael@paquier.xyz 4027 [ # # ]:UBC 0 : elog(ERROR, "cannot reindex partitioned table \"%s.%s\"",
4028 : : get_namespace_name(RelationGetNamespace(rel)),
4029 : : RelationGetRelationName(rel));
4030 : :
8373 tgl@sss.pgh.pa.us 4031 :CBC 5877 : toast_relid = rel->rd_rel->reltoastrelid;
4032 : :
4033 : : /*
4034 : : * Get the list of index OIDs for this relation. (We trust the relcache
4035 : : * to get this with a sequential scan if ignoring system indexes.)
4036 : : */
4037 : 5877 : indexIds = RelationGetIndexList(rel);
4038 : :
2319 4039 [ + + ]: 5877 : if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
4040 : : {
4041 : : /* Suppress use of all the indexes until they are rebuilt */
4042 : 1444 : SetReindexPending(indexIds);
4043 : :
4044 : : /*
4045 : : * Make the new heap contents visible --- now things might be
4046 : : * inconsistent!
4047 : : */
4048 : 1444 : CommandCounterIncrement();
4049 : : }
4050 : :
4051 : : /*
4052 : : * Reindex the toast table, if any, before the main table.
4053 : : *
4054 : : * This helps in cases where a corruption in the toast table's index would
4055 : : * otherwise error and stop REINDEX TABLE command when it tries to fetch a
4056 : : * toasted datum. This way. the toast table's index is rebuilt and fixed
4057 : : * before it is used for reindexing the main table.
4058 : : *
4059 : : * It is critical to call reindex_relation() *after* the call to
4060 : : * RelationGetIndexList() returning the list of indexes on the relation,
4061 : : * because reindex_relation() will call CommandCounterIncrement() after
4062 : : * every reindex_index(). See REINDEX_REL_SUPPRESS_INDEX_USE for more
4063 : : * details.
4064 : : */
944 michael@paquier.xyz 4065 [ + + + + ]: 5877 : if ((flags & REINDEX_REL_PROCESS_TOAST) && OidIsValid(toast_relid))
4066 : : {
4067 : : /*
4068 : : * Note that this should fail if the toast relation is missing, so
4069 : : * reset REINDEXOPT_MISSING_OK. Even if a new tablespace is set for
4070 : : * the parent relation, the indexes on its toast table are not moved.
4071 : : * This rule is enforced by setting tablespaceOid to InvalidOid.
4072 : : */
4073 : 1630 : ReindexParams newparams = *params;
4074 : :
4075 : 1630 : newparams.options &= ~(REINDEXOPT_MISSING_OK);
4076 : 1630 : newparams.tablespaceOid = InvalidOid;
4077 : 1630 : result |= reindex_relation(stmt, toast_relid, flags, &newparams);
4078 : : }
4079 : :
4080 : : /*
4081 : : * Compute persistence of indexes: same as that of owning rel, unless
4082 : : * caller specified otherwise.
4083 : : */
2319 tgl@sss.pgh.pa.us 4084 [ + + ]: 5877 : if (flags & REINDEX_REL_FORCE_INDEXES_UNLOGGED)
4085 : 25 : persistence = RELPERSISTENCE_UNLOGGED;
4086 [ + + ]: 5852 : else if (flags & REINDEX_REL_FORCE_INDEXES_PERMANENT)
4087 : 1366 : persistence = RELPERSISTENCE_PERMANENT;
4088 : : else
4089 : 4486 : persistence = rel->rd_rel->relpersistence;
4090 : :
4091 : : /* Reindex all the indexes. */
4092 : 5877 : i = 1;
4093 [ + + + + : 10712 : foreach(indexId, indexIds)
+ + ]
4094 : : {
4095 : 4868 : Oid indexOid = lfirst_oid(indexId);
4096 : 4868 : Oid indexNamespaceId = get_rel_namespace(indexOid);
4097 : :
4098 : : /*
4099 : : * Skip any invalid indexes on a TOAST table. These can only be
4100 : : * duplicate leftovers from a failed REINDEX CONCURRENTLY, and if
4101 : : * rebuilt it would not be possible to drop them anymore.
4102 : : */
4103 [ + + ]: 4868 : if (IsToastNamespace(indexNamespaceId) &&
4104 [ - + ]: 1643 : !get_index_isvalid(indexOid))
4105 : : {
2319 tgl@sss.pgh.pa.us 4106 [ # # ]:UBC 0 : ereport(WARNING,
4107 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4108 : : errmsg("cannot reindex invalid index \"%s.%s\" on TOAST table, skipping",
4109 : : get_namespace_name(indexNamespaceId),
4110 : : get_rel_name(indexOid))));
4111 : :
4112 : : /*
4113 : : * Remove this invalid toast index from the reindex pending list,
4114 : : * as it is skipped here due to the hard failure that would happen
4115 : : * in reindex_index(), should we try to process it.
4116 : : */
699 michael@paquier.xyz 4117 [ # # ]: 0 : if (flags & REINDEX_REL_SUPPRESS_INDEX_USE)
4118 : 0 : RemoveReindexPending(indexOid);
2319 tgl@sss.pgh.pa.us 4119 : 0 : continue;
4120 : : }
4121 : :
997 michael@paquier.xyz 4122 :CBC 4868 : reindex_index(stmt, indexOid, !(flags & REINDEX_REL_CHECK_CONSTRAINTS),
4123 : : persistence, params);
4124 : :
2319 tgl@sss.pgh.pa.us 4125 : 4835 : CommandCounterIncrement();
4126 : :
4127 : : /* Index should no longer be in the pending list */
4128 [ - + ]: 4835 : Assert(!ReindexIsProcessingIndex(indexOid));
4129 : :
4130 : : /* Set index rebuild count */
170 alvherre@kurilemu.de 4131 : 4835 : pgstat_progress_update_param(PROGRESS_REPACK_INDEX_REBUILD_COUNT,
4132 : : i);
2319 tgl@sss.pgh.pa.us 4133 : 4835 : i++;
4134 : : }
4135 : :
4136 : : /*
4137 : : * Close rel, but continue to hold the lock.
4138 : : */
2775 andres@anarazel.de 4139 : 5844 : table_close(rel, NoLock);
4140 : :
944 michael@paquier.xyz 4141 : 5844 : result |= (indexIds != NIL);
4142 : :
8373 tgl@sss.pgh.pa.us 4143 : 5844 : return result;
4144 : : }
4145 : :
4146 : :
4147 : : /* ----------------------------------------------------------------
4148 : : * System index reindexing support
4149 : : *
4150 : : * When we are busy reindexing a system index, this code provides support
4151 : : * for preventing catalog lookups from using that index. We also make use
4152 : : * of this to catch attempted uses of user indexes during reindexing of
4153 : : * those indexes. This information is propagated to parallel workers;
4154 : : * attempting to change it during a parallel operation is not permitted.
4155 : : * ----------------------------------------------------------------
4156 : : */
4157 : :
4158 : : static Oid currentlyReindexedHeap = InvalidOid;
4159 : : static Oid currentlyReindexedIndex = InvalidOid;
4160 : : static List *pendingReindexedIndexes = NIL;
4161 : : static int reindexingNestLevel = 0;
4162 : :
4163 : : /*
4164 : : * ReindexIsProcessingHeap
4165 : : * True if heap specified by OID is currently being reindexed.
4166 : : */
4167 : : bool
6045 tgl@sss.pgh.pa.us 4168 :UBC 0 : ReindexIsProcessingHeap(Oid heapOid)
4169 : : {
4170 : 0 : return heapOid == currentlyReindexedHeap;
4171 : : }
4172 : :
4173 : : /*
4174 : : * ReindexIsCurrentlyProcessingIndex
4175 : : * True if index specified by OID is currently being reindexed.
4176 : : */
4177 : : static bool
5562 tgl@sss.pgh.pa.us 4178 :CBC 691 : ReindexIsCurrentlyProcessingIndex(Oid indexOid)
4179 : : {
4180 : 691 : return indexOid == currentlyReindexedIndex;
4181 : : }
4182 : :
4183 : : /*
4184 : : * ReindexIsProcessingIndex
4185 : : * True if index specified by OID is currently being reindexed,
4186 : : * or should be treated as invalid because it is awaiting reindex.
4187 : : */
4188 : : bool
6045 4189 : 27545215 : ReindexIsProcessingIndex(Oid indexOid)
4190 : : {
4191 [ + + + + ]: 55082663 : return indexOid == currentlyReindexedIndex ||
4192 : 27537448 : list_member_oid(pendingReindexedIndexes, indexOid);
4193 : : }
4194 : :
4195 : : /*
4196 : : * SetReindexProcessing
4197 : : * Set flag that specified heap/index are being reindexed.
4198 : : */
4199 : : static void
4200 : 4937 : SetReindexProcessing(Oid heapOid, Oid indexOid)
4201 : : {
4202 [ + - - + ]: 4937 : Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
4203 : : /* Reindexing is not re-entrant. */
4204 [ - + ]: 4937 : if (OidIsValid(currentlyReindexedHeap))
6045 tgl@sss.pgh.pa.us 4205 [ # # ]:UBC 0 : elog(ERROR, "cannot reindex while reindexing");
6045 tgl@sss.pgh.pa.us 4206 :CBC 4937 : currentlyReindexedHeap = heapOid;
4207 : 4937 : currentlyReindexedIndex = indexOid;
4208 : : /* Index is no longer "pending" reindex. */
5562 4209 : 4937 : RemoveReindexPending(indexOid);
4210 : : /* This may have been set already, but in case it isn't, do so now. */
2319 4211 : 4937 : reindexingNestLevel = GetCurrentTransactionNestLevel();
6045 4212 : 4937 : }
4213 : :
4214 : : /*
4215 : : * ResetReindexProcessing
4216 : : * Unset reindexing status.
4217 : : */
4218 : : static void
4219 : 4973 : ResetReindexProcessing(void)
4220 : : {
4221 : 4973 : currentlyReindexedHeap = InvalidOid;
4222 : 4973 : currentlyReindexedIndex = InvalidOid;
4223 : : /* reindexingNestLevel remains set till end of (sub)transaction */
4224 : 4973 : }
4225 : :
4226 : : /*
4227 : : * SetReindexPending
4228 : : * Mark the given indexes as pending reindex.
4229 : : *
4230 : : * NB: we assume that the current memory context stays valid throughout.
4231 : : */
4232 : : static void
4233 : 1444 : SetReindexPending(List *indexes)
4234 : : {
4235 : : /* Reindexing is not re-entrant. */
4236 [ - + ]: 1444 : if (pendingReindexedIndexes)
6045 tgl@sss.pgh.pa.us 4237 [ # # ]:UBC 0 : elog(ERROR, "cannot reindex while reindexing");
3142 rhaas@postgresql.org 4238 [ - + ]:CBC 1444 : if (IsInParallelMode())
3142 rhaas@postgresql.org 4239 [ # # ]:UBC 0 : elog(ERROR, "cannot modify reindex state during a parallel operation");
6045 tgl@sss.pgh.pa.us 4240 :CBC 1444 : pendingReindexedIndexes = list_copy(indexes);
2319 4241 : 1444 : reindexingNestLevel = GetCurrentTransactionNestLevel();
6045 4242 : 1444 : }
4243 : :
4244 : : /*
4245 : : * RemoveReindexPending
4246 : : * Remove the given index from the pending list.
4247 : : */
4248 : : static void
4249 : 4937 : RemoveReindexPending(Oid indexOid)
4250 : : {
3142 rhaas@postgresql.org 4251 [ - + ]: 4937 : if (IsInParallelMode())
3142 rhaas@postgresql.org 4252 [ # # ]:UBC 0 : elog(ERROR, "cannot modify reindex state during a parallel operation");
6045 tgl@sss.pgh.pa.us 4253 :CBC 4937 : pendingReindexedIndexes = list_delete_oid(pendingReindexedIndexes,
4254 : : indexOid);
4255 : 4937 : }
4256 : :
4257 : : /*
4258 : : * ResetReindexState
4259 : : * Clear all reindexing state during (sub)transaction abort.
4260 : : */
4261 : : void
2319 4262 : 41269 : ResetReindexState(int nestLevel)
4263 : : {
4264 : : /*
4265 : : * Because reindexing is not re-entrant, we don't need to cope with nested
4266 : : * reindexing states. We just need to avoid messing up the outer-level
4267 : : * state in case a subtransaction fails within a REINDEX. So checking the
4268 : : * current nest level against that of the reindex operation is sufficient.
4269 : : */
4270 [ + + ]: 41269 : if (reindexingNestLevel >= nestLevel)
4271 : : {
4272 : 989 : currentlyReindexedHeap = InvalidOid;
4273 : 989 : currentlyReindexedIndex = InvalidOid;
4274 : :
4275 : : /*
4276 : : * We needn't try to release the contents of pendingReindexedIndexes;
4277 : : * that list should be in a transaction-lifespan context, so it will
4278 : : * go away automatically.
4279 : : */
4280 : 989 : pendingReindexedIndexes = NIL;
4281 : :
4282 : 989 : reindexingNestLevel = 0;
4283 : : }
6045 4284 : 41269 : }
4285 : :
4286 : : /*
4287 : : * EstimateReindexStateSpace
4288 : : * Estimate space needed to pass reindex state to parallel workers.
4289 : : */
4290 : : Size
3142 rhaas@postgresql.org 4291 : 679 : EstimateReindexStateSpace(void)
4292 : : {
4293 : : return offsetof(SerializedReindexState, pendingReindexedIndexes)
4294 : 679 : + mul_size(sizeof(Oid), list_length(pendingReindexedIndexes));
4295 : : }
4296 : :
4297 : : /*
4298 : : * SerializeReindexState
4299 : : * Serialize reindex state for parallel workers.
4300 : : */
4301 : : void
4302 : 679 : SerializeReindexState(Size maxsize, char *start_address)
4303 : : {
4304 : 679 : SerializedReindexState *sistate = (SerializedReindexState *) start_address;
4305 : 679 : int c = 0;
4306 : : ListCell *lc;
4307 : :
4308 : 679 : sistate->currentlyReindexedHeap = currentlyReindexedHeap;
4309 : 679 : sistate->currentlyReindexedIndex = currentlyReindexedIndex;
4310 : 679 : sistate->numPendingReindexedIndexes = list_length(pendingReindexedIndexes);
4311 [ - + - - : 679 : foreach(lc, pendingReindexedIndexes)
- + ]
3142 rhaas@postgresql.org 4312 :UBC 0 : sistate->pendingReindexedIndexes[c++] = lfirst_oid(lc);
3142 rhaas@postgresql.org 4313 :CBC 679 : }
4314 : :
4315 : : /*
4316 : : * RestoreReindexState
4317 : : * Restore reindex state in a parallel worker.
4318 : : */
4319 : : void
1100 peter@eisentraut.org 4320 : 2007 : RestoreReindexState(const void *reindexstate)
4321 : : {
4322 : 2007 : const SerializedReindexState *sistate = (const SerializedReindexState *) reindexstate;
3142 rhaas@postgresql.org 4323 : 2007 : int c = 0;
4324 : : MemoryContext oldcontext;
4325 : :
4326 : 2007 : currentlyReindexedHeap = sistate->currentlyReindexedHeap;
4327 : 2007 : currentlyReindexedIndex = sistate->currentlyReindexedIndex;
4328 : :
4329 [ - + ]: 2007 : Assert(pendingReindexedIndexes == NIL);
4330 : 2007 : oldcontext = MemoryContextSwitchTo(TopMemoryContext);
4331 [ - + ]: 2007 : for (c = 0; c < sistate->numPendingReindexedIndexes; ++c)
3142 rhaas@postgresql.org 4332 :UBC 0 : pendingReindexedIndexes =
4333 : 0 : lappend_oid(pendingReindexedIndexes,
4334 : 0 : sistate->pendingReindexedIndexes[c]);
3142 rhaas@postgresql.org 4335 :CBC 2007 : MemoryContextSwitchTo(oldcontext);
4336 : :
4337 : : /* Note the worker has its own transaction nesting level */
2319 tgl@sss.pgh.pa.us 4338 : 2007 : reindexingNestLevel = GetCurrentTransactionNestLevel();
3142 rhaas@postgresql.org 4339 : 2007 : }
|