0

一般来说,我是 pg 和 dbs 的新手。我找到了一个博客数据库样板,我正在尝试添加一些计算列来返回布尔值,以确定 currentPerson(经过身份验证的用户)是否是帖子的作者。基本上,posts 表中的一个虚拟列对于每个帖子都有一个 true 或 false 来判断 currentPerson 是否创作了它。

此函数返回 currentPerson:

SELECT *
FROM myschema.person
WHERE id = nullif(current_setting('jwt.claims.person_id', true), '')::uuid

所以,我想做类似下面的事情,但这是不正确的。这在 graphiql 中显示为一个突变(我正在使用 postgraphile 来生成我的模式)。

任何关于如何在帖子表中创建isMyPost布尔计算列的提示都会很棒。

CREATE OR REPLACE FUNCTION myschema.is_my_post(
    )
    RETURNS BOOLEAN AS 
$func$
BEGIN
  SELECT *
  FROM myschema.post
  WHERE author_id = nullif(current_setting('jwt.claims.person_id', true), '')::uuid;
   IF FOUND THEN
      RETURN TRUE;
   ELSE
      RETURN FALSE;
   END IF;
END
$func$ LANGUAGE plpgsql;

4

1 回答 1

0

感谢@benjie @Graphile,答案最终是这样的:

    CREATE OR REPLACE FUNCTION myschema.post_current_person_has_reacted(
        p myschema.post)
        RETURNS boolean
        LANGUAGE 'sql'
        COST 100
        STABLE PARALLEL UNSAFE
    AS $BODY$
    select exists(
    select 1
    from myschema.post_reactions pr
    where pr.post_id = p.id
    and pr.person_id = nullif(current_setting('jwt.claims.person_id', true), '')::uuid
    )
    $BODY$;
于 2021-04-14T00:13:33.987 回答