【问题标题】:how to dynamically create an output file for psql如何为 psql 动态创建输出文件
【发布时间】:2023-03-05 06:16:01
【问题描述】:

我有一个用于更改数据库的 SQL 脚本。出于审计和可追溯性的原因,我希望脚本根据 DBNAME 和时间戳生成输出文件名。

db_test=> select 'script_output-' || :'DBNAME' || '-' ||
 to_char(now(),'yyyymmdd-HH24MISS') || '.txt' as spoolfile;
                 spoolfile
--------------------------------------------
 script_output-db_test-20190718-163936.txt

但是,当我尝试将查询结果分配给 \out 运算符时,我得到以下

db_test=> \out select 'script_output-' || :'DBNAME' || '-' || to_char(now(),'yyyymmdd-HH24MISS') || '.txt'
\out: extra argument "script_output-" ignored
\out: extra argument "||" ignored
\out: extra argument ":'DBNAME'" ignored
\out: extra argument "||" ignored
\out: extra argument "-" ignored
\out: extra argument "||" ignored
\out: extra argument "to_char(now(),yyyymmdd-HH24MISS)" ignored
\out: extra argument "||" ignored
\out: extra argument ".txt" ignored

实际创建的输出文件名为select

SDV184022L:~ myuser$ ls -la Downloads/DB-Install/sele*
-rw-r--r--  1 myuser  myuser     0B Jul 18 11:42 Downloads/DB-Install/select

基于这些结果和大量搜索,我将假设这是不可能的,那么有没有人有另一种方法来完成为输出指令生成动态文件名?

【问题讨论】:

    标签: postgresql psql


    【解决方案1】:

    查询生成的结果可以通过\gset 传输到 psql 中的自动实例化变量。变量的名称是列的名称。试试

    db_test=> select 'script_output-' || :'DBNAME' || '-' ||
     to_char(now(),'yyyymmdd-HH24MISS') || '.txt' as spoolfile
     \gset
    

    那你就可以了

    db_test=> \out :spoolfile
    

    请注意,变量是通过“宏”类型的扩展来处理的。因此,如果 :spoolfile 的值恰好包含空格或反斜杠,psql 会将它们解释为好像它们是在命令行中输入的一样。

    【讨论】:

    • 感谢您的解决方案,这正是我想要的。将其添加到我的 SQL 模板文件中。
    【解决方案2】:

    您可以使用psql 变量来存储查询结果,方法是在其中运行psql 命令。

    knayak=# \set v_spoolfile `psql -A -t -c "select 'script_output-' ||  current_database() || '-' ||to_char(now(),'yyyymmdd-HH24MISS') || '.txt' as spoolfile" yourdbname`
    knayak=# \echo :v_spoolfile
    script_output-knayak-20190718-225537.txt
    knayak=# \out :v_spoolfile
    

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2022-10-08
      • 2020-06-20
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多