CREATE TABLE AS 在 Postgresql 的非易失性函数中是不允许的

CREATE TABLE AS is not allowed in a non-volatile function in Postgresql

我在 postgresql 10 上写过这个方法:

create or replace function get_users()
  returns TABLE(user_idd uuid, device_idd text, shapee text , datee timestamp) AS
$$
begin
  create temp table lines as
    SELECT DISTINCT user_id, device_id from olocations;
  select uuid_generate_v4(),
         o1.user_id,
         o1.device_id,
         st_astext(ST_Collect(o1.shape)),
         date(o1.creation_date_time) as date
  from olocations o1
      inner join lines on o1. device_id = lines.device_id and o1.user_id = lines.user_id
    where o1.user_id = 'd0edfc59-9923-44c3-9c34-ef5aad3cb810'
    and o1.device_id = '89984320001811791540'
group by o1.user_id, o1.device_id, date
order by date ASC ;
DROP TABLE lines;
end
$$
LANGUAGE 'plpgsql'
IMMUTABLE
SECURITY DEFINER
COST 100;

创建方法后没有任何问题,当我调用我的方法时: select * from get_users(); 我收到此错误:

sql> select  from get_users()
[2018-09-30 17:23:23] [0A000] ERROR: CREATE TABLE AS is not allowed in a non-volatile function
[2018-09-30 17:23:23] Where: SQL statement "create temp table lines as
[2018-09-30 17:23:23] SELECT DISTINCT user_id, device_id from olocations"
[2018-09-30 17:23:23] PL/pgSQL function get_users() line 3 at SQL statement

我想我不能在方法中创建 table?对吗?

函数不能是IMMUTABLE,定义为VOLATILE.

the documentation:

Any function with side-effects must be labeled VOLATILE, so that calls to it cannot be optimized away.

在这种情况下,此副作用是 table 创建。


更新。

使用 return query 到 return 查询生成的行:

  ...
  return query  
  select uuid_generate_v4(),
         o1.user_id,
         o1.device_id,
         st_astext(ST_Collect(o1.shape)),
         date(o1.creation_date_time) as date
  ...