检查查询计数并在 PostgreSql 函数中执行操作

问题描述 投票:0回答:1

我有以下功能

CREATE OR REPLACE FUNCTION public.view_function()
 RETURNS TABLE (
    uid VARCHAR,
    namingid VARCHAR,
    service VARCHAR,
    servicetype VARCHAR,
    name VARCHAR,
    location VARCHAR )

 LANGUAGE plpgsql
AS $function$
declare

    count     Integer;

begin

    RETURN QUERY 
  SELECT DISTINCT etm.uid,
  etm.namingid,
  etm.service,
  etm.servicetype,
  el.name,
  el.location
  FROM public.table1 etm
   LEFT JOIN public.table2 bt ON etm.namingid = bt.businessid
   LEFT JOIN public.table3 at2 ON etm.namingid = at2.aliasid
   LEFT JOIN table4 el ON etm.uid::text = el.uid::text AND etm.namingid::text = el.name::text;

END; $function$
;

我想将查询结果上传到aws存储桶中。但在此之前,我需要知道计数,然后如果计数大于零,则导出查询输出的数据。

我想在函数中调用此

aws_s3.query_export_to_s3
,仅当查询的输出大于零时。我们也需要在
aws_s3.query_export_to_s3
方法中使用查询作为参数,但是如何避免它运行两次,检查计数,然后获取查询输出。只想在单次执行中完成。

就像,运行查询,将输出数据存储在某个

tmp
变量中,检查该变量的计数,如果其等级小于零,则导出该
tmp
变量。类似这样的事情..

找不到方法。有人可以建议吗?

postgresql amazon-web-services amazon-s3 amazon-rds
1个回答
0
投票

PL/pgSQL 公开了

ROW_COUNT
系统状态指示器。您可以将函数的输出保存到临时表和
if ROW_COUNT>0 then
中,然后才进行导出。 db<>fiddle 的演示:

CREATE OR REPLACE FUNCTION public.view_function()
 RETURNS TABLE (
    uid         TEXT,
    namingid    TEXT,
    service     TEXT,
    servicetype TEXT,
    name        TEXT,
    location    TEXT)
LANGUAGE sql AS $function$
SELECT DISTINCT etm.uid,
  etm.namingid,
  etm.service,
  etm.servicetype,
  el.name,
  el.location
FROM         public.table1 etm
   LEFT JOIN public.table2 bt  ON etm.namingid = bt.businessid
   LEFT JOIN public.table3 at2 ON etm.namingid = at2.aliasid
   LEFT JOIN table4 el         ON  etm.uid::text = el.uid::text 
                              AND etm.namingid::text = el.name::text 
$function$;
create procedure public.export_not_empty_view_function_output_to_s3() 
language plpgsql as $p2$
declare v_rowcount int;
begin
  create temp table tmp_output on commit drop 
    as select * from public.view_function();
  GET DIAGNOSTICS v_rowcount=ROW_COUNT;
  if v_rowcount>0 then
    perform aws_s3.query_export_to_s3('select * from tmp_output;');
  end if;
  drop table tmp_output;
end $p2$;

您还可以将其设为一个函数,并传递通常从

aws_s3.query_export_to_s3()
输出的状态,或者如果最终不尝试导出,则传递一堆 null 或 0。

create function public.export_not_empty_view_function_output_to_s3() 
returns table (rows_uploaded bigint,
               files_uploaded bigint,
               bytes_uploaded bigint) language plpgsql as $p2$
declare v_rowcount int;
begin
  create temp table tmp_output on commit drop 
    as select * from public.view_function();
  GET DIAGNOSTICS v_rowcount=ROW_COUNT;
  if v_rowcount>0 then
    return query select * from aws_s3.query_export_to_s3('select * from tmp_output;');
  end if;
  return query select null,null,null;
  --return query select 0,0,0;
  drop table tmp_output;
end $p2$;
© www.soinside.com 2019 - 2024. All rights reserved.