首页 > 解决方案 > PostgreSQL 上的事务语句构成的函数

问题描述

我想通过用户networkIdrecoyx.user昵称recoyx_private.user(该功能基于浏览这篇PostGraphile 教程(PostGraphile 结合了 GraphQL 和 PostgreSQL)。

create function recoyx.authenticate(
    network_id text,
    password_hash text
) returns recoyx.jwt_token
begin;
    set local id to (select (numeric_id) from recoyx.user where user.network_id = $1).numeric_id;
    select (numeric_id, password_hash)::recoyx.jwt_token
        from recoyx_private.user
        where user.numeric_id = id and user.password_hash = $2;
end;

查询运行器在整个函数中给出了无效的语法,包括select * from recoyx.table where table.field = value事务帧和id绑定部分。我从这个例子中获取了查询运行器,它为 PostgreSQL 数据库的初始化、查询和释放查询运行器提供了一个简短的工具(我通过这个postgraphile 模块 API 文档来到这里)。

当我从查询中消除此功能时,它运行良好。据我刚刚看到的点是有效的,本地分配也是如此。那么我的语法真的错了吗?

更新

现在这是我的功能:

create function recoyx.authenticate(
    network_id text,
    password_hash text
) returns recoyx.jwt_token
as
$body$
    select (numeric_id, password_hash)::recoyx.jwt_token
        from recoyx_private.user
        where   numeric_id = (select numeric_id from recoyx.user where network_id = $1)
            and password_hash = $2;
$body$
language sql
stable;

我得到了未定义的关系,但是postgres当我运行create function查询时,我正在连接到我的 PostgreSQL 安装(角色)中的默认 root 角色

我已经把项目放在了GitHub 上。我正在运行查询npm run init-database。请参阅environment-example.json(它指定了传统的“postgres”角色)。

标签: node.jspostgresqlpostgraphile

解决方案


如手册中所述,函数体在 Postgres 中作为字符串传递(并且您链接到的教程实际上包含了必要的as $$ ...$$内容 - 您只是没有复制它)。您还忘记指定函数的语言。

set local id既不是PL/pgSQL中的有效变量赋值,也不是 SQL(没有变量开头)。

但是你真的不需要一个变量来做你想做的事,你的函数可以实现为一个 SQL 函数:

create function recoyx.authenticate(
    network_id text,
    password_hash text
) returns recoyx.jwt_token
as
$body$
  select (numeric_id, password_hash)::recoyx.jwt_token
  from recoyx_private.user
  where user.numeric_id = (select numeric_id 
                           from recoyx.user 
                           where network_id = $1)
    and user.password_hash = $2;
$body$
language sql
stable;

推荐阅读