EXECUTE <query-string> USING value1 ...第一个替换占位符($ 1)的阻塞

时间:2015-11-06 02:08:11

标签: database postgresql plpgsql dynamic-sql postgresql-9.2

以下代码在&#34; dollar-one&#34;占位符,我不知道为什么。我试图确定我是否在这里遗漏了一些语义,或者这是否是一个实际的Postgresql核心错误,可以通过下面的代码来支持。

-- Attempt to run the following on any database.
-- Creating the relations of the correct names etc. should not be necessary,
-- as the error occurs before this would even matter.

-- The code below fails in an unexpected way because no substitution appears
-- to take place.

--
-- ERROR:  syntax error at or near "$1"
-- LINE 3:    special_constraint_trigger($1,$2,$3);
--                                       ^
-- SQL state: 42601
-- Context: PL/pgSQL function inline_code_block line 11 at EXECUTE statement
--

DO LANGUAGE plpgsql $$
DECLARE
    -- simulated parameters:
    referencing_table TEXT = 'the_great_referencer';
    referencing_column TEXT = 'fk_field';
    referenced_column TEXT = 'measurement_id';
    -- :simulated parameters
BEGIN
    EXECUTE 'CREATE CONSTRAINT TRIGGER maybe_throw_some_exceptions AFTER UPDATE OR DELETE ON measurement 
         DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE PROCEDURE 
         special_constraint_trigger($1,$2,$3);'
        USING referenced_column,referencing_table, referencing_column;
END;
$$;

其他人是否清楚为什么这个USING替换不起作用?我希望上面的内容可以简单地说明这里引用了伪造的表格和列,但在我的系统上,Postgres似乎更关注未被替换的美元符号。特别是如果其他人能够重现此错误,我将计划将其作为错误提交。

版本信息:x86_64-redhat-linux-gnu上的PostgreSQL 9.2.14,由gcc(GCC)4.8.3 20140911(Red Hat 4.8.3-9)编译,64位< / p>

操作系统:Linux 4.1.10-17.31.amzn1.x86_64#1 SMP Sat Oct 24 01:31:37 UTC 2015 x86_64 x86_64 x86_64 GNU / Linux

1 个答案:

答案 0 :(得分:3)

您的代码不起作用 - params只能与带有计划的SQL语句一起使用。 DML(INSERTUPDATEDELETE)和SELECT是计划中的陈述。 DDL语句没有计划,然后不应该参数化。因此,您不能对USINGCREATEALTER等任何DDL语句使用子句DROP。您必须执行一些没有任何参数的SQL字符串 - 以下代码应该起作用:

BEGIN
   EXECUTE format('CREATE CONSTRAINT TRIGGER maybe_throw_some_exceptions
                   AFTER UPDATE OR DELETE ON measurement 
                   DEFERRABLE INITIALLY DEFERRED
                   FOR EACH ROW EXECUTE PROCEDURE 
                   special_constraint_trigger(%I,%I,%I)',
                  referenced_column,
                  referencing_table,
                  referencing_column);
END;