简体   繁体   中英

clean way to detect if current_query() is a prepared statement?

Does anyone know a good way to detect if the result from current_query() is a prepared statement or not?

I seems that I can't simply use a string function because this would be an exampe for a prepared statement:

UPDATE table SET "x" = $1 WHERE "y" = $2 AND "z" = $3

But this would not:

UPDATE table SET "x" = '$1 + $2 = $3' WHERE "y"='$1' AND "z" = 1

Is there maybe another function I can use together with / instead of current_query() or do you have any other ideas?

You may be able to detect if current_query() is a prepared statement by looking for \\$[[:digit:]] after stripping the text of all strings. The following query would do, however it may fail in cases of intricate quote nesting:

with 
  queries(curr_query) as (
       values ($$UPDATE table SET "x" = '$1||''a'' + $2 = $3' WHERE "y"='$1' AND "z" = 1$$),
              ($$UPDATE table SET "x" = $r1$a$r1$||$1 WHERE "y" = $2 AND "z" = $3||$r1$b$r1$ $$),
              ($$UPDATE table SET "x" = $1 WHERE "y" = $2 AND "z" = $3$$)
    ),
  stripped as (
    select *, 
       regexp_replace(
         regexp_replace(
           regexp_replace(curr_query, '(["'']).*?\1', '', 'g'),
           '\$([[:alpha:]]*?)\$.*?\$\1\$', '', 'g'),
         '\$([[:alpha:]][[:alnum:]]*?)\$.*?\$\1\$', '', 'g') as stripped_query
    from queries
    )
select *, stripped_query ~ '\$[[:digit:]]' AS is_prepared
from stripped

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM