psql - 将查询和查询的输出写入文件

Way*_*rad 10 postgresql psql

在postgresql 9.3.1中,当使用psql命令交互式开发查询时,最终结果有时会将查询结果写入文件:

boron.production=> \o /tmp/output
boron.production=> select 1;
boron.production=> \o
boron.production=> \q
$ cat /tmp/output
?column? 
----------
        1
(1 row)
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,如何将查询本身与查询结果一起写入文件?

我试过给psql --echo-queries开关:

   -e, --echo-queries
       Copy all SQL commands sent to the server to standard output as well.
       This is equivalent to setting the variable ECHO to queries.
Run Code Online (Sandbox Code Playgroud)

但这总是与stdout相呼应,而不是我用\ o命令给出的文件.

我也试过了这个--echo-all开关,但它似乎没有回应交互式输入.

使用命令编辑,我可以\qecho在它前面重复查询.这很有效,但很乏味.

有没有办法指导交互式psql会话将查询和查询输出都写入文件?

Luc*_*ati 16

您可以尝试直接从shell重定向stdout到文件(Win或Linux应该工作)

psql -U postgres -c "select 1 as result" -e nomedb >> hello.txt
Run Code Online (Sandbox Code Playgroud)

这样做的缺点是不允许您以交互方式查看输出.如果这是一个问题,您可以在单独的终端中拖尾输出文件,或者,如果在*nix中,则使用该tee实用程序:

psql -U postgres -c "select 1 as result" -e nomedb | tee hello.txt
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

卢卡


小智 6

我知道这是一个老问题,但至少在9.3和当前版本中,这可以使用文档中显示的查询缓冲区元命令或\?来自psql控制台:https://www.postgresql.org/docs/9.3/static/app-psql.html

\w or \write filename
\w or \write |command

Outputs the current query buffer to the file filename or pipes it to the shell command command.
Run Code Online (Sandbox Code Playgroud)