<commit_before># 55. 撰寫程序語言的處理程序

使用目前編譯語言的「version 1」介面以外的語言撰寫的函數（包括使用者定義的程序語言函數和用 SQL 撰寫的函數）在被呼叫時，都將透過特定語言的呼叫處理程序函數。呼叫處理程序有責任以有意義的方式執行功能，例如透過解譯程式原始碼。本章概述如何撰寫新程序語言的呼叫處理程序。

程序語言的呼叫處理程序是「一般」函數，必須使用「version 1」介面以編譯語言（例如 C）撰寫，並在 PostgreSQL 中註冊為不帶任何參數且回傳 language\_handler 型別。這種特殊的偽型別將函數標識為呼叫處理程序，並防止在 SQL 指令中直接呼叫該函數。有關 C 語言呼叫約定和動態載入的更多詳細訊，請參閱[第 37.10 節](../server-programming/extending-sql/c-language-functions.md)。

The call handler is called in the same way as any other function: It receives a pointer to a `FunctionCallInfoBaseData` `struct` containing argument values and information about the called function, and it is expected to return a `Datum` result \(and possibly set the `isnull` field of the `FunctionCallInfoBaseData` structure, if it wishes to return an SQL null result\). The difference between a call handler and an ordinary callee function is that the `flinfo->fn_oid` field of the `FunctionCallInfoBaseData` structure will contain the OID of the actual function to be called, not of the call handler itself. The call handler must use this field to determine which function to execute. Also, the passed argument list has been set up according to the declaration of the target function, not of the call handler.

It's up to the call handler to fetch the entry of the function from the `pg_proc` system catalog and to analyze the argument and return types of the called function. The `AS` clause from the `CREATE FUNCTION` command for the function will be found in the `prosrc` column of the `pg_proc` row. This is commonly source text in the procedural language, but in theory it could be something else, such as a path name to a file, or anything else that tells the call handler what to do in detail.

Often, the same function is called many times per SQL statement. A call handler can avoid repeated lookups of information about the called function by using the `flinfo->fn_extra` field. This will initially be `NULL`, but can be set by the call handler to point at information about the called function. On subsequent calls, if `flinfo->fn_extra` is already non-`NULL` then it can be used and the information lookup step skipped. The call handler must make sure that `flinfo->fn_extra` is made to point at memory that will live at least until the end of the current query, since an `FmgrInfo` data structure could be kept that long. One way to do this is to allocate the extra data in the memory context specified by `flinfo->fn_mcxt`; such data will normally have the same lifespan as the `FmgrInfo` itself. But the handler could also choose to use a longer-lived memory context so that it can cache function definition information across queries.

When a procedural-language function is invoked as a trigger, no arguments are passed in the usual way, but the `FunctionCallInfoBaseData`'s `context` field points at a `TriggerData` structure, rather than being `NULL` as it is in a plain function call. A language handler should provide mechanisms for procedural-language functions to get at the trigger information.

This is a template for a procedural-language handler written in C:

```text
#include "postgres.h"
#include "executor/spi.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"

PG_MODULE_MAGIC;

PG_FUNCTION_INFO_V1(plsample_call_handler);

Datum
plsample_call_handler(PG_FUNCTION_ARGS)
{
    Datum          retval;

    if (CALLED_AS_TRIGGER(fcinfo))
    {
        /*
         * Called as a trigger function
         */<commit_msg>GitBook: [master] one page modified<commit_after># 55. 撰寫程序語言的處理程序

使用目前編譯語言的「version 1」介面以外的語言撰寫的函數（包括使用者定義的程序語言函數和用 SQL 撰寫的函數）在被呼叫時，都將透過特定語言的呼叫處理程序函數。呼叫處理程序有責任以有意義的方式執行功能，例如透過解譯程式原始碼。本章概述如何撰寫新程序語言的呼叫處理程序。

程序語言的呼叫處理程序是「一般」函數，必須使用「version 1」介面以編譯語言（例如 C）撰寫，並在 PostgreSQL 中註冊為不帶任何參數且回傳 language\_handler 型別。這種特殊的偽型別將函數標識為呼叫處理程序，並防止在 SQL 指令中直接呼叫該函數。有關 C 語言呼叫約定和動態載入的更多詳細訊，請參閱[第 37.10 節](../server-programming/extending-sql/c-language-functions.md)。

呼叫處理程序的呼叫方式與其他任何函數相同：它會接收到一個指向 FunctionCallInfoBaseData 結構的指標，該結構包含參數值和有關被呼叫函數的資訊，並且期待回傳 Datum 結果（也可能設定 FunctionCallInfoBaseData 結構中 isnull 的欄位，如果該函數希望回傳 SQL NULL 的結果）。呼叫處理程序和普通被呼叫函數之間的區別在於 FunctionCallInfoBaseData 結構的 flinfo-&gt;fn\_oid 欄位會包含要呼叫實際函數的 OID，而不包含呼叫處理程序本身的 OID。呼叫處理程序必須使用此欄位來決定所要執行的功能。同樣地，傳遞的參數列表是根據目標函數而不是呼叫處理程序的宣告設定。

呼叫處理程序要從 pg\_proc 系統目錄中取得函數的項目，並分析被呼叫函數的參數和回傳型別。該函數的 CREATE FUNCTION 命令的 AS 子句可以在 pg\_proc 行的 prosrc 欄位中看到。這通常是程序語言的原始碼，但是從理論上說，它也可能是其他內容，例如檔案的路徑名稱，或告訴呼叫處理程序詳細操作的其他任何內容。

通常，每個 SQL 語句會多次呼叫同一函數。 呼叫處理程序可以透過使用 flinfo-&gt;fn\_extra 欄位來避免重複查詢有關被呼叫函數的資訊。最初將為 NULL，但可以由呼叫處理程序設定為指向有關被呼叫函數的資訊。在後續的呼叫中，如果 flinfo-&gt;fn\_extra 已經為非 NULL，則可以使用它，並且跳過資訊查詢步驟。呼叫處理程序必須確保使 flinfo-&gt;fn\_extra 指向至少可以保存到目前查詢結束的快取，因為 FmgrInfo 資料結構可以保留那麼長時間。一種方法是在 flinfo-&gt;fn\_mcxt 指定的快取內容中分配額外的資料。此類資料通常與 FmgrInfo 本身俱有相同的壽命。但是處理程序還可以選擇使用壽命更長的快取，以便它可以跨查詢快取函數定義資訊。

當將程序語言函數作為事件觸發器呼叫時，不會以通常的方式傳遞任何參數，但是 FunctionCallInfoBaseData 的 context 欄位指向 TriggerData 結構，而不是像在普通函數呼叫中那樣為 NULL。語言處理程序應提供程序語言函數的機制，以取得所觸發資訊。

This is a template for a procedural-language handler written in C:

```text
#include "postgres.h"
#include "executor/spi.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"

PG_MODULE_MAGIC;

PG_FUNCTION_INFO_V1(plsample_call_handler);

Datum
plsample_call_handler(PG_FUNCTION_ARGS)
{
    Datum          retval;

    if (CALLED_AS_TRIGGER(fcinfo))
    {
        /*
         * Called as a trigger function
         */
{'fraction_non_alphanumeric': 0.06739755571531272, 'fraction_numerical': 0.003235082674335011, 'mean_word_length': 5.632896305125149, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5040158', 'n_tokens_mistral': 2608, 'n_tokens_neox': 2886, 'n_words': 613}