Regex / Parse PostgreSQL names
<p>Going through PostgreSQL <a href="http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS" rel="nofollow noreferrer">Names and Identifiers</a>, I'm trying to figure out the following:</p>

<p>Is it possible to implement a regular expression (or parse it otherwise) to check whether a PostgreSQL name / identifier needs to be wrapped in double-quotes or not? And if possible, also to check if it is a Unicode-style name or not.</p>

<p>I need to inject an identifier name into an SQL query, and I would like to wrap this into double quotes only if the name needs it, because I read that adding quotes where they are not needed in fact changes the name format (see updates below).</p>

<p><strong>UPDATE-1:</strong></p>

<p>Ultimately, I need to implement the following function:</p>

<pre><code>function prepareSQLName(name) {

    if (/* this is a regular name*/) {
        return name;
    }

    if (/* this is a unicode name */) {
        return 'U&amp;"' + name + '"';
    } else {
        /* needs double quotes only */
        return '"' + name + '"';
    }
}
</code></pre>

<p>One of the major points of concern - processing non-English names. For example, the following is a perfectly valid PostgreSQL (in Russian) that doesn't require wrapping anything into double quotes:</p>

<pre><code>create table жирафы(вес int, рост int, возраст int, имя text);
select имя, вес from жирафы order by рост;
</code></pre>

<p><strong>UPDATE-2:</strong> </p>

<p>Examples of why it is such a big deal...</p>

<pre><code>CREATE TABLE Test1(name text);

-- can be queried as:
SELECT * FROM Test1
SELECT * FROM test1
SELECT * FROM "test1"

-- but not as:
SELECT * FROM "Test1"
</code></pre>

<p>another one:</p>

<pre><code>CREATE TABLE "Test2"(name text);

-- can be queried only as:
SELECT * FROM "Test2"
</code></pre>

<p>And it gets even trickier for Unicode-formatted names, ones that require <code>U&amp;</code> in front.</p>