从标准输入的php postgresql pdo复制 [英] php postgresql pdo copy from stdin

查看:94
本文介绍了从标准输入的php postgresql pdo复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

COPY table_name ( field1, field2, field3) FROM STDIN CSV;
1,2,"q w"
3,4,"a s"
5,6,d
\.

如何通过PDO执行此查询?

How to execute this query by PDO ?

问题是PDO驱动程序以语句的形式执行此查询.
例如,如果将其粘贴到pgAdmin中,则会引发错误.
我需要在psql中执行它:

Problem is PDO driver executes this query as statement.
For example, if you paste it into pgAdmin, it throws an error.
I need execute it in psql:

C:\Users\User>psql -e -h localhost -U postgres db_name
psql (9.1.2)
db_name=# COPY table_name ( field1, field2, field3) FROM STDIN CSV;
COPY table_name ( field1, field2, field3) FROM STDIN CSV;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 1,2,"q w"
>> 3,4,"a s"
>> 5,6,d
>> \.

推荐答案

感谢这本书

请注意,此处提供的功能有效地绕过了安全限制,这是有原因的.您的函数应对照严格的白名单条件检查提供的文件路径和表.此示例也可用于SQL注入,因为它未正确引用其输入.

CREATE OR REPLACE FUNCTION copy_from_csv_ignoring_security(table_name text, table_fieds text, file_path text, oids boolean DEFAULT false, header boolean DEFAULT false, delimeter text DEFAULT ','::text, "null" text DEFAULT ''::text, quote text DEFAULT '"'::text, escape text DEFAULT '"'::text, force_not_null text DEFAULT ''::text)
  RETURNS void AS
$BODY$

declare statement text;
begin

statement := 'COPY ' || table_name || ' (' || table_fieds || ') ' || 'FROM ''' || file_path || ''' WITH ';
IF oids THEN
 statement := statement || 'OIDS ';
end if;
statement := statement || 'DELIMITER ''' || delimeter || ''' ';
statement := statement || 'NULL ''' || "null" || ''' CSV ';
IF header THEN
 statement := statement || 'HEADER ';
end if;
statement := statement || 'QUOTE ''' || "quote" || ''' ';
statement := statement || 'ESCAPE ''' || "escape" || ''' ';
IF force_not_null <> '' THEN
statement := statement || 'FORCE NOT NULL ''' || force_not_null || ''' ';
end if;
execute statement;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE SECURITY DEFINER
  COST 100;

授予功能权利

revoke all on function copy_from_csv_ignoring_security(text, text, text, boolean, boolean, text, text, text, text, text) from public;
grant execute on function copy_from_csv_ignoring_security(text, text, text, boolean, boolean, text, text, text, text, text) to db_user;

从PHP执行

$dbh->exec('SELECT copy_from_csv_ignoring_security(...)');

=====如果版本> = 9.1.7的上述技巧不起作用. =====

解决方案:

在以下位置创建文件 .pgpass (避免输入密码提示)运行此脚本的用户的主目录.

create file .pgpass (avoid password prompt) in home directory of user which run this script.

#.pgpass contents (chmod 600 - requred)    
host:port:db_name:user_name:password

创建php函数,该函数执行元命令

create php function, which executes meta-command

function executeMetaCommand($dbUser, $dbName, $dbPort, $command)
{    
    $command = sprintf(
        "psql -U %s -p %s -d %s -f - <<EOT\n%s\nEOT\n",
        $dbUser, $dbPort, $dbName, $command
    );
    $streams = array(
        array('pipe', 'r'),// stdin
        array('pipe', 'w'),// stdout
        array('pipe', 'w') // stderr
    );
    $process = proc_open($command, $streams, $pipes);
    if (!is_resource($process)) {
        throw new Exception("Cannot open process:\n$command");
    } else {
        list(, $stdout, $stderr) = $pipes;
        $error = stream_get_contents($stderr);
        fclose($stderr);
        if (strlen($error) > 0) {
            throw new Exception("Process error:\n$error");
        } else {
            $output = stream_get_contents($stdout);
            fclose($stdout);
            $returnCode = proc_close($process);
            if ($returnCode === -1) {
                throw new Exception("Process was completed incorrectly:\n$output");
            } else {
                return array(
                    $returnCode,
                    $output
                );
            }
        }
    }
}

//usage:
$command = sprintf("\\copy table(field1, field2) FROM '%s' WITH CSV", $filePath);
executeMetaCommand('postgres', 'test_db', '5432', $command);

这篇关于从标准输入的php postgresql pdo复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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