How to get the key fields for a table in plpgsql function?

纵然是瞬间 提交于 2019-12-23 05:31:03

问题


I need to make a function that would be triggered after every UPDATE and INSERT operation and would check the key fields of the table that the operation is performed on vs some conditions.

The function (and the trigger) needs to be an universal one, it shouldn't have the table name / fields names hardcoded.

I got stuck on the part where I need to access the table name and its schema part - check what fields are part of the PRIMARY KEY.


回答1:


After getting the primary key info as already posted in the first answer you can check the code in http://github.com/fgp/pg_record_inspect to get record field values dynamicaly in PL/pgSQL.




回答2:


Have a look at How do I get the primary key(s) of a table from Postgres via plpgsql? The answer in that one should be able to help you.




回答3:


Note that you can't use dynamic SQL in PL/pgSQL; it's too strongly-typed a language for that. You'll have more luck with PL/Perl, on which you can access a hash of the columns and use regular Perl accessors to check them. (PL/Python would also work, but sadly that's an untrusted language only. PL/Tcl works too.)

In 8.4 you can use EXECUTE 'something' USING NEW, which in some cases is able to do the job.



来源:https://stackoverflow.com/questions/1984675/how-to-get-the-key-fields-for-a-table-in-plpgsql-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!