> For the complete documentation index, see [llms.txt](https://docs.postgresql.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.postgresql.tw/19/server-programming/pltcl/pltcl-global.md). Agents can also search and read this documentation through its [MCP server](https://docs.postgresql.tw/~gitbook/mcp).

# 42.4. PL/Tcl 中的全域資料 \#

### 42.4. PL/Tcl 中的全域資料 [#](#pltcl-global) <a href="#pltcl-global" id="pltcl-global"></a>

有時候，能夠擁有在兩次函式呼叫之間保留、或在不同函式之間共享的全域資料是很有用的。在 PL/Tcl 中這很容易做到，但有一些必須先了解的限制。

基於安全考量，PL/Tcl 會針對每一個 SQL 角色，在各自獨立的 Tcl 直譯器中執行由該角色所呼叫的函式。這可以避免某個使用者意外或惡意地干擾另一個使用者的 PL/Tcl 函式行為。每個這樣的直譯器都會有自己的一份「全域」Tcl 變數值。因此，兩個 PL/Tcl 函式若且唯若由同一個 SQL 角色執行時，才會共享相同的全域變數。在某個應用中，如果單一工作階段會以多個 SQL 角色執行程式碼（透過 `SECURITY DEFINER` 函式、使用 `SET ROLE` 等等），你可能需要採取明確的步驟，以確保 PL/Tcl 函式能夠共享資料。要做到這一點，請確認那些應該互相溝通的函式由同一個使用者所擁有，並將它們標記為 `SECURITY DEFINER`。當然，你也必須留意這類函式不能被用來做出任何非預期的事情。

在一個工作階段中使用的所有 PL/TclU 函式都在同一個 Tcl 直譯器中執行，而這個直譯器當然與 PL/Tcl 函式所使用的直譯器不同。所以全域資料會自動在 PL/TclU 函式之間共享。這並不被視為安全風險，因為所有 PL/TclU 函式都以相同的信任層級執行，也就是資料庫超級使用者的層級。

為了協助保護 PL/Tcl 函式不會無意間互相干擾，每個函式都可以透過 `upvar` 指令取得一個全域陣列。這個變數的全域名稱是該函式的內部名稱，而區域名稱是 `GD`。建議把 `GD` 用於函式的持續性私有資料。只有在你特別希望多個函式之間共享的值，才使用一般的 Tcl 全域變數。（請注意，`GD` 陣列只在特定直譯器內是全域的，所以它們並不會繞過上面提到的安全限制。）

使用 `GD` 的範例出現在下面的 `spi_execp` 範例中。

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/pltcl-global.html)（原文版本：18.6；核對日期：2026-09-13）


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.postgresql.tw/19/server-programming/pltcl/pltcl-global.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
