如何将 SQL 查询返回值绑定到 psql 变量?

如何将 SQL 查询返回值绑定到 psql 变量?

问题描述:

背景:我正在为 PL/pgSQL 函数编写我的第一个 pgTAP 测试用例,并从 psql 测试脚本开始.没有问题,但我遇到了一个小烦恼 psql 变量.

Background: I'm writing my first pgTAP test cases for a PL/pgSQL function and starting small with psql test scripts. No problems on that but I run into a small annoyance on psql variables.

在我的测试脚本中,我首先将相当多的测试数据转储到相关表,然后通过序列生成的主键引用数据.我发现能够创建一个包含主键的变量很方便.这就是我要找的:

In my test scripts I first dump quite a bit of test data to a relevant tables and later refer to the data with a primary keys that were generated by sequences. I'd find it handy to be able to create a variable that would contain the primary key. This is what I'm looking for:

scalasb=> \set the_id (select currval('id_data_id_seq'))
scalasb=> \echo :the_id
54754
scalasb=> 

但这就是我得到的:

scalasb=> \set the_id (select currval('id_data_id_seq'))
scalasb=> \echo :the_id
(selectcurrval('id_data_id_seq'))
scalasb=> 

我有一个解决方法(请参见下面的示例),但看起来 psql 变量不是这项工作的正确工具.或者它们只是我在 Oracle sqlplus 中使用的不同 绑定变量一个> ...

I have a workaround (please see the example below), but it looks like psql variables are not the right tool for this job. Or they are just a different of what I've used with Oracle sqlplus bind variables ...

所以我的问题是:如何将 SQL 查询的返回值绑定到 psql 脚本中的变量中?

So my question: how I can bind the return value of a SQL query into a variable in psql script ?

我正在使用 9.1 的 linux.

I'm working on a linux with 9.1.

-- this is a simplified example to illustrate the problem
begin;

create table id_data(id serial primary key, data text not null);

create or replace function get_text(p_id bigint)
returns text
as $$
declare
  v_data constant text := data from id_data where id = p_id;
begin
  return v_data;
end;
$$ language plpgsql;

insert into id_data(data) values('lorem ipsum');

-- this works correctly but is a rather verbose (especially when one have
-- more of these, in the same query/function)
select get_text((select currval('id_data_id_seq')));

-- instead I'd like to set the id to a variable and use that but this
-- seems to be impossible with psql, right ?
\set the_id (select currval('id_data_id_seq'))
\echo First try: :the_id
--select get_text(:the_id); -- this will fail

-- this works and reveals psql variables' true nature - they are just a
-- textual replacements
\set the_id '(select currval(\'id_data_id_seq\'))'
\echo Second try: :the_id
select get_text(:the_id);

rollback;

恐怕你做不到 - 我为 psql 写了一些补丁,但它不在核心中

I afraid so you cannot do it - I wrote some patches for psql, but it is not in core

您可以使用解决方法:

postgres=# \set myvar `psql -A -t -c "select version()" postgres `
postgres=# \echo :myvar
PostgreSQL 9.1.4 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.7.0 20120507 (Red Hat 4.7.0-5), 64-bit