Postgresql 中文操作指南

DECLARE

DECLARE — 定义一个游标

DECLARE — define a cursor

Synopsis

DECLARE name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ]
    CURSOR [ { WITH | WITHOUT } HOLD ] FOR query

Description

DECLARE 允许用户创建游标,该游标可用来一次从一个较大的查询中检索少量行。创建游标后,使用 FETCH 从中获取行。

DECLARE allows a user to create cursors, which can be used to retrieve a small number of rows at a time out of a larger query. After the cursor is created, rows are fetched from it using FETCH.

Note

本页描述了 SQL 命令级别中游标的使用。如果你尝试在 PL/pgSQL 函数内使用游标,规则不同 — 请参阅 Section 43.7

This page describes usage of cursors at the SQL command level. If you are trying to use cursors inside a PL/pgSQL function, the rules are different — see Section 43.7.

Parameters

  • name

    • The name of the cursor to be created. This must be different from any other active cursor name in the session.

  • BINARY

    • Causes the cursor to return data in binary rather than in text format.

  • ASENSITIVE__INSENSITIVE

    • Cursor sensitivity determines whether changes to the data underlying the cursor, done in the same transaction, after the cursor has been declared, are visible in the cursor. INSENSITIVE means they are not visible, ASENSITIVE means the behavior is implementation-dependent. A third behavior, SENSITIVE, meaning that such changes are visible in the cursor, is not available in PostgreSQL. In PostgreSQL, all cursors are insensitive; so these key words have no effect and are only accepted for compatibility with the SQL standard.

    • Specifying INSENSITIVE together with FOR UPDATE or FOR SHARE is an error.

  • SCROLL__NO SCROLL

    • SCROLL specifies that the cursor can be used to retrieve rows in a nonsequential fashion (e.g., backward). Depending upon the complexity of the query’s execution plan, specifying SCROLL might impose a performance penalty on the query’s execution time. NO SCROLL specifies that the cursor cannot be used to retrieve rows in a nonsequential fashion. The default is to allow scrolling in some cases; this is not the same as specifying SCROLL. See Notes below for details.

  • WITH HOLD__WITHOUT HOLD

    • WITH HOLD specifies that the cursor can continue to be used after the transaction that created it successfully commits. WITHOUT HOLD specifies that the cursor cannot be used outside of the transaction that created it. If neither WITHOUT HOLD nor WITH HOLD is specified, WITHOUT HOLD is the default.

  • query

    • A SELECT or VALUES command which will provide the rows to be returned by the cursor.

关键字 ASENSITIVEBINARYINSENSITIVESCROLL 可按任何顺序显示。

The key words ASENSITIVE, BINARY, INSENSITIVE, and SCROLL can appear in any order.

Notes

普通光标以文本格式返回数据,与 SELECT 相同。 BINARY 选项指定光标应以二进制格式返回数据。这样可减少服务器和客户端的转换工作量,但会增加处理与平台相关的二进制数据格式的编程工作量。例如,如果一个查询从整数列中返回 1 的值,则使用默认光标时会得到一个 1 字符串,而使用二进制光标时会得到一个包含该值内部表示(大端字节序)的 4 字节字段。

Normal cursors return data in text format, the same as a SELECT would produce. The BINARY option specifies that the cursor should return data in binary format. This reduces conversion effort for both the server and client, at the cost of more programmer effort to deal with platform-dependent binary data formats. As an example, if a query returns a value of one from an integer column, you would get a string of 1 with a default cursor, whereas with a binary cursor you would get a 4-byte field containing the internal representation of the value (in big-endian byte order).

应谨慎使用二进制光标。许多应用程序(包括 psql)尚无法处理二进制光标,并期望数据采用文本格式返回。

Binary cursors should be used carefully. Many applications, including psql, are not prepared to handle binary cursors and expect data to come back in the text format.

Note

当客户端应用程序使用“扩展查询”协议发出 FETCH 命令时,Bind 协议消息会指定数据是按文本或二进制格式检索的。此选项会覆盖游标的定义方式。因此,当使用扩展查询协议时,二进制游标的概念就此过时——任何游标都可以被视为文本或二进制格式。

When the client application uses the “extended query” protocol to issue a FETCH command, the Bind protocol message specifies whether data is to be retrieved in text or binary format. This choice overrides the way that the cursor is defined. The concept of a binary cursor as such is thus obsolete when using extended query protocol — any cursor can be treated as either text or binary.

除非指定 WITH HOLD ,否则此命令创建的游标只能在当前事务中使用。因此,没有 WITH HOLDDECLARE 在事务块之外无用:游标将只能存在到此语句完成为止。因此,如果此类命令在交易块之外使用,PostgreSQL 将报告错误。使用 BEGINCOMMIT (或 ROLLBACK )定义事务块。

Unless WITH HOLD is specified, the cursor created by this command can only be used within the current transaction. Thus, DECLARE without WITH HOLD is useless outside a transaction block: the cursor would survive only to the completion of the statement. Therefore PostgreSQL reports an error if such a command is used outside a transaction block. Use BEGIN and COMMIT (or ROLLBACK) to define a transaction block.

如果指定了 WITH HOLD ,并且创建游标的事务成功提交,则后续事务仍可以访问该游标(但如果创建事务中止,则将移除该游标)。使用 WITH HOLD 创建的游标在针对该游标发出 CLOSE 命令或会话结束时关闭。在当前实现中,游标保存的行会复制到一个临时文件或内存区域,以便它们可以供后续事务使用。

If WITH HOLD is specified and the transaction that created the cursor successfully commits, the cursor can continue to be accessed by subsequent transactions in the same session. (But if the creating transaction is aborted, the cursor is removed.) A cursor created with WITH HOLD is closed when an explicit CLOSE command is issued on it, or the session ends. In the current implementation, the rows represented by a held cursor are copied into a temporary file or memory area so that they remain available for subsequent transactions.

当查询包含 FOR UPDATEFOR SHARE 时,可能无法指定 WITH HOLD

WITH HOLD may not be specified when the query includes FOR UPDATE or FOR SHARE.

在定义用于向后获取的游标时,应该指定 SCROLL 选项。这是 SQL 标准所必需的。然而,为了与早期版本兼容,如果游标的查询计划足够简单,无需额外的开销来支持它,PostgreSQL 将允许向后获取而不使用 SCROLL 。然而,建议应用程序开发人员不要依赖于从没有使用 SCROLL 创建的游标中向后获取数据。如果指定 NO SCROLL ,则在任何情况下都禁止向后获取。

The SCROLL option should be specified when defining a cursor that will be used to fetch backwards. This is required by the SQL standard. However, for compatibility with earlier versions, PostgreSQL will allow backward fetches without SCROLL, if the cursor’s query plan is simple enough that no extra overhead is needed to support it. However, application developers are advised not to rely on using backward fetches from a cursor that has not been created with SCROLL. If NO SCROLL is specified, then backward fetches are disallowed in any case.

当查询包含 FOR UPDATEFOR SHARE 时,也不允许向后获取;因此,在这种情况下可能无法指定 SCROLL

Backward fetches are also disallowed when the query includes FOR UPDATE or FOR SHARE; therefore SCROLL may not be specified in this case.

Caution

如果可滚动游标调用任何不稳定函数(参见 Section 38.7 ),则它们可能会产生意外的结果。当重新获取以前获取的行时,可能会重新执行函数,从而产生与第一次不同的结果。最好针对涉及不稳定函数的查询指定 NO SCROLL 。如果这不可行,一种解决方法是在读取中的任何行之前声明游标为 SCROLL WITH HOLD 并提交事务。这会强制游标的整个输出保存在临时存储中,以便针对每行只执行一次不稳定函数。

Scrollable cursors may give unexpected results if they invoke any volatile functions (see Section 38.7). When a previously fetched row is re-fetched, the functions might be re-executed, perhaps leading to results different from the first time. It’s best to specify NO SCROLL for a query involving volatile functions. If that is not practical, one workaround is to declare the cursor SCROLL WITH HOLD and commit the transaction before reading any rows from it. This will force the entire output of the cursor to be materialized in temporary storage, so that volatile functions are executed exactly once for each row.

如果游标的查询包含 FOR UPDATEFOR SHARE ,则返回的行会像使用这些选项的常规 SELECT 命令一样,在初次获取时锁定。此外,返回的行将是最新的版本。

If the cursor’s query includes FOR UPDATE or FOR SHARE, then returned rows are locked at the time they are first fetched, in the same way as for a regular SELECT command with these options. In addition, the returned rows will be the most up-to-date versions.

Caution

如果游标打算与 UPDATE …​ WHERE CURRENT OFDELETE …​ WHERE CURRENT OF 一起使用,通常建议使用 FOR UPDATE 。使用 FOR UPDATE 可以防止其他会话在获取行的时间和更新时间之间更改行。如果不使用 FOR UPDATE ,则如果自创建游标以来该行已被更改,随后的 WHERE CURRENT OF 命令将不起作用。

It is generally recommended to use FOR UPDATE if the cursor is intended to be used with UPDATE …​ WHERE CURRENT OF or DELETE …​ WHERE CURRENT OF. Using FOR UPDATE prevents other sessions from changing the rows between the time they are fetched and the time they are updated. Without FOR UPDATE, a subsequent WHERE CURRENT OF command will have no effect if the row was changed since the cursor was created.

使用 FOR UPDATE 的另一个原因是:如果没有它,如果游标查询不满足 SQL 标准的“可简单更新”规则(特别是,游标必须仅引用一个表,并且不使用分组或 ORDER BY ),则 WHERE CURRENT OF 可能会失败。不可简单更新的游标可能有效,也可能无效,具体取决于计划选择详细信息;因此在最坏的情况下,应用程序可能会在测试中正常运行,但在生产中失败。如果指定 FOR UPDATE ,则游标可以保证可更新。

Another reason to use FOR UPDATE is that without it, a subsequent WHERE CURRENT OF might fail if the cursor query does not meet the SQL standard’s rules for being “simply updatable” (in particular, the cursor must reference just one table and not use grouping or ORDER BY). Cursors that are not simply updatable might work, or might not, depending on plan choice details; so in the worst case, an application might work in testing and then fail in production. If FOR UPDATE is specified, the cursor is guaranteed to be updatable.

不使用 WHERE CURRENT OF 配合使用 FOR UPDATE 的主要原因是你需要该游标具有可滚动性,或与并发更新隔离(即继续显示旧数据)。如果这是要求,请密切注意上面显示的警告。

The main reason not to use FOR UPDATE with WHERE CURRENT OF is if you need the cursor to be scrollable, or to be isolated from concurrent updates (that is, continue to show the old data). If this is a requirement, pay close heed to the caveats shown above.

SQL 标准仅为嵌入式 SQL 中的游标提供规定。PostgreSQL 服务器没有为游标实现 OPEN 语句;声明时,游标被认为已打开。然而,PostgreSQL 的嵌入式 SQL 预处理器 ECPG 支持标准 SQL 游标约定,包括涉及 DECLAREOPEN 语句的约定。

The SQL standard only makes provisions for cursors in embedded SQL. The PostgreSQL server does not implement an OPEN statement for cursors; a cursor is considered to be open when it is declared. However, ECPG, the embedded SQL preprocessor for PostgreSQL, supports the standard SQL cursor conventions, including those involving DECLARE and OPEN statements.

作为打开游标基础的数据结构称为 portal 。门户名称在客户端协议中公开:如果知道门户名称,客户端可以直接从打开的门户中获取行。使用 DECLARE 创建游标时,门户名称与游标名称相同。

The server data structure underlying an open cursor is called a portal. Portal names are exposed in the client protocol: a client can fetch rows directly from an open portal, if it knows the portal name. When creating a cursor with DECLARE, the portal name is the same as the cursor name.

你可以通过查询 pg_cursors 系统视图来查看所有可用的游标。

You can see all available cursors by querying the pg_cursors system view.

Examples

要声明游标:

To declare a cursor:

DECLARE liahona CURSOR FOR SELECT * FROM films;

有关使用游标的更多示例,请参阅 FETCH

See FETCH for more examples of cursor usage.

Compatibility

SQL 标准仅允许在嵌入式 SQL 和模块中使用游标。PostgreSQL 允许交互式使用游标。

The SQL standard allows cursors only in embedded SQL and in modules. PostgreSQL permits cursors to be used interactively.

根据 SQL 标准, UPDATE …​ WHERE CURRENT OFDELETE …​ WHERE CURRENT OF 语句对不敏感游标所做的更改在该游标中可见。PostgreSQL 将这些语句视为所有其他数据更改语句,因为它们在不敏感游标中不可见。

According to the SQL standard, changes made to insensitive cursors by UPDATE …​ WHERE CURRENT OF and DELETE …​ WHERE CURRENT OF statements are visible in that same cursor. PostgreSQL treats these statements like all other data changing statements in that they are not visible in insensitive cursors.

二进制游标是 PostgreSQL 的扩展。

Binary cursors are a PostgreSQL extension.

See Also