Using EXECUTE ... USING with the format() function and its format specifiers will make your code much safer, simpler, easier to read, and probably faster.
SQL WARNING WARNING . If you ever accept source_geom or target_geom from the end user, your code is potentially vulnerable to SQL injection . It is important to use parameterized statements (e.g. EXECUTE ... USING ) or, if not, paranoid quotation to prevent SQL injection attacks. Even if you donβt think your function requires user input, you should still strengthen it against SQL injection because you donβt know how your application will develop.
If you use the new PostgreSQL with the format function , your code can be greatly simplified:
EXECUTE format('update %I SET source = %L, target = %L WHERE %I = %L', geom_table, source_geom, target_geom, gid_cname, _r.id);
... which processes the identifier ( %I ) and the literal ( %L ) for you using format specifiers, so you donβt have to write all these terrible || concatenation and quote_literal / quote_ident things.
Then, according to the documentation for EXECUTE ... USING , you can further refine the request:
EXECUTE format( 'update %I SET source = $1, target = $2 WHERE %I = $3', geom_table, gid_cname ) USING source_geom, target_geom, _r.id;
which turns a query into a parameterized statement, clearly separating parameters from identifiers and reducing the cost of processing strings for a more efficient query.
Craig Ringer
source share