测试PostgreSQL函数
我正在将现有的Sybase系统迁移到PostgreSQL,在测试我的功能时遇到了问题。例如,我有以下代码测试PostgreSQL函数,postgresql,function,plpgsql,Postgresql,Function,Plpgsql,我正在将现有的Sybase系统迁移到PostgreSQL,在测试我的功能时遇到了问题。例如,我有以下代码 drop function if exists contract_line_ins(bigint, bigint, char(10), date, date, numeric(18, 0), numeric(18, 0), integer, bigint); create function contract_line_ins ( in _contract_id bi
drop function if exists contract_line_ins(bigint, bigint, char(10), date, date, numeric(18, 0), numeric(18, 0), integer, bigint);
create function contract_line_ins (
in _contract_id bigint,
in _product_id bigint,
in _number char(10),
in _start_date date,
in _end_date date,
in _history_access numeric(18, 0),
in _subscription_type numeric(18, 0),
inout _rows_updated integer,
inout _id bigint
)
as $$
declare
_locus int = 1; -- Set this in code to indicate current executing statement in exception
_at text; -- Used in exception handling
begin
insert into contract_line(contract_id, product_id, number, start_date, end_date, history_access, subscription_type)
values (_contract_id, _product_id, _number, _start_date, _end_date, _history_access, _subscription_type)
returning _id;
get diagnostics _rows_updated = row_count;
-- Exception handling
exception when others then
get stacked diagnostics _at = PG_EXCEPTION_CONTEXT;
raise notice E'EXCEPTION\nError: %\nMessage: %\nLocus: %\nAt: %', SQLSTATE, SQLERRM, _locus, _at;
end;
$$ language plpgsql;
我明白,在这种情况下,两个返回值都是非常有用的,但我被要求除非绝对必要,否则不要更改参数
我编写了以下测试代码
do language plpgsql $$
declare
contract_id bigint = 1;
product_id bigint = 2;
number char(10) = 'CONTRACT';
start_date date = '20160101';
end_date date = '20161231';
history_access numeric(18, 0) = 3;
subscription_type numeric(18, 0) = 4;
rows_updated int;
id bigint;
begin
perform contract_line_ins(contract_id, product_id, number, start_date, end_date, history_access, subscription_type, rows_updated, id);
raise notice E'row count % id %', rows_updated, id;
end
$$
当我执行此测试时,我得到以下结果:
[2016-06-18 05:55:17] EXCEPTION
Error: 42601
Message: query has no destination for result data
Locus: 1
At: PL/pgSQL function contract_line_ins(bigint,bigint,character,date,date,numeric,numeric,integer,bigint) line 7 at SQL statement
SQL statement "SELECT contract_line_ins(contract_id, product_id, number, start_date, end_date, history_access, subscription_type, rows_updated, id)"
PL/pgSQL function inline_code_block line 13 at PERFORM
[2016-06-18 05:55:17] row count <NULL> id <NULL>
[2016-06-18 05:55:17] completed in 43ms
[2016-06-18 05:55:17]例外
错误:42601
消息:查询没有结果数据的目标
地点:1
在:PL/pgSQL函数contract_line_ins(bigint,bigint,character,date,date,numeric,numeric,integer,bigint)SQL语句的第7行
SQL语句“选择合同行(合同id、产品id、编号、开始日期、结束日期、历史访问、订阅类型、行更新、id)”
PL/pgSQL函数内联\u代码\u块执行时的第13行
[2016-06-18 05:55:17]行计数id
[2016-06-18 05:55:17]在43毫秒内完成
我不明白的是:
返回的_id
位给出了一个异常。因为插入。。。返回的
应以列列表而不是变量名结束。如果要将插入的行列id
值设置为\u id
变量,请将其更改为将id返回到
问题2
我相信函数中会发生错误如果从insert语句中删除
返回的_id
,会发生什么情况?。。