从触发器内的文本文件中读取数据 [英] Read data from a text file inside a trigger

查看:105
本文介绍了从触发器内的文本文件中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过某种方式在触发器函数中访问文本文件上的数据?

Is there any way by which data on an text file can be accessed inside a trigger function?

推荐答案

您可以使用

如果我们谈论的是CSV文件(或类似文件),文件位于您使用的db服务器上 COPY 。我在此处引用手册。

If we are talking about CSV files (or similar) and the file is on the db server you use COPY. I quote the manual here.


具有文件名的COPY指示PostgreSQL服务器直接从文件读取
或将其写入文件。该文件必须可供服务器访问,并且必须从服务器的角度指定
的名称。

COPY with a file name instructs the PostgreSQL server to directly read from or write to a file. The file must be accessible to the server and the name must be specified from the viewpoint of the server.

有关更多信息对于复杂的操作,您可能需要使用临时表作为登台表,将文件 COPY 放入其中并从那里使用普通的SQL命令。 类似于该示例。确保您不会在尝试在同一会话中多次创建同一表时遇到冲突,尽管...

For more complex operations you might want to use a temporary table as staging table, COPY the file into it and work with plain SQL commands from there. Similar to this example. Be sure you don't run into conflicts with trying to create the same table in the same session multiple times, though ...

还有通用文件访问功能。出于安全原因,它们的使用受到很大限制:

There are also generic file access functions. For security reasons their use is rather restricted:


只能访问数据库集群目录和log_directory
中的文件。为群集
目录中的文件使用相对路径,并为日志文件使用与log_directory配置设置
匹配的路径。这些功能仅限超级用户使用。

Only files within the database cluster directory and the log_directory can be accessed. Use a relative path for files in the cluster directory, and a path matching the log_directory configuration setting for log files. Use of these functions is restricted to superusers.

我使用它来读取小型XML文件并在PostgreSQL内部进行处理。演示:

I use this to read in small XML files and process inside PostgreSQL. Demo:

CREATE OR REPLACE FUNCTION f_import_from_file()
  RETURNS boolean AS
$BODY$
DECLARE
   myxml    xml;
   datafile text := 'path/relative/to/db_cluster/myfile.xml';
BEGIN

myxml := pg_read_file(datafile, 0, 10000000);   -- 10 MB max.

-- do stuff, like INSERT ...

$BODY$

您可以使用从您的db目录到任何其他目录的符号链接来克服路径限制。

You can overcome the path restriction with a symlink from your db directory to any other directory. Be wary of possible security implications, though.

最后,您可以使用外部数据包装器来访问服务器文件系统中的数据文件。您需要其他模块 file_fdw 。每个数据库安装一次:

Finally, you could use a foreign data wrapper to access data files in the server's file system. You need the additional module file_fdw for this. Install once per database with:

CREATE EXTENSION file_fdw;

这篇关于从触发器内的文本文件中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆