客户端脚本中的PSQL lo_import

时间:2017-01-11 01:31:53

标签: sql postgresql psql

我们有一个简单的sql脚本,我们维护它设置你的模式并填充一组文本/示例值 - 所以它就像创建表,创建表表插入表...然后我们运行它使用简单的shell脚本调用psql

我们的一个表需要文件 - 我想要做的只是将文件放在与脚本相同的目录中,并执行类似插入存储库(id,picture)值的操作(' first', lo_import(' first.jpg'))

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

以超级用户身份运行不是一种选择。

2 个答案:

答案 0 :(得分:3)

使用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)"

答案 1 :(得分:1)

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

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字段更简单的方法