質問

I am new to PostgreSql, I am using version 8.3. I need to create a function which checks if a table has a specific trigger or not. If the trigger exists, I need drop it.

I am generating the drop query as given below:

var_DropTriggerSqlPart = 'drop trigger "' || var_TriggersRecord."triggerName" || '" on "' || var_Record."SchemaName" || '"."' || var_Record."TableName" || '";';

-- (where all 'var_' are variables with required data).

perform var_DropTriggerSqlPart;

But I don't see the triggers dropped. Could someone please let me know what I am doing wrong here?

役に立ちましたか?

解決

I think I found the answer. I changed "perform" to "execute" and made the function "volatile" instead of "stable".

他のヒント

A couple points here.

First, you are right that EXECUTE is the correct way to do this. If you are creating a trigger though there are some things to keep in mind (we do a lot of stuff like this).

The big one is that utility statements like this have no query plan and so cannot be parameterized. You are, of course, creating a string and executing it as SQL. This has all the problems it does everywhere including the possibility of SQL injection. If your function is SECURITY DEFINER then you have the possibility of privilege escalation through sql injection in your stored procedure.

This is solved by getting to know two functions very well: quote_ident() and quote_literal().

In your example above, I would recommend changing it to:

var_DropTriggerSqlPart = 'drop trigger "' || 
     quote_ident(var_TriggersRecord."triggerName") || '" on "' || 
     quote_ident(var_Record."SchemaName") || '"."' || 
     quote_ident(var_Record."TableName") || '";';

In LedgerSMB we do a lot of utility statements in UDF's and have to deal with this problem. Typically we also put most of the functions together that do this for easy review/auditing.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top