跳到主要内容

关系型数据库(PostgreSQL)

版本提示

@cloudbase/manager-node@5.4.0 起新增此模块。通过 app.database 访问,提供在 PostgreSQL 架构的云开发环境上执行 SQL 语句及管理数据的能力。


初始化

import CloudBase from '@cloudbase/manager-node'

const app = CloudBase.init({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId'
})

const { database } = app

executePGSql

1. 接口描述

接口功能:在 PostgreSQL 环境上执行任意 SQL 语句(DDL / DML / DQL 等),并返回结果集与受影响行数。

接口声明:app.database.executePGSql(options): Promise<IExecutePGSqlResult>

2. 输入参数

IExecutePGSqlOptions

字段必填类型说明
SqlString要执行的 SQL 语句
RoleString指定 role 执行 SQL(如 postgres),用于执行需要更高权限的语句(如 CREATE POLICY / DROP POLICY
EnvIdString云开发环境 ID,不传则使用当前管理实例初始化时的 EnvId

3. 返回结果

IExecutePGSqlResult

字段类型说明
RequestIdString请求唯一标识
AffectedRowsNumber受影响行数(DML 类语句有效)
ColumnsString[] / null字段名列表(SELECT 类语句返回);无结果集时为 null
RowsString[] / null数据行列表,每一项是 JSON 串,反序列化后是 (string | null)[],按 Columns 顺序对齐;无结果集时为 null
ExecutionTimeMsNumberSQL 执行耗时(毫秒)

4. 示例代码

// 创建表
await database.executePGSql({
Sql: 'CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE)'
})

// 插入数据
const insertRes = await database.executePGSql({
Sql: "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')"
})
console.log('受影响行数:', insertRes.AffectedRows) // 1

// 查询并解析结果
const res = await database.executePGSql({
Sql: 'SELECT id, name, email FROM users WHERE id = 1'
})
console.log(res.Columns) // ['id', 'name', 'email']
const rows = (res.Rows || []).map(s => JSON.parse(s))
// rows: [['1', 'Alice', 'alice@example.com']]

// 使用指定 role 创建 RLS 策略
await database.executePGSql({
Role: 'postgres',
Sql: `CREATE POLICY avatars_public_read ON storage.objects
FOR SELECT TO public USING (bucket_id = 'avatars')`
})

// 指定其他环境 ID 执行
await database.executePGSql({
EnvId: 'other-env-id',
Sql: 'SELECT NOW()'
})