【问题标题】:pgTAP syntax error with plpgsql but not with sqlplpgsql 的 pgTAP 语法错误,但 sql 没有
【发布时间】:2014-01-21 22:15:22
【问题描述】:

这个 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 运行测试?

【问题讨论】:

    标签: postgresql tap pgtap


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 2012-12-19
      • 2014-06-08
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      相关资源
      最近更新 更多