pgTAP语法错误与plpgsql但不与sql

时间:2014-01-21 22:15:23

标签: postgresql tap pgtap

此pgTAP测试

BEGIN;

CREATE OR REPLACE FUNCTION test.testXUnitStyle() RETURNS SETOF TEXT AS $$
    SELECT ok(4 * 5 = 20, 'math should work in postgres');
$$ LANGUAGE plpgsql;

SELECT * FROM runtests('test'::name);

给我这个语法错误:

prove --ext .sql t/pgtap-xunit.sql  --source pgTAP --pgtap-option dbname=test
psql:t/pgtap-xunit.sql:5: ERROR:  syntax error at or near "SELECT"
LINE 2:     SELECT ok(4 * 5 = 20, 'math should work in postgres');
            ^
t/pgtap-xunit.sql .. Dubious, test returned 3 (wstat 768, 0x300)
No subtests run

Test Summary Report
-------------------
t/pgtap-xunit.sql (Wstat: 768 Tests: 0 Failed: 0)
  Non-zero exit status: 3
  Parse errors: No plan found in TAP output
Files=1, Tests=0,  0 wallclock secs ( 0.03 usr +  0.00 sys =  0.03 CPU)
Result: FAIL

但如果我将LANGUAGE plpgsql更改为LANGUAGE sql,则可以正常工作。

如何以plpgsql运行测试我需要做什么?

1 个答案:

答案 0 :(得分:1)

PL / PgSQL有不同的结构。你不能只复制一个SQL函数体,声明它language plpgsql,并期望它能够工作。

独立运行,你会看到:

regress=> CREATE SCHEMA test;
CREATE SCHEMA
regress=> CREATE OR REPLACE FUNCTION test.testXUnitStyle() RETURNS SETOF TEXT AS $$
    SELECT ok(4 * 5 = 20, 'math should work in postgres');
$$ LANGUAGE plpgsql;
ERROR:  syntax error at or near "SELECT"
LINE 2:     SELECT ok(4 * 5 = 20, 'math should work in postgres');
            ^

如果您read the manual for Pl/PgSQL,您将很快理解原因:PL / PgSQL的整体结构为[DECLARE ...] BEGIN ... END;。您还必须使用PERFORM运行查询并放弃结果,或RETURN QUERY如果您希望返回结果。因此,您将PL / PgSQL中的代码重写为:

CREATE OR REPLACE FUNCTION test.testXUnitStyle() RETURNS SETOF TEXT AS $$
BEGIN
    RETURN QUERY SELECT ok(4 * 5 = 20, 'math should work in postgres');
END;
$$ LANGUAGE plpgsql;