【问题标题】:psql --(record|field)-separator NULpsql --(记录|字段)-分隔符 NUL
【发布时间】:2011-07-28 10:10:18
【问题描述】:

有没有办法让psql\0 分隔字段和记录,也就是NUL?这是能够将任意数据传递给 Bash 脚本的唯一方法。

根据Matthew Wood 的回答,我希望这会在新初始化的数据库上打印出比1 更多的内容:

declare -i count=0
echo "\pset recordsep '\000'
\f '\000'
select typname from pg_type" | \
sudo -iu postgres psql --no-align --quiet --tuples-only -d dbname -U username | while IFS= read -r -d ''
do
    #echo "$REPLY"
    let count++
done
if [ -n "$REPLY" ]
then
    #echo "$REPLY"
    let count++
fi
echo $count

解决方法:如果SELECT 结果是唯一的,您可以使用此解决方法一次处理一个:

next_record() {
    psql --no-align --quiet --tuples-only -d dbname -U username <<SQL
SELECT colname
  FROM tablename
 WHERE colname > '${1}'
 ORDER BY colname
 LIMIT 1
SQL
}

last_col=
while true
do
    colx="$(next_record "$last_col"; printf x)"
    if [ "$colx" = x ]
    then
        exit
    fi
    col="${colx%$'\nx'}" # The extra \n character is from psql

    # Do your thing here

    col_escaped="${col//"'"/''}" # Double single quotes
    col_escaped="${col_escaped//\\/\\\\}" # Double backslashes
    last_col="$col_escaped"
done

【问题讨论】:

    标签: bash postgresql nul


    【解决方案1】:

    不支持。 psql 使用 C 打印函数来打印结果表,并且打印一个零字节在那里不起作用。

    更新:现在 PostgreSQL 9.2-to-be (git) 支持此功能。

    【讨论】:

    • +1 表示残酷的事实。太糟糕了,他们还没有弄清楚如何在 C 中打印 NUL 字符-sedgrepfindprintf 等等都支持它。
    • 嗯,“他们”=我,在某种程度上。如果提出了足够广泛的用例,实施起来并不难。我会记下它。
    • 这将是有史以来最好的事情 - 如果文本字段不能包含空字段,并且我正在选择已知数量的字段,我可以解析 any 值而无需担心垃圾数据。
    【解决方案2】:

    试试这个:

    psql --field-separator '\000' --no-align -c '<your query>'
    

    编辑:也许不是。但是,它似乎可以使用以下命令在 psql 中工作:

    \f '\000'
    \a
    

    【讨论】:

    • 这最终将字段分隔符设置为空字符串,而不是请求的零字节。
    【解决方案3】:

    psql support --field-separator-zero 标志的较新版本。

    【讨论】:

      猜你喜欢
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2019-04-22
      相关资源
      最近更新 更多