You*_*tan 17 postgresql function commit
我有Postgresql函数,它必须将大约150万个数据插入表中.我想要的是我希望看到每个记录插入填充表格.目前当我尝试使用大约1000条记录时会发生什么,只有在完成函数执行后才会填充get.如果我在中途停止功能,则不会填充任何数据.即使在插入了一定数量的记录后停止,我怎样才能提交记录?
Kub*_*aun 15
这可以使用dblink完成.我展示了一个提交一个插件的示例,您需要添加while循环逻辑并提交每个循环.您可以http://www.postgresql.org/docs/9.3/static/contrib-dblink-connect.html
CREATE OR REPLACE FUNCTION log_the_dancing(ip_dance_entry text)
RETURNS INT AS
$BODY$
DECLARE
BEGIN
PERFORM dblink_connect('dblink_trans','dbname=sandbox port=5433 user=postgres');
PERFORM dblink('dblink_trans','INSERT INTO dance_log(dance_entry) SELECT ' || '''' || ip_dance_entry || '''');
PERFORM dblink('dblink_trans','COMMIT;');
PERFORM dblink_disconnect('dblink_trans');
RETURN 0;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION log_the_dancing(ip_dance_entry text)
OWNER TO postgres;
BEGIN TRANSACTION;
select log_the_dancing('The Flamingo');
select log_the_dancing('Break Dance');
select log_the_dancing('Cha Cha');
ROLLBACK TRANSACTION;
--Show records committed even though we rolled back outer transaction
select *
from dance_log;
Run Code Online (Sandbox Code Playgroud)
您要求的通常称为自主交易.
PostgreSQL目前不支持自治事务(9.4).
为了正确地支持它们,它确实需要存储过程,而不仅仅是它当前支持的用户定义函数.由于与会话和流程模型相关的各种内部原因,在PostgreSQL中实现自治tx也非常复杂.
现在,按照Bob的建议使用dblink.
如果您可以灵活地从 function 更改为 procedure,从 Postgresql 12 开始,如果您使用过程而不是由 CALL 命令调用的函数,则可以进行内部提交。因此,您的函数将更改为过程并使用 CALL 命令调用:例如:
CREATE PROCEDURE transaction_test2()
LANGUAGE plpgsql
AS $$
DECLARE
r RECORD;
BEGIN
FOR r IN SELECT * FROM test2 ORDER BY x LOOP
INSERT INTO test1 (a) VALUES (r.x);
COMMIT;
END LOOP;
END;
$$;
CALL transaction_test2();
Run Code Online (Sandbox Code Playgroud)
有关 Postgres 事务管理的更多详细信息,请访问:https : //www.postgresql.org/docs/12/plpgsql-transactions.html
| 归档时间: |
|
| 查看次数: |
23949 次 |
| 最近记录: |