代码之家  ›  专栏  ›  技术社区  ›  stenci

升级到PostgreSQL 11:不允许在CASE中使用set返回函数

  •  0
  • stenci  · 技术社区  · 7 年前

    with doc as (select * from documents where name = doc_id)
    
    select jsonb_array_elements_text(permissions)
    from users
    where users.name = user_name
    
    union
    
    select 
      case 
        when doc.reader = user_name then 'read'
        when doc.owner = user_name then unnest(array['read','write'])
        else unnest(array[]::text[])
        end 
    from doc;
    

    这个 union 像往常一样 两个值列表,两个列表都可以有零个、一个或多个元素。

    select 可以返回零,一个或多个,因为这是 users 桌子。

    第二个 documents 表,但根据 case 决定。

    PostgreSQL 9.6按预期运行,PostgreSQL 11说:

    ERROR:  set-returning functions are not allowed in CASE
    LINE 56:    else unnest(array[]::text[])
                     ^
    HINT:  You might be able to move the set-returning function into a LATERAL FROM item.
    

    我很感激你的建议,但我不知道如何使用 LATERAL FROM 在这里。

    0 回复  |  直到 7 年前
        1
  •  5
  •   Nick Barnes    7 年前

    这里的暗示有点误导。正如它所说的,向返回函数集添加横向连接 帮助(一般来说),但我认为这对你的情况没有多大意义。

    您可以通过更改 CASE 表达式返回数组,然后取消对结果的测试:

    ...
    select 
      unnest(
        case 
          when doc.reader = user_name then array['read']
          when doc.owner = user_name then array['read','write']
          else array[]::text[]
        end
      )
    from doc;