从 PHP 查询时,Postgresql regexp_matches 内部视图总是 returns null

Postgresql regexp_matches inside view always returns null when queried from PHP

我有类似的观点

CREATE OR REPLACE VIEW regexp_test AS (
    SELECT regexp_matches(decode('NTB4', 'base64')::text, '(\d+)x')
)

当我从 pgAdmin 查询视图时,如预期的那样返回单个值为 50 的数组。

SELECT * FROM regexp_test

但是当我通过 pg_query('SELECT * FROM regexp_test') 从 PHP 中调用完全相同的查询时,没有任何返回。

postgres 版本 9.5.3, php 版本 7.0.3(与 5.6.14 结果相同)

PHP代码很通俗:

<?php

$link = pg_connect('host=localhost port=5432 dbname=test user=postgres password=postgres');
$qry = "SELECT * FROM regexp_test";
$res = pg_query($link, $qry);

while ($row = pg_fetch_row($res)) {
    print_r($row);
}

pg_query returns 结果资源。

$result = pg_query('SELECT * FROM regexp_test');

while ($row = pg_fetch_row($result)) {
  echo "$row";
}

pg_query returns false on error

If an error occurs, and FALSE is returned, details of the error can be retrieved using the pg_last_error() function if the connection is valid.

我发现使用 encode(decode('NTB4', 'base64'), 'escape') 而不是类型转换 decode('NTB4', 'base64')::text 解决了问题。

所以测试视图现在看起来像这样:

CREATE OR REPLACE VIEW regexp_test AS (
    SELECT regexp_matches(encode(decode('NTB4', 'base64'), 'escape'), '(\d+)x')
)

现在正在调用 pg_query('SELECT * FROM regexp_test') returns 预期结果 - 单个 row/field 其中包含 '{50}'

相同的查询

select  e'\x353078'::bytea;

psql:

中给出不同格式的结果
  bytea
----------
 \x353078

PgAdmin III 中:

  bytea
----------
 50x

For the documentation:

The bytea type supports two external formats for input and output: PostgreSQL's historical "escape" format, and "hex" format. Both of these are always accepted on input. The output format depends on the configuration parameter bytea_output; the default is hex. (Note that the hex format was introduced in PostgreSQL 9.0; earlier versions and some tools don't understand it.)

PgAdmin III(以及 PgAdmin4)可能出于历史原因将 bytea_output 的值设置为 escape,而参数的默认值为 hex。这可能会导致混乱(正如您所看到的那样)。看来pgAdmin应该不会更改参数的默认值。

您可以更改应用程序中的参数以获得与 PgAdmin 中相同的行为:

set bytea_output to escape;

当然,使用encode()也是一个很好的解决方案。