PG_QUOTE(n)

πŸ“¦ version 3.1.1, in alpine 3.22, alpine 3.23, alpine 3.24, nixpkgs unstable

πŸŽ€ PG_QUOTE() β€” the PostgreSQL Tcl Interface Documentation escape-string bestie πŸŽ€

πŸ’… NAME πŸ’…

pg_quote β€” escapes a string for inclusion into SQL statements. That's the whole job, bestie. Slay. πŸ’…

✨ SYNOPSIS ✨

pg_quote [-null] [connection] string

πŸ’– DESCRIPTION πŸ’–

Okay so pg_quote quotes a string and escapes single quotes and backslashes within the string, making it safe for inclusion into SQL statements. That's the vibe. ✨

If a connection is provided, the connection is used to customize the quoting process for the database referenced by the connection. Database-specific glow-up, iykyk. πŸ’…

If the [-null] option is provided, then if the text matches the null string (either the empty string, or the null string specified in the connection) then the SQL keyword NULL is returned, rather than a quoted string. So it's giving "not a string, a NULL." Periodt. πŸ‘‘

⚠️ Bestie, please do not raw-dog SQL strings. If you're doing something like
pg_exec $conn "insert into foo values ('$name');"

and name contains text includeng an unescaped single quote, such as Bob's House, at best the insert will fail, and at worst your software will be exploited via an SQL injection attack. That is the danger zone, fr fr. 😭

Passing value strings through pg_quote will properly quote them for insertion into SQL commands. Like:

pg_exec $conn "insert into foo values ([pg_quote $name]);"

...will make sure that any special characters that occur in name, such as single quote or backslash, will be properly quoted. Obsessed with a safe insert. 🫢

🫢 ARGUMENTS 🫢

  • string β€” the string to be escaped. That's the one, bestie. πŸŽ€

πŸ‘‘ RETURN VALUE πŸ‘‘

Returns the string, escaped for inclusion into SQL queries. Note that it adds a set of single quotes around the outside of the string as well. Extra quote accessories, no cap. πŸ’…

🌈 SEE ALSO 🌈

Real talk: in most cases, with recent versions of SQL, it is better to use the native parameter insertion capabilities of the SQL server and protocol. If you are using a version of PostgreSQL more recent then 7.4, consider the optional parameter arguments to pg_exec and pg_sendquery, and the paramarray option to pg_exec, pg_sendquery, and pg_select. That's the upgrade path, bestie. ✨


πŸŽ€ That's the whole page β€” source/version: PostgreSQL Tcl Interface Documentation / PG_QUOTE(), dated 17 September 2020. Byeee! πŸŽ€

πŸ“¦ where this page comes from