Stably escaping an identifier

From: Phillip Diffley <phillip6402(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Stably escaping an identifier
Date: 2025-06-15 19:55:10
Message-ID: CAGAwPgQ+rhRaiPyrjG2DZhEgtYxRnsAa6jZYq2FdHu8Se+YWdg@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-general

I am in a situation where I need to run dynamically generated queries with
identifiers from an untrusted source. For example
SELECT * FROM <untrusted_table_name> WHERE <untrusted_column_name> = $1;

We can use format('%I', <untrusted_value>) to escape the identifier and
avoid a security vulnerability, but if the provided identifier is already
escaped, this introduces a problem. For example,
SELECT format('%I', 'my identifier');
returns "my identifier", but
SELECT format('%I', format('%I', 'my identifier'));
returns """my identifier"""
because it is escaping the previously added quotation marks.

Is there a reliable way to determine if an identifier has already been
escaped, or alternatively is there a function that will stably escape an
identifier such that the identifier will not change if the function is
called repeatedly?

Thanks,
Phillip

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2025-06-15 20:11:24 Re: Stably escaping an identifier
Previous Message Adrian Klaver 2025-06-15 16:14:52 Re: pg_restore ERROR: permission denied to change default privileges