客户端脚本中的 PSQL lo_import

PSQL lo_import in client side script

我们维护了一个简单的 sql 脚本,它可以设置您的架构并填充一组 text/example 值 - 所以它就像创建 table、创建 table table 插入到 table... 我们 运行 它用一个简单的 shell 脚本调用 psql

我们的一个 table 需要文件——我想做的只是将文件放在与脚本相同的目录中,然后执行类似插入存储库(id、图片)值('first', lo_import('first.jpg'))

但我收到错误提示必须是超级用户才能使用服务器端脚本。有什么办法可以做到这一点?我只有一个 .sql 文件和一堆图像文件,然后通过 运行ning psql 对文件导入它们?

运行 作为超级用户不是一个选项。

使用 psql,您可以编写 shell 脚本,例如

oid=`psql -At -c "\lo_import 'first.jpg'" | tail -1 | cut -d " " -f 2`
psql -Aqt -c "INSERT INTO repository (id, picture) values ('first', $oid)"

因为评论不能有代码 - 感谢 Laurenz,我得到它 "working" 像这样:

drop table if exists some_landing_table;
create table some_landing_table( load_time timestamp, filename varchar, data bytea);

\set the_file 'example.jpg';
\lo_import 'example.jpg';
insert into some_landing_table
    select now(), 'example.jpg', string_agg(data,decode('','escape') order by pageno)
    from 
        pg_largeobject 
    where 
        loid = (select max(loid) from pg_largeobject);

select lo_unlink( max(loid) )   from pg_largeobject;

然而,这很丑陋,原因有二 -

  • 我似乎无法以任何方式将 \lo_import 的结果放入变量中。尽管 select \lo_import filename 有效 select \lo_import filename into x 无效。
  • 我不能使用变量 - 如果我这样做 \lo_import :the_file - 它只是说 example.jpg 不存在 - 尽管如果我直接把它放进去它工作得很好
  • 我找不到比 decode('','escape')
  • 更简单的提供 0 长度 bytea 字段的方法