Postgresql COPY命令 - 如何删除临时文件?

时间:2016-05-17 17:49:11

标签: postgresql plpgsql

我有程序,效果很好。

CREATE OR REPLACE FUNCTION f_dynamic_copy(_tbl     text = 'tmp1')
RETURNS void AS
$func$
DECLARE
   _filename VARCHAR;
BEGIN
  _filename := '/tmp/' || random() || '.csv';
  EXECUTE format($$COPY (select id, 1, 1, 1 from my_first_table) TO %L$$, _filename);
  EXECUTE format($$COPY my_second_table FROM %L$$, _filename);
END
$func$  LANGUAGE plpgsql;

但我想删除在此过程中创建的临时文件。怎么做?

2 个答案:

答案 0 :(得分:1)

plpgsql没有删除文件的功能。您需要在perl或python中创建存储的函数才能删除临时文件。但是你真的需要一个临时文件吗?INSERT SELECT不需要执行存储函数吗?

INSERT INTO my_second_table SELECT id, 1, 1, 1 from my_first_table

答案 1 :(得分:1)

我找到了PostgreSQL 9.3+的解决方案:

-- Delete temporary file
EXECUTE format(
  $$COPY (SELECT 1) TO PROGRAM 'rm %I'$$,
  _filename
);

所以,我的功能是

CREATE OR REPLACE FUNCTION f_dynamic_copy(_tbl     text = 'tmp1')
RETURNS void AS
$func$
DECLARE
   _filename VARCHAR;
BEGIN
  _filename := '/tmp/' || random() || '.csv';
  EXECUTE format($$COPY (select id, 1, 1, 1 from my_first_table) TO %L$$, _filename);
  EXECUTE format($$COPY my_second_table FROM %L$$, _filename);

  -- Delete temporary file
  EXECUTE format(
    $$COPY (SELECT 1) TO PROGRAM 'rm %I'$$,
    _filename
  );

END
$func$  LANGUAGE plpgsql;