【问题标题】:PL/pgSQL function + client-side lo_importPL/pgSQL 函数 + 客户端 lo_import
【发布时间】:2012-08-24 05:40:24
【问题描述】:

我在将文档导入 postgres db 时遇到问题。我有 plpgsql 函数,更简单的版本可能是这样的:

create function add_file(flag integer, sth varchar) returns void as
begin
   if flag = 1 then 
      insert into tab_one values (my_file_oid, sth);
   else
      insert into tab_two values (my_file_oid, sth);
   end if;
end;

和 psql 命令:

\lo_import('path/to/file');

两个代码在一个文件中。我不能将 lo_import() 放入插入语句,因为我需要客户端 lo_import。有变量 LASTOID,但在 add_file 函数中不可用。并且它不会在每次调用 add_file() 时更新。
那么,在我们的示例中,如何通过 insert 语句将 oid 放入数据库,并在函数中使用参数?文件在客户端计算机中。

【问题讨论】:

    标签: sql postgresql plpgsql psql


    【解决方案1】:

    psql's \lo_import 返回导入产生的 OID。您需要将其作为参数传递给函数,如下所示:

    CREATE FUNCTION add_file(_flag integer, _sth varchar, _oid oid)
      RETURNS void LANGUAGE plpgsql AS
    BEGIN
       IF _flag = 1 THEN
          INSERT INTO tab_one(file_oid, sth) VALUES (_oid, _sth);
       ELSE
          INSERT INTO tab_two(file_oid, sth) VALUES (_oid, _sth);
       END IF;
    END;
    

    顺便说一句:总是使用INSERT 命令将列列表添加到您的表中(可能除了临时调用)。


    在 plpgsql 函数中,您可以使用还提供的server side functions。可能看起来像这样:

    INSERT INTO tab_one(file_oid, sth) VALUES (lo_import('/etc/motd'), _sth);
    

    请注意,这在数据库服务器的文件系统中以所有者(通常是系统用户postgres)的权限运行。因此,仅限超级用户使用。

    【讨论】:

    • 我从另一个 plpgsql 代码中调用了这个函数 (add_file):create function main() returns void language plpgsql as begin (...) perform add_file(1, 'a'); end; 所以我不能在这里使用 \lo_import。感谢您提供有关 INSERT 的提示!
    • @Borgo:我为服务器端执行添加了一个变体。不过,这仅限于超级用户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2013-11-15
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2012-03-27
    相关资源
    最近更新 更多