PostgreSQL 中文参考文档
🌐 英文原版 官方 ↗

64.2. 自定义 WAL 资源管理器 #

本节阐述 PostgreSQL 核心系统与自定义 WAL 资源管理器之间的接口,它使扩展能够直接与 WAL 集成。

一个扩展,尤其是 表访问方法 或 索引访问方法,可能需要使用 WAL 来实现恢复、复制和/或 逻辑解码。

要创建新的自定义 WAL 资源管理器,首先定义一个带有资源管理器方法实现的 RmgrData 结构。请参考 PostgreSQL 源码中的 src/backend/access/transam/README 与 src/include/access/xlog_internal.h。

/*
 * Method table for resource managers.
 *
 * This struct must be kept in sync with the PG_RMGR definition in
 * rmgr.c.
 *
 * rm_identify must return a name for the record based on xl_info (without
 * reference to the rmid). For example, XLOG_BTREE_VACUUM would be named
 * "VACUUM". rm_desc can then be called to obtain additional detail for the
 * record, if available (e.g. the last block).
 *
 * rm_mask takes as input a page modified by the resource manager and masks
 * out bits that shouldn't be flagged by wal_consistency_checking.
 *
 * RmgrTable[] is indexed by RmgrId values (see rmgrlist.h). If rm_name is
 * NULL, the corresponding RmgrTable entry is considered invalid.
 */
typedef struct RmgrData
{
    const char *rm_name;
    void        (*rm_redo) (XLogReaderState *record);
    void        (*rm_desc) (StringInfo buf, XLogReaderState *record);
    const char *(*rm_identify) (uint8 info);
    void        (*rm_startup) (void);
    void        (*rm_cleanup) (void);
    void        (*rm_mask) (char *pagedata, BlockNumber blkno);
    void        (*rm_decode) (struct LogicalDecodingContext *ctx,
                              struct XLogRecordBuffer *buf);
} RmgrData;

src/test/modules/test_custom_rmgrs 模块包含一个可运行的示例,演示自定义 WAL 资源管理器的用法。

然后,注册你的新资源管理器。

/*
 * Register a new custom WAL resource manager.
 *
 * Resource manager IDs must be globally unique across all extensions. Refer
 * to https://wiki.postgresql.org/wiki/CustomWALResourceManagers to reserve a
 * unique RmgrId for your extension, to avoid conflicts with other extension
 * developers. During development, use RM_EXPERIMENTAL_ID to avoid needlessly
 * reserving a new ID.
 */
extern void RegisterCustomRmgr(RmgrId rmid, const RmgrData *rmgr);

RegisterCustomRmgr 必须从扩展模块的 _PG_init 函数中调用。开发新扩展时,请对 rmid 使用 RM_EXPERIMENTAL_ID。当你准备好向用户发布该扩展时,请在 自定义 WAL 资源管理器 页面预留一个新的资源管理器 ID。

把实现自定义资源管理器的扩展模块放入 shared_preload_libraries,使它在 PostgreSQL 启动过程的早期被加载。

Note

只要系统中还可能存在任何自定义 WAL 记录,该扩展就必须保留在 shared_preload_libraries 中。否则 PostgreSQL 将无法应用或解码这些自定义 WAL 记录,这可能阻止服务器启动。