跳至主要内容

withPgClient 和 withPgClientTransaction

有时您想直接使用 PostgreSQL 客户端,例如运行任意 SQL 或使用特定数据库客户端的辅助方法;这就是 withPgClient 的用武之地。

危险

lambda 一样,withPgClient 是一个逃生舱,不使用批处理。

withPgClient(executor, $data, callback)

您需要向 withPgClient 传递三个参数

  • executor - 这用于连接到数据库;您可以从您在同一数据库中拥有的任何 资源 中获取执行器
  • $data - 表示您的 callback 需要的数据的任意步骤;如果您不需要任何东西,将其设置为 constant(null)
  • callback(client, data) - 要使用数据库客户端和来自 $data 步骤的数据调用的(异步)函数

withPgClient 将从上下文中获取一个客户端,调用您的回调并等待它返回,然后释放客户端,最终解析为您的回调的返回结果。

// Grab executor from any resource
const { executor } = usersResource;

// Arbitrary data for our callback to use
const $twenty = constant(20);

// 20 + 22 = 42
const $meaningOfLife = withPgClient(
executor,
$twenty,
async (client, twenty) => {
// The client that you receive will be dependent on the adaptor you're
// using, but must have a `query` method:
const {
rows: [{ num }],
} = await client.query({ text: `select 22 as num` });

return twenty + parseInt(num, 10);
},
);

withPgClientTransaction(executor, $data, callback)

withPgClient 完全相同,只是它在调用 callback 之前启动一个事务,并在 callback 成功完成时提交它,或者在引发错误时回滚它。