Debian Codegraph @

src/backend/executor/nodeIndexonlyscan.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * nodeIndexonlyscan.c
4 * Routines to support index-only scans
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/executor/nodeIndexonlyscan.c
12 *
13 *-------------------------------------------------------------------------
14 */
15 /*
16 * INTERFACE ROUTINES
17 * ExecIndexOnlyScan scans an index
18 * IndexOnlyNext retrieve next tuple
19 * ExecInitIndexOnlyScan creates and initializes state info.
20 * ExecReScanIndexOnlyScan rescans the indexed relation.
21 * ExecEndIndexOnlyScan releases all storage.
22 * ExecIndexOnlyMarkPos marks scan position.
23 * ExecIndexOnlyRestrPos restores scan position.
24 * ExecIndexOnlyScanEstimate estimates DSM space needed for
25 * parallel index-only scan
26 * ExecIndexOnlyScanInitializeDSM initialize DSM for parallel
27 * index-only scan
28 * ExecIndexOnlyScanReInitializeDSM reinitialize DSM for fresh scan
29 * ExecIndexOnlyScanInitializeWorker attach to DSM info in parallel worker
30 */
31 #include "postgres.h"
32
33 #include "access/genam.h"
34 #include "access/htup_details.h"
35 #include "access/relscan.h"
36 #include "access/tableam.h"
37 #include "access/tupdesc.h"
38 #include "access/visibilitymap.h"
39 #include "catalog/pg_type.h"
40 #include "executor/executor.h"
41 #include "executor/nodeIndexonlyscan.h"
42 #include "executor/nodeIndexscan.h"
43 #include "miscadmin.h"
44 #include "storage/bufmgr.h"
45 #include "storage/predicate.h"
46 #include "utils/builtins.h"
47 #include "utils/rel.h"
48
49
50 static TupleTableSlot *IndexOnlyNext(IndexOnlyScanState *node);
51 static void StoreIndexTuple(IndexOnlyScanState *node, TupleTableSlot *slot,
52 IndexScanDesc scandesc);
53
54
55 /* ----------------------------------------------------------------
56 * IndexOnlyNext
57 *
58 * Retrieve a tuple from the IndexOnlyScan node's index.
59 * ----------------------------------------------------------------
60 */
61 static TupleTableSlot *
62 IndexOnlyNext(IndexOnlyScanState *node)
63 {
64 EState *estate;
65 ExprContext *econtext;
66 ScanDirection direction;
67 IndexScanDesc scandesc;
68 TupleTableSlot *slot;
69 ItemPointer tid;
70
71 /*
72 * extract necessary information from index scan node
73 */
74 estate = node->ss.ps.state;
75
76 /*
77 * Determine which direction to scan the index in based on the plan's scan
78 * direction and the current direction of execution.
79 */
80 direction = ScanDirectionCombine(estate->es_direction,
81 ((IndexOnlyScan *) node->ss.ps.plan)->indexorderdir);
82 scandesc = node->ioss_ScanDesc;
83 econtext = node->ss.ps.ps_ExprContext;
84 slot = node->ss.ss_ScanTupleSlot;
85
86 if (scandesc == NULL)
87 {
88 /*
89 * We reach here if the index only scan is not parallel, or if we're
90 * serially executing an index only scan that was planned to be
91 * parallel.
92 */
93 scandesc = index_beginscan(node->ss.ss_currentRelation,
94 node->ioss_RelationDesc,
95 estate->es_snapshot,
96 &node->ioss_Instrument,
97 node->ioss_NumScanKeys,
98 node->ioss_NumOrderByKeys);
99
100 node->ioss_ScanDesc = scandesc;
101
102
103 /* Set it up for index-only scan */
104 node->ioss_ScanDesc->xs_want_itup = true;
105 node->ioss_VMBuffer = InvalidBuffer;
106
107 /*
108 * If no run-time keys to calculate or they are ready, go ahead and
109 * pass the scankeys to the index AM.
110 */
111 if (node->ioss_NumRuntimeKeys == 0 || node->ioss_RuntimeKeysReady)
112 index_rescan(scandesc,
113 node->ioss_ScanKeys,
114 node->ioss_NumScanKeys,
115 node->ioss_OrderByKeys,
116 node->ioss_NumOrderByKeys);
117 }
118
119 /*
120 * OK, now that we have what we need, fetch the next tuple.
121 */
122 while ((tid = index_getnext_tid(scandesc, direction)) != NULL)
123 {
124 bool tuple_from_heap = false;
125
126 CHECK_FOR_INTERRUPTS();
127
128 /*
129 * We can skip the heap fetch if the TID references a heap page on
130 * which all tuples are known visible to everybody. In any case,
131 * we'll use the index tuple not the heap tuple as the data source.
132 *
133 * Note on Memory Ordering Effects: visibilitymap_get_status does not
134 * lock the visibility map buffer, and therefore the result we read
135 * here could be slightly stale. However, it can't be stale enough to
136 * matter.
137 *
138 * We need to detect clearing a VM bit due to an insert right away,
139 * because the tuple is present in the index page but not visible. The
140 * reading of the TID by this scan (using a shared lock on the index
141 * buffer) is serialized with the insert of the TID into the index
142 * (using an exclusive lock on the index buffer). Because the VM bit
143 * is cleared before updating the index, and locking/unlocking of the
144 * index page acts as a full memory barrier, we are sure to see the
145 * cleared bit if we see a recently-inserted TID.
146 *
147 * Deletes do not update the index page (only VACUUM will clear out
148 * the TID), so the clearing of the VM bit by a delete is not
149 * serialized with this test below, and we may see a value that is
150 * significantly stale. However, we don't care about the delete right
151 * away, because the tuple is still visible until the deleting
152 * transaction commits or the statement ends (if it's our
153 * transaction). In either case, the lock on the VM buffer will have
154 * been released (acting as a write barrier) after clearing the bit.
155 * And for us to have a snapshot that includes the deleting
156 * transaction (making the tuple invisible), we must have acquired
157 * ProcArrayLock after that time, acting as a read barrier.
158 *
159 * It's worth going through this complexity to avoid needing to lock
160 * the VM buffer, which could cause significant contention.
161 */
162 if (!VM_ALL_VISIBLE(scandesc->heapRelation,
163 ItemPointerGetBlockNumber(tid),
164 &node->ioss_VMBuffer))
165 {
166 /*
167 * Rats, we have to visit the heap to check visibility.
168 */
169 InstrCountTuples2(node, 1);
170 if (!index_fetch_heap(scandesc, node->ioss_TableSlot))
171 continue; /* no visible tuple, try next index entry */
172
173 ExecClearTuple(node->ioss_TableSlot);
174
175 /*
176 * Only MVCC snapshots are supported here, so there should be no
177 * need to keep following the HOT chain once a visible entry has
178 * been found. If we did want to allow that, we'd need to keep
179 * more state to remember not to call index_getnext_tid next time.
180 */
181 if (scandesc->xs_heap_continue)
182 elog(ERROR, "non-MVCC snapshots are not supported in index-only scans");
183
184 /*
185 * Note: at this point we are holding a pin on the heap page, as
186 * recorded in scandesc->xs_cbuf. We could release that pin now,
187 * but it's not clear whether it's a win to do so. The next index
188 * entry might require a visit to the same heap page.
189 */
190
191 tuple_from_heap = true;
192 }
193
194 /* Fill the scan tuple slot with data from the index */
195 StoreIndexTuple(node, slot, scandesc);
196
197 /*
198 * If the index was lossy, we have to recheck the index quals.
199 */
200 if (scandesc->xs_recheck)
201 {
202 econtext->ecxt_scantuple = slot;
203 if (!ExecQualAndReset(node->recheckqual, econtext))
204 {
205 /* Fails recheck, so drop it and loop back for another */
206 InstrCountFiltered2(node, 1);
207 continue;
208 }
209 }
210
211 /*
212 * We don't currently support rechecking ORDER BY distances. (In
213 * principle, if the index can support retrieval of the originally
214 * indexed value, it should be able to produce an exact distance
215 * calculation too. So it's not clear that adding code here for
216 * recheck/re-sort would be worth the trouble. But we should at least
217 * throw an error if someone tries it.)
218 */
219 if (scandesc->numberOfOrderBys > 0 && scandesc->xs_recheckorderby)
220 ereport(ERROR,
221 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
222 errmsg("lossy distance functions are not supported in index-only scans")));
223
224 /*
225 * If we didn't access the heap, then we'll need to take a predicate
226 * lock explicitly, as if we had. For now we do that at page level.
227 */
228 if (!tuple_from_heap)
229 PredicateLockPage(scandesc->heapRelation,
230 ItemPointerGetBlockNumber(tid),
231 estate->es_snapshot);
232
233 return slot;
234 }
235
236 /*
237 * if we get here it means the index scan failed so we are at the end of
238 * the scan..
239 */
240 return ExecClearTuple(slot);
241 }
242
243 /*
244 * StoreIndexTuple
245 * Fill the slot with the data the index AM returned.
246 *
247 * The data might be provided in either HeapTuple (xs_hitup) or IndexTuple
248 * (xs_itup) format. Conceivably an index AM might fill both fields, in which
249 * case we prefer the heap format, since it's probably a bit cheaper to fill a
250 * slot from.
251 *
252 * At some point this might be generally-useful functionality, but
253 * right now we don't need it elsewhere.
254 */
255 static void
256 StoreIndexTuple(IndexOnlyScanState *node, TupleTableSlot *slot,
257 IndexScanDesc scandesc)
258 {
259 ExecClearTuple(slot);
260
261 /*
262 * We must deform the tuple using the tupdesc the index AM formed it with
263 * (xs_hitupdesc or xs_itupdesc), not the slot's tupdesc. The datums
264 * returned by the index AM must be binary compatible, but the descriptors
265 * may align each column differently in certain rare cases. (Actually,
266 * btree's "name" opclass stores cstring tuples that _aren't_ even binary
267 * compatible, in the strictest sense. We directly handle that here.)
268 */
269 if (scandesc->xs_hitup)
270 {
271 Assert(slot->tts_tupleDescriptor->natts == scandesc->xs_hitupdesc->natts);
272
273 heap_deform_tuple(scandesc->xs_hitup, scandesc->xs_hitupdesc,
274 slot->tts_values, slot->tts_isnull);
275 }
276 else if (scandesc->xs_itup)
277 {
278 Assert(slot->tts_tupleDescriptor->natts == scandesc->xs_itupdesc->natts);
279
280 index_deform_tuple(scandesc->xs_itup, scandesc->xs_itupdesc,
281 slot->tts_values, slot->tts_isnull);
282
283 /*
284 * Copy all name columns stored as cstrings back into a NAMEDATALEN
285 * byte sized allocation. We mark this branch as unlikely as
286 * generally "name" is used only for the system catalogs and this
287 * would have to be a user query running on those or some other user
288 * table with an index on a name column.
289 */
290 if (unlikely(node->ioss_NameCStringAttNums != NULL))
291 {
292 int attcount = node->ioss_NameCStringCount;
293
294 for (int idx = 0; idx < attcount; idx++)
295 {
296 int attnum = node->ioss_NameCStringAttNums[idx];
297 Name name;
298
299 /* skip null Datums */
300 if (slot->tts_isnull[attnum])
301 continue;
302
303 /*
304 * allocate the NAMEDATALEN and copy the datum into that
305 * memory
306 */
307 name = (Name) MemoryContextAlloc(node->ss.ps.ps_ExprContext->ecxt_per_tuple_memory,
308 NAMEDATALEN);
309
310 /* use namestrcpy to zero-pad all trailing bytes */
311 namestrcpy(name, DatumGetCString(slot->tts_values[attnum]));
312 slot->tts_values[attnum] = NameGetDatum(name);
313 }
314 }
315 }
316 else
317 elog(ERROR, "no data returned for index-only scan");
318
319 ExecStoreVirtualTuple(slot);
320 }
321
322 /*
323 * IndexOnlyRecheck -- access method routine to recheck a tuple in EvalPlanQual
324 *
325 * This can't really happen, since an index can't supply CTID which would
326 * be necessary data for any potential EvalPlanQual target relation. If it
327 * did happen, the EPQ code would pass us the wrong data, namely a heap
328 * tuple not an index tuple. So throw an error.
329 */
330 static bool
331 IndexOnlyRecheck(IndexOnlyScanState *node, TupleTableSlot *slot)
332 {
333 elog(ERROR, "EvalPlanQual recheck is not supported in index-only scans");
334 return false; /* keep compiler quiet */
335 }
336
337 /* ----------------------------------------------------------------
338 * ExecIndexOnlyScan(node)
339 * ----------------------------------------------------------------
340 */
341 static TupleTableSlot *
342 ExecIndexOnlyScan(PlanState *pstate)
343 {
344 IndexOnlyScanState *node = castNode(IndexOnlyScanState, pstate);
345
346 /*
347 * If we have runtime keys and they've not already been set up, do it now.
348 */
349 if (node->ioss_NumRuntimeKeys != 0 && !node->ioss_RuntimeKeysReady)
350 ExecReScan((PlanState *) node);
351
352 return ExecScan(&node->ss,
353 (ExecScanAccessMtd) IndexOnlyNext,
354 (ExecScanRecheckMtd) IndexOnlyRecheck);
355 }
356
357 /* ----------------------------------------------------------------
358 * ExecReScanIndexOnlyScan(node)
359 *
360 * Recalculates the values of any scan keys whose value depends on
361 * information known at runtime, then rescans the indexed relation.
362 *
363 * Updating the scan key was formerly done separately in
364 * ExecUpdateIndexScanKeys. Integrating it into ReScan makes
365 * rescans of indices and relations/general streams more uniform.
366 * ----------------------------------------------------------------
367 */
368 void
369 ExecReScanIndexOnlyScan(IndexOnlyScanState *node)
370 {
371 /*
372 * If we are doing runtime key calculations (ie, any of the index key
373 * values weren't simple Consts), compute the new key values. But first,
374 * reset the context so we don't leak memory as each outer tuple is
375 * scanned. Note this assumes that we will recalculate *all* runtime keys
376 * on each call.
377 */
378 if (node->ioss_NumRuntimeKeys != 0)
379 {
380 ExprContext *econtext = node->ioss_RuntimeContext;
381
382 ResetExprContext(econtext);
383 ExecIndexEvalRuntimeKeys(econtext,
384 node->ioss_RuntimeKeys,
385 node->ioss_NumRuntimeKeys);
386 }
387 node->ioss_RuntimeKeysReady = true;
388
389 /* reset index scan */
390 if (node->ioss_ScanDesc)
391 index_rescan(node->ioss_ScanDesc,
392 node->ioss_ScanKeys, node->ioss_NumScanKeys,
393 node->ioss_OrderByKeys, node->ioss_NumOrderByKeys);
394
395 ExecScanReScan(&node->ss);
396 }
397
398
399 /* ----------------------------------------------------------------
400 * ExecEndIndexOnlyScan
401 * ----------------------------------------------------------------
402 */
403 void
404 ExecEndIndexOnlyScan(IndexOnlyScanState *node)
405 {
406 Relation indexRelationDesc;
407 IndexScanDesc indexScanDesc;
408
409 /*
410 * extract information from the node
411 */
412 indexRelationDesc = node->ioss_RelationDesc;
413 indexScanDesc = node->ioss_ScanDesc;
414
415 /* Release VM buffer pin, if any. */
416 if (node->ioss_VMBuffer != InvalidBuffer)
417 {
418 ReleaseBuffer(node->ioss_VMBuffer);
419 node->ioss_VMBuffer = InvalidBuffer;
420 }
421
422 /*
423 * When ending a parallel worker, copy the statistics gathered by the
424 * worker back into shared memory so that it can be picked up by the main
425 * process to report in EXPLAIN ANALYZE
426 */
427 if (node->ioss_SharedInfo != NULL && IsParallelWorker())
428 {
429 IndexScanInstrumentation *winstrument;
430
431 Assert(ParallelWorkerNumber < node->ioss_SharedInfo->num_workers);
432 winstrument = &node->ioss_SharedInfo->winstrument[ParallelWorkerNumber];
433
434 /*
435 * We have to accumulate the stats rather than performing a memcpy.
436 * When a Gather/GatherMerge node finishes it will perform planner
437 * shutdown on the workers. On rescan it will spin up new workers
438 * which will have a new IndexOnlyScanState and zeroed stats.
439 */
440 winstrument->nsearches += node->ioss_Instrument.nsearches;
441 }
442
443 /*
444 * close the index relation (no-op if we didn't open it)
445 */
446 if (indexScanDesc)
447 index_endscan(indexScanDesc);
448 if (indexRelationDesc)
449 index_close(indexRelationDesc, NoLock);
450 }
451
452 /* ----------------------------------------------------------------
453 * ExecIndexOnlyMarkPos
454 *
455 * Note: we assume that no caller attempts to set a mark before having read
456 * at least one tuple. Otherwise, ioss_ScanDesc might still be NULL.
457 * ----------------------------------------------------------------
458 */
459 void
460 ExecIndexOnlyMarkPos(IndexOnlyScanState *node)
461 {
462 EState *estate = node->ss.ps.state;
463 EPQState *epqstate = estate->es_epq_active;
464
465 if (epqstate != NULL)
466 {
467 /*
468 * We are inside an EvalPlanQual recheck. If a test tuple exists for
469 * this relation, then we shouldn't access the index at all. We would
470 * instead need to save, and later restore, the state of the
471 * relsubs_done flag, so that re-fetching the test tuple is possible.
472 * However, given the assumption that no caller sets a mark at the
473 * start of the scan, we can only get here with relsubs_done[i]
474 * already set, and so no state need be saved.
475 */
476 Index scanrelid = ((Scan *) node->ss.ps.plan)->scanrelid;
477
478 Assert(scanrelid > 0);
479 if (epqstate->relsubs_slot[scanrelid - 1] != NULL ||
480 epqstate->relsubs_rowmark[scanrelid - 1] != NULL)
481 {
482 /* Verify the claim above */
483 if (!epqstate->relsubs_done[scanrelid - 1])
484 elog(ERROR, "unexpected ExecIndexOnlyMarkPos call in EPQ recheck");
485 return;
486 }
487 }
488
489 index_markpos(node->ioss_ScanDesc);
490 }
491
492 /* ----------------------------------------------------------------
493 * ExecIndexOnlyRestrPos
494 * ----------------------------------------------------------------
495 */
496 void
497 ExecIndexOnlyRestrPos(IndexOnlyScanState *node)
498 {
499 EState *estate = node->ss.ps.state;
500 EPQState *epqstate = estate->es_epq_active;
501
502 if (estate->es_epq_active != NULL)
503 {
504 /* See comments in ExecIndexMarkPos */
505 Index scanrelid = ((Scan *) node->ss.ps.plan)->scanrelid;
506
507 Assert(scanrelid > 0);
508 if (epqstate->relsubs_slot[scanrelid - 1] != NULL ||
509 epqstate->relsubs_rowmark[scanrelid - 1] != NULL)
510 {
511 /* Verify the claim above */
512 if (!epqstate->relsubs_done[scanrelid - 1])
513 elog(ERROR, "unexpected ExecIndexOnlyRestrPos call in EPQ recheck");
514 return;
515 }
516 }
517
518 index_restrpos(node->ioss_ScanDesc);
519 }
520
521 /* ----------------------------------------------------------------
522 * ExecInitIndexOnlyScan
523 *
524 * Initializes the index scan's state information, creates
525 * scan keys, and opens the base and index relations.
526 *
527 * Note: index scans have 2 sets of state information because
528 * we have to keep track of the base relation and the
529 * index relation.
530 * ----------------------------------------------------------------
531 */
532 IndexOnlyScanState *
533 ExecInitIndexOnlyScan(IndexOnlyScan *node, EState *estate, int eflags)
534 {
535 IndexOnlyScanState *indexstate;
536 Relation currentRelation;
537 Relation indexRelation;
538 LOCKMODE lockmode;
539 TupleDesc tupDesc;
540 int indnkeyatts;
541 int namecount;
542
543 /*
544 * create state structure
545 */
546 indexstate = makeNode(IndexOnlyScanState);
547 indexstate->ss.ps.plan = (Plan *) node;
548 indexstate->ss.ps.state = estate;
549 indexstate->ss.ps.ExecProcNode = ExecIndexOnlyScan;
550
551 /*
552 * Miscellaneous initialization
553 *
554 * create expression context for node
555 */
556 ExecAssignExprContext(estate, &indexstate->ss.ps);
557
558 /*
559 * open the scan relation
560 */
561 currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid, eflags);
562
563 indexstate->ss.ss_currentRelation = currentRelation;
564 indexstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */
565
566 /*
567 * Build the scan tuple type using the indextlist generated by the
568 * planner. We use this, rather than the index's physical tuple
569 * descriptor, because the latter contains storage column types not the
570 * types of the original datums. (It's the AM's responsibility to return
571 * suitable data anyway.)
572 */
573 tupDesc = ExecTypeFromTL(node->indextlist);
574 ExecInitScanTupleSlot(estate, &indexstate->ss, tupDesc,
575 &TTSOpsVirtual);
576
577 /*
578 * We need another slot, in a format that's suitable for the table AM, for
579 * when we need to fetch a tuple from the table for rechecking visibility.
580 */
581 indexstate->ioss_TableSlot =
582 ExecAllocTableSlot(&estate->es_tupleTable,
583 RelationGetDescr(currentRelation),
584 table_slot_callbacks(currentRelation));
585
586 /*
587 * Initialize result type and projection info. The node's targetlist will
588 * contain Vars with varno = INDEX_VAR, referencing the scan tuple.
589 */
590 ExecInitResultTypeTL(&indexstate->ss.ps);
591 ExecAssignScanProjectionInfoWithVarno(&indexstate->ss, INDEX_VAR);
592
593 /*
594 * initialize child expressions
595 *
596 * Note: we don't initialize all of the indexorderby expression, only the
597 * sub-parts corresponding to runtime keys (see below).
598 */
599 indexstate->ss.ps.qual =
600 ExecInitQual(node->scan.plan.qual, (PlanState *) indexstate);
601 indexstate->recheckqual =
602 ExecInitQual(node->recheckqual, (PlanState *) indexstate);
603
604 /*
605 * If we are just doing EXPLAIN (ie, aren't going to run the plan), stop
606 * here. This allows an index-advisor plugin to EXPLAIN a plan containing
607 * references to nonexistent indexes.
608 */
609 if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
610 return indexstate;
611
612 /* Open the index relation. */
613 lockmode = exec_rt_fetch(node->scan.scanrelid, estate)->rellockmode;
614 indexRelation = index_open(node->indexid, lockmode);
615 indexstate->ioss_RelationDesc = indexRelation;
616
617 /*
618 * Initialize index-specific scan state
619 */
620 indexstate->ioss_RuntimeKeysReady = false;
621 indexstate->ioss_RuntimeKeys = NULL;
622 indexstate->ioss_NumRuntimeKeys = 0;
623
624 /*
625 * build the index scan keys from the index qualification
626 */
627 ExecIndexBuildScanKeys((PlanState *) indexstate,
628 indexRelation,
629 node->indexqual,
630 false,
631 &indexstate->ioss_ScanKeys,
632 &indexstate->ioss_NumScanKeys,
633 &indexstate->ioss_RuntimeKeys,
634 &indexstate->ioss_NumRuntimeKeys,
635 NULL, /* no ArrayKeys */
636 NULL);
637
638 /*
639 * any ORDER BY exprs have to be turned into scankeys in the same way
640 */
641 ExecIndexBuildScanKeys((PlanState *) indexstate,
642 indexRelation,
643 node->indexorderby,
644 true,
645 &indexstate->ioss_OrderByKeys,
646 &indexstate->ioss_NumOrderByKeys,
647 &indexstate->ioss_RuntimeKeys,
648 &indexstate->ioss_NumRuntimeKeys,
649 NULL, /* no ArrayKeys */
650 NULL);
651
652 /*
653 * If we have runtime keys, we need an ExprContext to evaluate them. The
654 * node's standard context won't do because we want to reset that context
655 * for every tuple. So, build another context just like the other one...
656 * -tgl 7/11/00
657 */
658 if (indexstate->ioss_NumRuntimeKeys != 0)
659 {
660 ExprContext *stdecontext = indexstate->ss.ps.ps_ExprContext;
661
662 ExecAssignExprContext(estate, &indexstate->ss.ps);
663 indexstate->ioss_RuntimeContext = indexstate->ss.ps.ps_ExprContext;
664 indexstate->ss.ps.ps_ExprContext = stdecontext;
665 }
666 else
667 {
668 indexstate->ioss_RuntimeContext = NULL;
669 }
670
671 indexstate->ioss_NameCStringAttNums = NULL;
672 indnkeyatts = indexRelation->rd_index->indnkeyatts;
673 namecount = 0;
674
675 /*
676 * The "name" type for btree uses text_ops which results in storing
677 * cstrings in the indexed keys rather than names. Here we detect that in
678 * a generic way in case other index AMs want to do the same optimization.
679 * Check for opclasses with an opcintype of NAMEOID and an index tuple
680 * descriptor with CSTRINGOID. If any of these are found, create an array
681 * marking the index attribute number of each of them. StoreIndexTuple()
682 * handles copying the name Datums into a NAMEDATALEN-byte allocation.
683 */
684
685 /* First, count the number of such index keys */
686 for (int attnum = 0; attnum < indnkeyatts; attnum++)
687 {
688 if (TupleDescAttr(indexRelation->rd_att, attnum)->atttypid == CSTRINGOID &&
689 indexRelation->rd_opcintype[attnum] == NAMEOID)
690 namecount++;
691 }
692
693 if (namecount > 0)
694 {
695 int idx = 0;
696
697 /*
698 * Now create an array to mark the attribute numbers of the keys that
699 * need to be converted from cstring to name.
700 */
701 indexstate->ioss_NameCStringAttNums = (AttrNumber *)
702 palloc(sizeof(AttrNumber) * namecount);
703
704 for (int attnum = 0; attnum < indnkeyatts; attnum++)
705 {
706 if (TupleDescAttr(indexRelation->rd_att, attnum)->atttypid == CSTRINGOID &&
707 indexRelation->rd_opcintype[attnum] == NAMEOID)
708 indexstate->ioss_NameCStringAttNums[idx++] = (AttrNumber) attnum;
709 }
710 }
711
712 indexstate->ioss_NameCStringCount = namecount;
713
714 /*
715 * all done.
716 */
717 return indexstate;
718 }
719
720 /* ----------------------------------------------------------------
721 * Parallel Index-only Scan Support
722 * ----------------------------------------------------------------
723 */
724
725 /* ----------------------------------------------------------------
726 * ExecIndexOnlyScanEstimate
727 *
728 * Compute the amount of space we'll need in the parallel
729 * query DSM, and inform pcxt->estimator about our needs.
730 * ----------------------------------------------------------------
731 */
732 void
733 ExecIndexOnlyScanEstimate(IndexOnlyScanState *node,
734 ParallelContext *pcxt)
735 {
736 EState *estate = node->ss.ps.state;
737 bool instrument = (node->ss.ps.instrument != NULL);
738 bool parallel_aware = node->ss.ps.plan->parallel_aware;
739
740 if (!instrument && !parallel_aware)
741 {
742 /* No DSM required by the scan */
743 return;
744 }
745
746 node->ioss_PscanLen = index_parallelscan_estimate(node->ioss_RelationDesc,
747 node->ioss_NumScanKeys,
748 node->ioss_NumOrderByKeys,
749 estate->es_snapshot,
750 instrument, parallel_aware,
751 pcxt->nworkers);
752 shm_toc_estimate_chunk(&pcxt->estimator, node->ioss_PscanLen);
753 shm_toc_estimate_keys(&pcxt->estimator, 1);
754 }
755
756 /* ----------------------------------------------------------------
757 * ExecIndexOnlyScanInitializeDSM
758 *
759 * Set up a parallel index-only scan descriptor.
760 * ----------------------------------------------------------------
761 */
762 void
763 ExecIndexOnlyScanInitializeDSM(IndexOnlyScanState *node,
764 ParallelContext *pcxt)
765 {
766 EState *estate = node->ss.ps.state;
767 ParallelIndexScanDesc piscan;
768 bool instrument = node->ss.ps.instrument != NULL;
769 bool parallel_aware = node->ss.ps.plan->parallel_aware;
770
771 if (!instrument && !parallel_aware)
772 {
773 /* No DSM required by the scan */
774 return;
775 }
776
777 piscan = shm_toc_allocate(pcxt->toc, node->ioss_PscanLen);
778 index_parallelscan_initialize(node->ss.ss_currentRelation,
779 node->ioss_RelationDesc,
780 estate->es_snapshot,
781 instrument, parallel_aware, pcxt->nworkers,
782 &node->ioss_SharedInfo, piscan);
783 shm_toc_insert(pcxt->toc, node->ss.ps.plan->plan_node_id, piscan);
784
785 if (!parallel_aware)
786 {
787 /* Only here to initialize SharedInfo in DSM */
788 return;
789 }
790
791 node->ioss_ScanDesc =
792 index_beginscan_parallel(node->ss.ss_currentRelation,
793 node->ioss_RelationDesc,
794 &node->ioss_Instrument,
795 node->ioss_NumScanKeys,
796 node->ioss_NumOrderByKeys,
797 piscan);
798 node->ioss_ScanDesc->xs_want_itup = true;
799 node->ioss_VMBuffer = InvalidBuffer;
800
801 /*
802 * If no run-time keys to calculate or they are ready, go ahead and pass
803 * the scankeys to the index AM.
804 */
805 if (node->ioss_NumRuntimeKeys == 0 || node->ioss_RuntimeKeysReady)
806 index_rescan(node->ioss_ScanDesc,
807 node->ioss_ScanKeys, node->ioss_NumScanKeys,
808 node->ioss_OrderByKeys, node->ioss_NumOrderByKeys);
809 }
810
811 /* ----------------------------------------------------------------
812 * ExecIndexOnlyScanReInitializeDSM
813 *
814 * Reset shared state before beginning a fresh scan.
815 * ----------------------------------------------------------------
816 */
817 void
818 ExecIndexOnlyScanReInitializeDSM(IndexOnlyScanState *node,
819 ParallelContext *pcxt)
820 {
821 Assert(node->ss.ps.plan->parallel_aware);
822 index_parallelrescan(node->ioss_ScanDesc);
823 }
824
825 /* ----------------------------------------------------------------
826 * ExecIndexOnlyScanInitializeWorker
827 *
828 * Copy relevant information from TOC into planstate.
829 * ----------------------------------------------------------------
830 */
831 void
832 ExecIndexOnlyScanInitializeWorker(IndexOnlyScanState *node,
833 ParallelWorkerContext *pwcxt)
834 {
835 ParallelIndexScanDesc piscan;
836 bool instrument = node->ss.ps.instrument != NULL;
837 bool parallel_aware = node->ss.ps.plan->parallel_aware;
838
839 if (!instrument && !parallel_aware)
840 {
841 /* No DSM required by the scan */
842 return;
843 }
844
845 piscan = shm_toc_lookup(pwcxt->toc, node->ss.ps.plan->plan_node_id, false);
846
847 if (instrument)
848 node->ioss_SharedInfo = (SharedIndexScanInstrumentation *)
849 OffsetToPointer(piscan, piscan->ps_offset_ins);
850
851 if (!parallel_aware)
852 {
853 /* Only here to set up worker node's SharedInfo */
854 return;
855 }
856
857 node->ioss_ScanDesc =
858 index_beginscan_parallel(node->ss.ss_currentRelation,
859 node->ioss_RelationDesc,
860 &node->ioss_Instrument,
861 node->ioss_NumScanKeys,
862 node->ioss_NumOrderByKeys,
863 piscan);
864 node->ioss_ScanDesc->xs_want_itup = true;
865
866 /*
867 * If no run-time keys to calculate or they are ready, go ahead and pass
868 * the scankeys to the index AM.
869 */
870 if (node->ioss_NumRuntimeKeys == 0 || node->ioss_RuntimeKeysReady)
871 index_rescan(node->ioss_ScanDesc,
872 node->ioss_ScanKeys, node->ioss_NumScanKeys,
873 node->ioss_OrderByKeys, node->ioss_NumOrderByKeys);
874 }
875
876 /* ----------------------------------------------------------------
877 * ExecIndexOnlyScanRetrieveInstrumentation
878 *
879 * Transfer index-only scan statistics from DSM to private memory.
880 * ----------------------------------------------------------------
881 */
882 void
883 ExecIndexOnlyScanRetrieveInstrumentation(IndexOnlyScanState *node)
884 {
885 SharedIndexScanInstrumentation *SharedInfo = node->ioss_SharedInfo;
886 size_t size;
887
888 if (SharedInfo == NULL)
889 return;
890
891 /* Create a copy of SharedInfo in backend-local memory */
892 size = offsetof(SharedIndexScanInstrumentation, winstrument) +
893 SharedInfo->num_workers * sizeof(IndexScanInstrumentation);
894 node->ioss_SharedInfo = palloc(size);
895 memcpy(node->ioss_SharedInfo, SharedInfo, size);
896 }