升级到 PostgreSQL 11:CASE 中不允许设置返回函数

ste*_*nci 4 sql postgresql lateral

从 PostgreSQL 9.6 升级到 11 时,以下查询停止工作:

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;
Run Code Online (Sandbox Code Playgroud)

union照常值的两个列表,两个列表可具有零个,一个或多个元件。

第一个select可以返回零,一个或多个,因为这是users表中的内容。

第二个select总是从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.
Run Code Online (Sandbox Code Playgroud)

我很欣赏这个建议,但我不知道如何使用 a LATERAL FROMhere.

Nic*_*nes 5

这里的提示有点误导。正如它所说,向您的集合返回函数添加横向连接可能会有所帮助(通常),但我认为这对您的情况没有多大意义。

您可以通过更改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;
Run Code Online (Sandbox Code Playgroud)