56.2. Функции для индексных методов доступа
Индексный метод доступа должен определить в IndexAmRoutine
следующие функции построения и обслуживания индексов:
IndexBuildResult * ambuild (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo);
Строит новый индекс. Отношение индекса уже физически создано, но пока пусто. Оно должно быть наполнено фиксированными данными, которые требуются методу доступа, и записями для всех кортежей, уже существующих в таблице. Обычно функция ambuild
вызывает IndexBuildHeapScan()
для поиска в таблице существующих кортежей и для вычисления ключей, которые должны вставляться в этот индекс. Эта функция должна возвращать структуру, выделенную вызовом palloc и содержащую статистику нового индекса.
void ambuildempty (Relation indexRelation);
Создаёт пустой индекс и записывает его в слой инициализации (INIT_FORKNUM
) данного отношения. Этот метод вызывается только для нежурналируемых индексов; пустой индекс, записанный в слой инициализации, будет копироваться в основной слой отношения при каждом перезапуске сервера.
bool aminsert (Relation indexRelation, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRelation, IndexUniqueCheck checkUnique, IndexInfo *indexInfo);
Вставляет новый кортеж в существующий индекс. В массивах values
и isnull
передаются значения ключа, которые должны быть проиндексированы, а в heap_tid
— идентификатор индексируемого кортежа (TID). Если метод доступа поддерживает уникальные индексы (флаг amcanunique
установлен), параметр checkUnique
указывает, какая проверка уникальности должна выполняться. Это зависит от того, является ли ограничение уникальности откладываемым; за подробностями обратитесь к Разделу 56.5. Обычно параметр heapRelation
нужен методу доступа только для проверки уникальности (так как он должен обратиться к основным данным, чтобы убедиться в актуальности кортежа).
Возвращаемый функцией булев результат имеет значение, только когда параметр checkUnique
равен UNIQUE_CHECK_PARTIAL
. В этом случае результат TRUE означает, что новая запись признана уникальной, тогда как FALSE означает, что она может быть неуникальной (и требуется назначить отложенную проверку уникальности). В других случаях рекомендуется возвращать постоянный результат FALSE.
Некоторые индексы могут индексировать не все кортежи. Если кортеж не будет индексирован, aminsert
должна просто завершиться, не делая ничего.
Если индексный МД хочет кешировать данные между операциями добавления в индекс в одном операторе SQL, он может выделить память в indexInfo->ii_Context
и сохранить указатель на эти данные в поле indexInfo->ii_AmCache
(которое изначально равно NULL).
IndexBulkDeleteResult * ambulkdelete (IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state);
Удаляет кортеж(и) из индекса. Это операция «массового удаления», которая предположительно будет реализована путём сканирования всего индекса и проверки для каждой записи, должна ли она удаляться. Переданная функция callback
должна вызываться в стиле callback(
с результатом bool, который говорит, должна ли удаляться запись индекса, на которую указывает передаваемый TID. Возвращать эта функция должна NULL или структуру, выделенную вызовом palloc и содержащую статистику результата удаления. NULL можно вернуть, если никакая информация не должна передаваться в TID
, callback_state)amvacuumcleanup
.
Из-за ограничения maintenance_work_mem
процедура ambulkdelete
может вызываться несколько раз, когда удалению подлежит большое количество кортежей. В аргументе stats
передаётся результат предыдущего вызова для данного индекса (при первом вызове в ходе операции VACUUM
он содержит NULL). Это позволяет методу доступа накапливать статистику в процессе всей операции. Обычно ambulkdelete
модифицирует и возвращает одну и ту же структуру, если в stats
передаётся не NULL.
IndexBulkDeleteResult * amvacuumcleanup (IndexVacuumInfo *info, IndexBulkDeleteResult *stats);
Провести уборку после операции VACUUM
(до этого ambulkdelete
могла вызываться несколько или ноль раз). От этой функции не требуется ничего, кроме как выдать статистику по индексу, но она может произвести массовую уборку, например, высвободить пустые страницы индекса. В stats
ей передаётся структура, возвращённая при последнем вызове ambulkdelete
, либо NULL, если ambulkdelete
не вызывалась, так как никакие кортежи удалять не требовалось. Эта функция должна возвращать NULL или структуру, выделенную вызовом palloc. Содержащаяся в этой структуре статистика будет отражена в записи в pg_class
и попадёт в вывод команды VACUUM
, если она выполнялась с указанием VERBOSE
. NULL может возвращаться, если индекс вовсе не изменился в процессе операции VACUUM
, но в противном случае должна возвращаться корректная статистика.
Начиная с PostgreSQL версии 8.4, amvacuumcleanup
также вызывается в конце операции ANALYZE
. В этом случае stats
всегда NULL и любое возвращаемое значение игнорируется. Этот вариант вызова можно распознать, проверив поле info->analyze_only
. При таком вызове методу доступа рекомендуется ничего не делать, кроме как провести уборку после добавления данных, и только в рабочем процессе автоочистки.
bool amcanreturn (Relation indexRelation, int attno);
Проверяет, поддерживается ли сканирование только индекса для заданного столбца, когда для записи индекса возвращаются значения индексируемых столбцов в виде IndexTuple
. Атрибуты нумеруются с 1, то есть для первого столбца attno равен 1. Возвращает true, если такое сканирование поддерживается, а иначе — false. Если индексный метод доступа в принципе не поддерживает сканирование только индекса, в поле amcanreturn
его структуры IndexAmRoutine
можно записать NULL.
void amcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages);
Рассчитывает примерную стоимость сканирования индекса. Эта функция полностью описывается ниже в Разделе 56.6.
bytea * amoptions (ArrayType *reloptions, bool validate);
Разбирает и проверяет массив параметров для индекса. Эта функция вызывается, только когда для индекса задан отличный от NULL массив reloptions. Массив reloptions
состоит из элементов типа text
, содержащих записи вида имя
=
значение
. Данная функция должна получить значение типа bytea
, которое будет скопировано в поле rd_options
записи индекса в relcache. Содержимое этого значения bytea
определяется самим методом доступа; большинство стандартных методов доступа помещают в него структуру StdRdOptions
. Когда параметр validate
равен true, эта функция должна выдать подходящее сообщение об ошибке, если какие-либо параметры нераспознаны или имеют недопустимые значения; если же validate
равен false, некорректные записи должны просто игнорироваться. (В validate
передаётся false, когда параметры уже загружены в pg_catalog
; при этом неверная запись может быть обнаружена, только если в методе доступа поменялись правила обработки параметров, и в этом случае стоит просто игнорировать такие записи.) NULL можно вернуть, когда нужно получить поведение по умолчанию.
bool amproperty (Oid index_oid, int attno, IndexAMProperty prop, const char *propname, bool *res, bool *isnull);
Процедура amproperty
позволяет индексным методам доступа переопределять стандартное поведение функции pg_index_column_has_property
и связанных с ней. Если метод доступа не проявляет никаких особенностей при запросе свойств индексов, поле amproperty
в структуре IndexAmRoutine
может содержать NULL. В противном случае процедура amproperty
будет вызываться с нулевыми параметрами index_oid
и attno
при вызове pg_indexam_has_property
, либо с корректным index_oid
и нулевым attno
при вызове pg_index_has_property
, либо с корректным index_oid
и положительным attno
при вызове pg_index_column_has_property
. В prop
передаётся значение перечисления, указывающее на проверяемое значение, а в propname
— строка с именем свойства. Если код ядра не распознаёт имя свойства, в prop
передаётся AMPROP_UNKNOWN
. Методы доступа могут воспринимать нестандартные имена свойств, проверяя propname
на совпадение (для согласованности с кодом ядра используйте для проверки pg_strcasecmp
); для имён, известных коду ядра, лучше проверять prop
. Если процедура amproperty
возвращает true
, это значит, что она установила результат проверки свойства: она должна задать в *res
возвращаемое логическое значение или установить в *isnull
значение true
, чтобы возвратить NULL. (Перед вызовом обе упомянутые переменные инициализируются значением false
.) Если amproperty
возвращает false
, код ядра переключается на обычную логику определения результата проверки свойства.
Методы доступа, поддерживающие операторы упорядочивания, должны реализовывать проверку свойства AMPROP_DISTANCE_ORDERABLE
, так как код ядра не знает, как это сделать и возвращает NULL. Также может быть полезно реализовать проверку AMPROP_RETURNABLE
, если это можно сделать проще, чем обращаясь к индексу и вызывая amcanreturn
(что делает код ядра по умолчанию). Для всех остальных стандартных свойств поведение ядра по умолчанию можно считать удовлетворительным.
bool amvalidate (Oid opclassoid);
Проверяет записи в каталоге для заданного класса операторов, насколько это может сделать метод доступа. Например, это может включать проверку, все ли необходимые опорные функции реализованы. Функция amvalidate
должна вернуть false, если класс операторов непригоден к использованию. Сообщения о проблеме следует выдать через ereport
.
Цель индекса, конечно, в том, чтобы поддерживать поиск кортежей, соответствующих индексируемому условию WHERE
, по ограничению или ключу поиска. Сканирование индекса описывается более полно ниже, в Разделе 56.3. Индексный метод доступа может поддерживать «простое» сканирование, сканирование по «битовой карте» или и то, и другое. Метод доступа должен или может реализовывать следующие функции, связанные со сканированием:
IndexScanDesc ambeginscan (Relation indexRelation, int nkeys, int norderbys);
Подготавливает метод к сканированию индекса. В параметрах nkeys
и norderbys
задаётся количество операторов условия и сортировки, которые будут задействованы при сканировании; это может быть полезно для выделения памяти. Заметьте, что фактические значения ключей сканирования в этот момент ещё не предоставляются. В результате функция должна выдать структуру, выделенную средствами palloc. В связи с особенностями реализации, метод доступа должен создать эту структуру, вызвав RelationGetIndexScan()
. В большинстве случаев все действия ambeginscan
сводятся только к выполнению этого вызова и, возможно, получению блокировок; всё самое интересное при запуске сканирования индекса происходит в amrescan
.
void amrescan (IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys);
Запускает или перезапускает сканирование индекса, возможно, с новыми ключами сканирования. (Для перезапуска сканирования с ранее переданными ключами в keys
и/или orderbys
передаётся NULL.) Заметьте, что количество ключей или операторов сортировки не может превышать значения, поступившие в ambeginscan
. На практике возможность перезапуска используется, когда в соединении со вложенным циклом выбирается новый внешний кортеж, так что требуется сравнение с новым ключом, но структура ключей сканирования не меняется.
bool amgettuple (IndexScanDesc scan, ScanDirection direction);
Выбирает следующий кортеж в ходе данного сканирования, с передвижением по индексу в заданном направлении (вперёд или назад). Возвращает TRUE, если кортеж был получен, или FALSE, если подходящих кортежей не осталось. В случае успеха в структуре scan
сохраняется TID кортежа. Заметьте, что под «успехом» здесь подразумевается только, что индекс содержит запись, соответствующую ключам сканирования, а не то, что данный кортеж обязательно существует в данных или оказывается видимым в снимке вызывающего субъекта. При положительном результате amgettuple
должна также установить для свойства scan->xs_recheck
значение TRUE или FALSE. FALSE будет означать, что запись индекса точно соответствует ключам сканирования, а TRUE, что есть сомнение в этом, так что условия, представленные ключами сканирования, необходимо ещё раз перепроверить для фактического кортежа, когда он будет получен. Это свойство введено для поддержки «неточных» операторов индексов. Заметьте, что такая перепроверка касается только условий сканирования; предикат частичного индекса (если он имеется) никогда не перепроверяется кодом, вызывающим amgettuple
.
Если индекс поддерживает сканирование только индекса (то есть, amcanreturn
для него равен TRUE), то в случае успеха метод доступа должен также проверить флаг scan->xs_want_itup
и, если он установлен, должен вернуть исходные индексированные данные для этой записи индекса. Данные могут возвращаться посредством указателя на IndexTuple
, сохранённого в scan->xs_itup
, с дескриптором scan->xs_itupdesc
; либо посредством указателя на HeapTuple
, сохранённого в scan->xs_hitup
, с дескриптором кортежа scan->xs_hitupdesc
. (Второй вариант должен использоваться для восстановления данных, которые могут не уместиться в IndexTuple
.) В любом случае за управление целевой областью данных, определяемой этим указателем, отвечает метод доступа. Данные должны оставаться актуальными как минимум до следующего вызова amgettuple
, amrescan
или amendscan
в процессе сканирования.
Функция amgettuple
должна быть реализована, только если метод доступа поддерживает «простое» сканирование индекса. В противном случае поле amgettuple
в структуре IndexAmRoutine
должно содержать NULL.
int64 amgetbitmap (IndexScanDesc scan, TIDBitmap *tbm);
Выбирает все кортежи для данного сканирования и добавляет их в передаваемую вызывающим кодом структуру TIDBitmap
(то есть, получает логическое объединение множества TID выбранных кортежей с множеством, уже записанным в битовой карте). Возвращает эта функция число полученных кортежей (это может быть только приблизительная оценка; например, некоторые методы доступа не учитывают повторяющиеся значения). Добавляя идентификаторы кортежей в битовую карту, amgetbitmap
может обозначить, что для этих кортежей нужно перепроверить условия сканирования. Для этого так же, как и в amgettuple
, устанавливается выходной параметр xs_recheck
. Замечание: в текущей реализации эта возможность увязывается с возможностью неточного хранения самих битовых карт, таким образом вызывающий код перепроверяет для отмеченных кортежей и условия сканирования, и предикат частичного индекса (если он имеется). Однако так может быть не всегда. Функции amgetbitmap
и amgettuple
не могут использоваться в одном сканировании индекса; есть и другие ограничения в применении amgetbitmap
, описанные в Разделе 56.3.
Функция amgetbitmap
должна быть реализована, только если метод доступа поддерживает сканирование индекса «по битовой карте». В противном случае поле amgetbitmap
в структуре IndexAmRoutine
должно содержать NULL.
void amendscan (IndexScanDesc scan);
Завершает сканирование и освобождает ресурсы. Саму структуру scan
освобождать не следует, но любые блокировки или закрепления объектов, установленные внутри метода доступа, должны быть сняты.
void ammarkpos (IndexScanDesc scan);
Помечает текущую позицию сканирования. Метод доступа должен поддерживать сохранение только одной позиции в процессе сканирования.
Функция ammarkpos
должна быть реализована, только если метод доступа поддерживает сканирование по порядку. Если это не так, в поле ammarkpos
в структуре IndexAmRoutine
можно записать NULL.
void amrestrpos (IndexScanDesc scan);
Восстанавливает позицию сканирования, отмеченную последней.
Функция amrestrpos
должна быть реализована, только если метод доступа поддерживает сканирование по порядку. Если это не так, в поле amrestrpos
в структуре IndexAmRoutine
можно записать NULL.
Помимо обычного сканирования некоторые типы индексов могут поддерживать параллельное сканирование индекса, что позволяет осуществлять совместное сканирование индекса нескольким обслуживающим процессам. Для этого метод доступа должен организовать работу так, чтобы каждый из взаимодействующих процессов возвращал подмножество кортежей, которое бы возвращалось при обычном, не параллельном сканировании, и таким образом, чтобы объединение этих подмножеств совпадало с множеством кортежей, возвращаемых при обычном сканировании. Более того, чтобы не требовалась глобальная сортировка кортежей, возвращаемых при параллельном сканировании, порядок кортежей в подмножествах, выдаваемых всеми взаимодействующими процессами, должен соответствовать запрошенному. Для поддержки параллельного сканирования по индексу должны быть реализованы следующие функции:
Size amestimateparallelscan (void);
Рассчитывает и возвращает объём (в байтах) в динамической разделяемой памяти, который может потребоваться для осуществления параллельного сканирования. (Этот объём дополняет, а не заменяет объём памяти, затребованный для данных, независимо от МД, в ParallelIndexScanDescData
.)
Эту функцию можно не реализовывать для методов доступа, которые не поддерживают параллельное сканирование, или для которых объём дополнительно требующейся памяти равен нулю.
void aminitparallelscan (void *target);
Эта функция будет вызываться для инициализации области динамической разделяемой памяти в начале параллельного сканирования. Параметр target
будет указывать на область объёма, не меньшего, чем возвратила функция amestimateparallelscan
, и данная функция может хранить в этой области любые нужные ей данные.
Эту функцию можно не реализовывать для методов доступа, которые не поддерживают параллельное сканирование, или когда выделенная область в разделяемой памяти не требует инициализации.
void amparallelrescan (IndexScanDesc scan);
Эта функция, если её реализовать, будет вызываться перед перезапуском параллельного сканирования индекса. Она должна сбросить всё разделяемое состояние, установленное функцией aminitparallelscan
, с тем, чтобы такое сканирование перезапустилось с начала.
56.2. Index Access Method Functions
The index construction and maintenance functions that an index access method must provide in IndexAmRoutine
are:
IndexBuildResult * ambuild (Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo);
Build a new index. The index relation has been physically created, but is empty. It must be filled in with whatever fixed data the access method requires, plus entries for all tuples already existing in the table. Ordinarily the ambuild
function will call IndexBuildHeapScan()
to scan the table for existing tuples and compute the keys that need to be inserted into the index. The function must return a palloc'd struct containing statistics about the new index.
void ambuildempty (Relation indexRelation);
Build an empty index, and write it to the initialization fork (INIT_FORKNUM
) of the given relation. This method is called only for unlogged indexes; the empty index written to the initialization fork will be copied over the main relation fork on each server restart.
bool aminsert (Relation indexRelation, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRelation, IndexUniqueCheck checkUnique, IndexInfo *indexInfo);
Insert a new tuple into an existing index. The values
and isnull
arrays give the key values to be indexed, and heap_tid
is the TID to be indexed. If the access method supports unique indexes (its amcanunique
flag is true) then checkUnique
indicates the type of uniqueness check to perform. This varies depending on whether the unique constraint is deferrable; see Section 56.5 for details. Normally the access method only needs the heapRelation
parameter when performing uniqueness checking (since then it will have to look into the heap to verify tuple liveness).
The function's Boolean result value is significant only when checkUnique
is UNIQUE_CHECK_PARTIAL
. In this case a TRUE result means the new entry is known unique, whereas FALSE means it might be non-unique (and a deferred uniqueness check must be scheduled). For other cases a constant FALSE result is recommended.
Some indexes might not index all tuples. If the tuple is not to be indexed, aminsert
should just return without doing anything.
If the index AM wishes to cache data across successive index insertions within a SQL statement, it can allocate space in indexInfo->ii_Context
and store a pointer to the data in indexInfo->ii_AmCache
(which will be NULL initially).
IndexBulkDeleteResult * ambulkdelete (IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state);
Delete tuple(s) from the index. This is a “bulk delete” operation that is intended to be implemented by scanning the whole index and checking each entry to see if it should be deleted. The passed-in callback
function must be called, in the style callback(
, to determine whether any particular index entry, as identified by its referenced TID, is to be deleted. Must return either NULL or a palloc'd struct containing statistics about the effects of the deletion operation. It is OK to return NULL if no information needs to be passed on to TID
, callback_state) returns boolamvacuumcleanup
.
Because of limited maintenance_work_mem
, ambulkdelete
might need to be called more than once when many tuples are to be deleted. The stats
argument is the result of the previous call for this index (it is NULL for the first call within a VACUUM
operation). This allows the AM to accumulate statistics across the whole operation. Typically, ambulkdelete
will modify and return the same struct if the passed stats
is not null.
IndexBulkDeleteResult * amvacuumcleanup (IndexVacuumInfo *info, IndexBulkDeleteResult *stats);
Clean up after a VACUUM
operation (zero or more ambulkdelete
calls). This does not have to do anything beyond returning index statistics, but it might perform bulk cleanup such as reclaiming empty index pages. stats
is whatever the last ambulkdelete
call returned, or NULL if ambulkdelete
was not called because no tuples needed to be deleted. If the result is not NULL it must be a palloc'd struct. The statistics it contains will be used to update pg_class
, and will be reported by VACUUM
if VERBOSE
is given. It is OK to return NULL if the index was not changed at all during the VACUUM
operation, but otherwise correct stats should be returned.
As of PostgreSQL 8.4, amvacuumcleanup
will also be called at completion of an ANALYZE
operation. In this case stats
is always NULL and any return value will be ignored. This case can be distinguished by checking info->analyze_only
. It is recommended that the access method do nothing except post-insert cleanup in such a call, and that only in an autovacuum worker process.
bool amcanreturn (Relation indexRelation, int attno);
Check whether the index can support index-only scans on the given column, by returning the indexed column values for an index entry in the form of an IndexTuple
. The attribute number is 1-based, i.e., the first column's attno is 1. Returns TRUE if supported, else FALSE. If the access method does not support index-only scans at all, the amcanreturn
field in its IndexAmRoutine
struct can be set to NULL.
void amcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages);
Estimate the costs of an index scan. This function is described fully in Section 56.6, below.
bytea * amoptions (ArrayType *reloptions, bool validate);
Parse and validate the reloptions array for an index. This is called only when a non-null reloptions array exists for the index. reloptions
is a text
array containing entries of the form name
=
value
. The function should construct a bytea
value, which will be copied into the rd_options
field of the index's relcache entry. The data contents of the bytea
value are open for the access method to define; most of the standard access methods use struct StdRdOptions
. When validate
is true, the function should report a suitable error message if any of the options are unrecognized or have invalid values; when validate
is false, invalid entries should be silently ignored. (validate
is false when loading options already stored in pg_catalog
; an invalid entry could only be found if the access method has changed its rules for options, and in that case ignoring obsolete entries is appropriate.) It is OK to return NULL if default behavior is wanted.
bool amproperty (Oid index_oid, int attno, IndexAMProperty prop, const char *propname, bool *res, bool *isnull);
The amproperty
method allows index access methods to override the default behavior of pg_index_column_has_property
and related functions. If the access method does not have any special behavior for index property inquiries, the amproperty
field in its IndexAmRoutine
struct can be set to NULL. Otherwise, the amproperty
method will be called with index_oid
and attno
both zero for pg_indexam_has_property
calls, or with index_oid
valid and attno
zero for pg_index_has_property
calls, or with index_oid
valid and attno
greater than zero for pg_index_column_has_property
calls. prop
is an enum value identifying the property being tested, while propname
is the original property name string. If the core code does not recognize the property name then prop
is AMPROP_UNKNOWN
. Access methods can define custom property names by checking propname
for a match (use pg_strcasecmp
to match, for consistency with the core code); for names known to the core code, it's better to inspect prop
. If the amproperty
method returns true
then it has determined the property test result: it must set *res
to the boolean value to return, or set *isnull
to true
to return a NULL. (Both of the referenced variables are initialized to false
before the call.) If the amproperty
method returns false
then the core code will proceed with its normal logic for determining the property test result.
Access methods that support ordering operators should implement AMPROP_DISTANCE_ORDERABLE
property testing, as the core code does not know how to do that and will return NULL. It may also be advantageous to implement AMPROP_RETURNABLE
testing, if that can be done more cheaply than by opening the index and calling amcanreturn
, which is the core code's default behavior. The default behavior should be satisfactory for all other standard properties.
bool amvalidate (Oid opclassoid);
Validate the catalog entries for the specified operator class, so far as the access method can reasonably do that. For example, this might include testing that all required support functions are provided. The amvalidate
function must return false if the opclass is invalid. Problems should be reported with ereport
messages.
The purpose of an index, of course, is to support scans for tuples matching an indexable WHERE
condition, often called a qualifier or scan key. The semantics of index scanning are described more fully in Section 56.3, below. An index access method can support “plain” index scans, “bitmap” index scans, or both. The scan-related functions that an index access method must or may provide are:
IndexScanDesc ambeginscan (Relation indexRelation, int nkeys, int norderbys);
Prepare for an index scan. The nkeys
and norderbys
parameters indicate the number of quals and ordering operators that will be used in the scan; these may be useful for space allocation purposes. Note that the actual values of the scan keys aren't provided yet. The result must be a palloc'd struct. For implementation reasons the index access method must create this struct by calling RelationGetIndexScan()
. In most cases ambeginscan
does little beyond making that call and perhaps acquiring locks; the interesting parts of index-scan startup are in amrescan
.
void amrescan (IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys);
Start or restart an index scan, possibly with new scan keys. (To restart using previously-passed keys, NULL is passed for keys
and/or orderbys
.) Note that it is not allowed for the number of keys or order-by operators to be larger than what was passed to ambeginscan
. In practice the restart feature is used when a new outer tuple is selected by a nested-loop join and so a new key comparison value is needed, but the scan key structure remains the same.
bool amgettuple (IndexScanDesc scan, ScanDirection direction);
Fetch the next tuple in the given scan, moving in the given direction (forward or backward in the index). Returns TRUE if a tuple was obtained, FALSE if no matching tuples remain. In the TRUE case the tuple TID is stored into the scan
structure. Note that “success” means only that the index contains an entry that matches the scan keys, not that the tuple necessarily still exists in the heap or will pass the caller's snapshot test. On success, amgettuple
must also set scan->xs_recheck
to TRUE or FALSE. FALSE means it is certain that the index entry matches the scan keys. TRUE means this is not certain, and the conditions represented by the scan keys must be rechecked against the heap tuple after fetching it. This provision supports “lossy” index operators. Note that rechecking will extend only to the scan conditions; a partial index predicate (if any) is never rechecked by amgettuple
callers.
If the index supports index-only scans (i.e., amcanreturn
returns TRUE for it), then on success the AM must also check scan->xs_want_itup
, and if that is true it must return the originally indexed data for the index entry. The data can be returned in the form of an IndexTuple
pointer stored at scan->xs_itup
, with tuple descriptor scan->xs_itupdesc
; or in the form of a HeapTuple
pointer stored at scan->xs_hitup
, with tuple descriptor scan->xs_hitupdesc
. (The latter format should be used when reconstructing data that might possibly not fit into an IndexTuple
.) In either case, management of the data referenced by the pointer is the access method's responsibility. The data must remain good at least until the next amgettuple
, amrescan
, or amendscan
call for the scan.
The amgettuple
function need only be provided if the access method supports “plain” index scans. If it doesn't, the amgettuple
field in its IndexAmRoutine
struct must be set to NULL.
int64 amgetbitmap (IndexScanDesc scan, TIDBitmap *tbm);
Fetch all tuples in the given scan and add them to the caller-supplied TIDBitmap
(that is, OR the set of tuple IDs into whatever set is already in the bitmap). The number of tuples fetched is returned (this might be just an approximate count, for instance some AMs do not detect duplicates). While inserting tuple IDs into the bitmap, amgetbitmap
can indicate that rechecking of the scan conditions is required for specific tuple IDs. This is analogous to the xs_recheck
output parameter of amgettuple
. Note: in the current implementation, support for this feature is conflated with support for lossy storage of the bitmap itself, and therefore callers recheck both the scan conditions and the partial index predicate (if any) for recheckable tuples. That might not always be true, however. amgetbitmap
and amgettuple
cannot be used in the same index scan; there are other restrictions too when using amgetbitmap
, as explained in Section 56.3.
The amgetbitmap
function need only be provided if the access method supports “bitmap” index scans. If it doesn't, the amgetbitmap
field in its IndexAmRoutine
struct must be set to NULL.
void amendscan (IndexScanDesc scan);
End a scan and release resources. The scan
struct itself should not be freed, but any locks or pins taken internally by the access method must be released, as well as any other memory allocated by ambeginscan
and other scan-related functions.
void ammarkpos (IndexScanDesc scan);
Mark current scan position. The access method need only support one remembered scan position per scan.
The ammarkpos
function need only be provided if the access method supports ordered scans. If it doesn't, the ammarkpos
field in its IndexAmRoutine
struct may be set to NULL.
void amrestrpos (IndexScanDesc scan);
Restore the scan to the most recently marked position.
The amrestrpos
function need only be provided if the access method supports ordered scans. If it doesn't, the amrestrpos
field in its IndexAmRoutine
struct may be set to NULL.
In addition to supporting ordinary index scans, some types of index may wish to support parallel index scans, which allow multiple backends to cooperate in performing an index scan. The index access method should arrange things so that each cooperating process returns a subset of the tuples that would be performed by an ordinary, non-parallel index scan, but in such a way that the union of those subsets is equal to the set of tuples that would be returned by an ordinary, non-parallel index scan. Furthermore, while there need not be any global ordering of tuples returned by a parallel scan, the ordering of that subset of tuples returned within each cooperating backend must match the requested ordering. The following functions may be implemented to support parallel index scans:
Size amestimateparallelscan (void);
Estimate and return the number of bytes of dynamic shared memory which the access method will be needed to perform a parallel scan. (This number is in addition to, not in lieu of, the amount of space needed for AM-independent data in ParallelIndexScanDescData
.)
It is not necessary to implement this function for access methods which do not support parallel scans or for which the number of additional bytes of storage required is zero.
void aminitparallelscan (void *target);
This function will be called to initialize dynamic shared memory at the beginning of a parallel scan. target
will point to at least the number of bytes previously returned by amestimateparallelscan
, and this function may use that amount of space to store whatever data it wishes.
It is not necessary to implement this function for access methods which do not support parallel scans or in cases where the shared memory space required needs no initialization.
void amparallelrescan (IndexScanDesc scan);
This function, if implemented, will be called when a parallel index scan must be restarted. It should reset any shared state set up by aminitparallelscan
such that the scan will be restarted from the beginning.