+ linkend="functions-string">). For safety, expressions containing column
+ or table identifiers should be passed through
+ quote_ident before insertion in a dynamic query.
+ Expressions containing values that should be literal strings in the
+ constructed command should be passed through quote_literal>.
+ These functions take the appropriate steps to return the input text
+ enclosed in double or single quotes respectively, with any embedded
+ special characters properly escaped.
+
+
+ Because quote_literal is labelled
+ STRICT, it will always return null when called with a
+ null argument. In the above example, if newvalue> or
+ keyvalue> were null, the entire dynamic query string would
+ become null, leading to an error from EXECUTE.
+ You can avoid this problem by using the quote_nullable>
+ function, which works the same as quote_literal> except that
+ when called with a null argument it returns the string NULL>.
+ For example,
+EXECUTE 'UPDATE tbl SET '
+ || quote_ident(colname)
+ || ' = '
+ || quote_nullable(newvalue)
+ || ' WHERE key = '
+ || quote_nullable(keyvalue);
+
+ If you are dealing with values that might be null, you should usually
+ use quote_nullable> in place of quote_literal>.
+
+
+ As always, care must be taken to ensure that null values in a query do
+ not deliver unintended results. For example the WHERE> clause
+ 'WHERE key = ' || quote_nullable(keyvalue)
+
+ will never succeed if keyvalue> is null, because the
+ result of using the equality operator => with a null operand
+ is always null. If you wish null to work like an ordinary key value,
+ you would need to rewrite the above as
+ 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
+
+ (At present, IS NOT DISTINCT FROM> is handled much less
+ efficiently than =>, so don't do this unless you must.
+ See for
+ more information on nulls and IS DISTINCT>.)
Note that dollar quoting is only useful for quoting fixed text.
- It would be a very bad idea to try to do the above example as:
+ It would be a very bad idea to try to write this example as:
EXECUTE 'UPDATE tbl SET '
|| quote_ident(colname)
happened to contain $$>. The same objection would
apply to any other dollar-quoting delimiter you might pick.
So, to safely quote text that is not known in advance, you
- must> use quote_literal.
+ must> use quote_literal>,
+ quote_nullable>, or quote_ident>, as appropriate.
+
A much larger example of a dynamic command and