云数据库 PostgreSQL 调用 CloudBase 云函数

云数据库 PostgreSQL 支持通过插件 tencentdb_scf 实现调用 CloudBase 云函数,这里说明关于调用 CloudBase 云函数的说明及使用方法。

相关产品
云数据库 PostgreSQL 产品页,含版本规格、价格与购买入口。

一、使用限制

·该能力由扩展 tencentdb_scf 提供,仅支持通过 SQL 函数调用 CloudBase 云函数网关,不支持访问任意外部 URL,也不支持 GET/PUT/DELETE 等其他 HTTP 方法,当前只支持 POST。

·tencentdb_scf 依赖 pgcrypto(用于加密保存凭证)以及 tencentdb_polaris(用于 CloudBase 网关的服务发现),需要将两者一并加入 shared_preload_libraries 并重启实例后才能正常使用,仅创建扩展不足以让请求生效。

·path 参数只能是 /v1/functions/{函数名} 形式的 CloudBase 函数路径,不能传入完整 URL,也不能访问 api.tcloudbasegateway.com 以外的域名。

·tencentdb_scf.config、tencentdb_scf.request_queue、tencentdb_scf._http_response 均为内部表,暂不支持查询。

二、支持版本

v17.10_r1.19及以上。

三、环境准备

1. 在控制台修改内核参数,加载扩展依赖:

控制台操作:登录 云数据库 PostgreSQL 控制台 → 实例管理 → 参数设置,搜索参数 shared_preload_libraries,将 tencentdb_scf 和 tencentdb_polaris 添加到该参数值中并保存。该参数为重启生效级别,保存后需重启实例。

2. 创建扩展(pgcrypto 与 tencentdb_polaris 为前置依赖,需先创建):

postgres=> CREATE EXTENSION pgcrypto;postgres=> CREATE EXTENSION tencentdb_polaris;postgres=> CREATE EXTENSION tencentdb_scf;

3. 建议设置 search_path,后续调用可省略 schema 前缀:

postgres=> SET search_path = tencentdb_scf, public;

4. 确认异步处理 Worker 已启动:

postgres=> SELECT wait_until_running(); wait_until_running——————–(1 row)

四、配置 CloudBase 调用凭证

在发起调用前,需要同时完成以下两项配置——CloudBase 环境 ID 与 API Key 缺一不可。两者会持久化保存到 tencentdb_scf.config 表中(api_key 通过 pgcrypto 加密保存)。

postgres=> SELECT set_cloudbase_env_id('<your-cloudbase-env-id>');postgres=> SELECT set_cloudbase_api_key('<your-cloudbase-api-key>');

注意:说明:

五、调用 CloudBase 云函数

tencentdb_scf.tencentdb_scf_post( path TEXT, headers JSONB DEFAULT '{}'::jsonb, body TEXT DEFAULT '', sync BOOLEAN DEFAULT true, timeout_milliseconds INT DEFAULT 5000);

参数说明:

参数名 类型 是否必填 说明
path TEXT 是 CloudBase 函数路径,必须以 /v1/functions/ 开头,总长度不超过512字符;函数名需以字母开头,只能包含字母、数字、短横线、下划线,且不能以短横线或下划线结尾
headers JSONB 否 自定义请求头,默认 {};Authorization、Host、Cookie、Content-Type、X-Forwarded-For、X-Forwarded-Host、X-Forwarded-Proto、User-Agent 会被过滤,无法覆盖
body TEXT 否 请求体,默认为空字符串
sync BOOLEAN 否 是否同步调用,默认 true;true 表示同步阻塞等待结果,false 表示异步写入队列由后台 Worker 处理
timeout_milliseconds INT 否 超时时间(毫秒),默认5000

返回值:BIGINT 类型的请求 ID,用于后续通过 tencentdb_scf_result 查询结果。

注意:说明:

注意:服务端会固定注入 Authorization: Bearer <api_key>、Content-Type: application/json、User-Agent: TencentDB-PG <version> 三个请求头;若你在 headers 中传入同名请求头(不区分大小写),会被过滤并打印 WARNING,不会覆盖服务端注入的值。

六、方式一:同步调用

同步模式适用于需要立即获取调用结果、云函数执行时间较短的场景,tencentdb_scf_post 会在当前 backend 内直接完成 HTTP 调用并把结果写入 tencentdb_scf._http_response 表。

postgres=> SELECT tencentdb_scf.tencentdb_scf_post( path := '/v1/functions/scfnodejshelloworld', headers := '{"X-Request-Id":"1c12da52-782f-407b-81aa-b181306f28fe"}'::jsonb, body := '{"hello":"world"}', sync := true, timeout_milliseconds := 10000) AS request_id \\gsetpostgres=> SELECT status_code, timed_out, error_msg IS NULL AS no_errorFROM tencentdb_scf._http_response WHERE id = :request_id; status_code | timed_out | no_error————-+———–+———- 200 | f | t(1 row)

七、方式二:异步调用

异步模式适用于触发器、批量任务、定时任务等不希望阻塞主流程的场景。调用会先写入 tencentdb_scf.request_queue,事务提交后由后台 Worker 消费并把结果写入 tencentdb_scf._http_response。

postgres=> SELECT tencentdb_scf.tencentdb_scf_post( path := '/v1/functions/heavyTask', body := '{"dataset":"large"}', sync := false, timeout_milliseconds := 30000) AS request_id \\gset

注意:说明:

八、配合 pg_cron 定时触发

postgres=> CREATE OR REPLACE FUNCTION trigger_daily_cleanup()RETURNS void AS $$BEGIN PERFORM tencentdb_scf.tencentdb_scf_post( path := '/v1/functions/dailyCleanup', body := json_build_object('action', 'cleanup', 'timestamp', now()::text)::text, sync := false, timeout_milliseconds := 15000 );END;$$ LANGUAGE plpgsql;postgres=> SELECT cron.schedule('daily-cleanup', '0 2 * * *', 'SELECT trigger_daily_cleanup()');

九、查询调用结果

postgres=> SELECT tencentdb_scf.tencentdb_scf_result(req_id BIGINT);

字段说明(返回值为 JSONB,对应 _http_response 表的以下字段):

·id:请求 ID。

·status_code:HTTP 状态码,请求未完成或异常时为 NULL。

·content_type:响应的 Content-Type。

·headers:响应头,JSONB 对象。

·content:响应体。

·timed_out:是否超时。

·error_msg:内部错误信息(如超时、连接失败等),无错误时为 NULL。

·created:写入时间。

示例:

postgres=> SELECT tencentdb_scf.tencentdb_scf_result(:request_id);-[ RECORD 1 ]—————————————–tencentdb_scf_result | {"id": 42, "status_code": 200, "content_type": "application/json; charset=utf-8", "headers": {…}, "content": "…", "timed_out": false, "error_msg": null, "created": "2026-07-07T10:00:00+08:00"}

调用不存在的请求 ID,或结果已被 TTL(默认6小时,见下文 GUC 说明)清理时,返回 NULL:

postgres=> SELECT tencentdb_scf.tencentdb_scf_result(-1) IS NULL AS missing_result_is_null; missing_result_is_null————————- t(1 row)

十、Worker 管理辅助函数

以下函数用于异步 Worker 的运维和测试辅助,一般业务侧无需主动调用:

函数 返回类型 作用
wake() VOID 立即唤醒后台 Worker 消费请求队列(正常场景下事务提交会自动唤醒)
worker_restart() BOOLEAN 触发后台 Worker 重新加载配置并恢复处理
wait_until_running() VOID 阻塞等待,直到 Worker 进入 running 状态,常用于验证 Worker 是否已就绪

示例:

postgres=> SELECT worker_restart(); worker_restart—————- t(1 row)postgres=> SELECT wait_until_running(); wait_until_running——————–(1 row)

十一、相关内核参数

参数名 默认值 生效方式 说明
tencentdb_scf.ttl 6 hours 重载配置生效 _http_response 中调用结果的保留时长,超过该时长的记录会被后台 Worker 定期清理
tencentdb_scf.batch_size 200 重载配置生效 后台 Worker 每轮迭代处理的请求数量上限
tencentdb_scf.database_name postgres 重启实例生效 后台 Worker 连接的数据库名
tencentdb_scf.username postgres 重启实例生效 后台 Worker 连接使用的用户名,建议按需填写实际使用的数据库用户
tencentdb_scf.allow_super 当前默认开启 重载配置生效 是否允许 superuser 调用云函数,为运维侧开关,普通用户无需关注

十二、调用 tencentdb_scf_post 报错「CloudBase env_id is not configured; call set_cloudbase_env_id() first」是什么原因?

尚未通过 set_cloudbase_env_id() 配置 CloudBase 环境 ID,请先完成配置后再发起调用。同理,若报错「CloudBase api_key is not configured; call set_cloudbase_api_key() first」,说明尚未配置 API Key。

十三、调用时报错「path must start with '/v1/functions/'」是什么原因?

tencentdb_scf_post 的 path 参数不接受完整 URL,也不接受缺少前导路径的写法,必须是以 /v1/functions/ 开头的 CloudBase 函数路径,例如 /v1/functions/myFunction。

十四、为什么在 headers 中传入 Content-Type、Authorization 等请求头没有生效,还出现了 WARNING?

Authorization、Host、Cookie、Content-Type、X-Forwarded-For、X-Forwarded-Host、X-Forwarded-Proto、User-Agent(不区分大小写)属于服务端固定注入或协议语义相关的请求头,会被强制过滤,避免覆盖服务端认证信息或造成网关解析歧义,日志中会打印如下提示:

WARNING: tencentdb_scf: sensitive header 'Content-Type' has been filtered; overriding it is not allowed

十五、查询 tencentdb_scf.config 等内部表报错「permission denied for schema tencentdb_scf」是什么原因?

config、request_queue、_http_response 是内部实现表,默认未对普通角色开放 schema 使用权限,无法直接查询,请通过 tencentdb_scf_result() 等 SQL 接口获取所需信息。

十六、异步调用后,tencentdb_scf_result 一直返回 NULL 是什么原因?

可能是请求仍在队列中尚未被 Worker 消费(可稍后重试查询),也可能是调用发生在事务中且事务尚未提交(未提交的异步请求不会被 Worker 消费),或者结果已超过 tencentdb_scf.ttl 保留时长被清理。

赞 (0)
上一篇 4天前
下一篇 4天前