从函数postgre执行复制命令并创建文件

时间:2019-02-07 20:15:11

标签: function unix copy greenplum

我的要求就像创建一个函数,将数据从查询复制到文件并捕获其计数。例子

  Create function xoy(query,path) returns integer as
   Copy (query) to stdout >path of file
    Get row_count of the query above
    Close

以上是需要的基本逻辑,请帮忙 Postgre SQL 8.3,绿色plump

1 个答案:

答案 0 :(得分:1)

这里是使用gpfdist和外部表的示例。这将提供最快的性能来写入外部文件。您还应该注意,可以使用PXF写入S3,HDFS和其他文件。

这是Greenplum中的示例表:

create table foo
(id int,
 fname text,
 lname text,
 city text,
 state text,
 zip text)
distributed by (id);

为此示例插入一些虚拟数据:

insert into foo 
(id, fname, lname, city, state, zip)
select i, 'foo_' || i, 'bar_' || i, 'city_' || i, 'state_' || i, 'zip_' || i
from generate_series(1, 10000) as i;

这是一个使用gpfdist的可写外部表。

create writable external table ext_foo
(like foo)
location ('gpfdist://mdw:8999/foo.txt')
format 'text' (delimiter '|' null as '')
distributed by (id);

这是您要使用的功能:

create or replace function fn_export_foo() returns void as
$$
declare

begin
    insert into ext_foo 
    select * from foo;
end

$$
language plpgsql;

现在,在mdw主机上(在可写外部表定义中指定),从bash启动gpfdist。

gpfdist -p 8999 > gpfdist_8999.log 2>&1 < gpfdist_8999.log &

现在执行功能:

select fn_export_foo();

以下是结果:

[gpadmin@mdw ~]$ head foo.txt 
42|foo_42|bar_42|city_42|state_42|zip_42
74|foo_74|bar_74|city_74|state_74|zip_74
90|foo_90|bar_90|city_90|state_90|zip_90
122|foo_122|bar_122|city_122|state_122|zip_122
234|foo_234|bar_234|city_234|state_234|zip_234
250|foo_250|bar_250|city_250|state_250|zip_250
293|foo_293|bar_293|city_293|state_293|zip_293
325|foo_325|bar_325|city_325|state_325|zip_325
341|foo_341|bar_341|city_341|state_341|zip_341
373|foo_373|bar_373|city_373|state_373|zip_373

在我的测试群集中,具有10,000条记录的文件在143毫秒内写入。