使用Psycopg2 SQL模块生成带引号标识符的查询为何仍生效?
Great question! Let's clear up the confusion here:
First off, PostgreSQL fully supports double-quoted identifiers—the documentation note you're referencing probably means that quotes are not required for valid, non-reserved identifiers (like your asin, name, etc.), not that they're forbidden.
Here's why your query works perfectly:
- Double quotes around identifiers are part of standard SQL syntax, and PostgreSQL adheres to this. When you use quotes, you're explicitly telling PostgreSQL to treat the string as a literal identifier, avoiding conflicts with reserved keywords or special characters.
- Psycopg2's
sql.Identifieradds these quotes by design for universal safety. Even if your column names were reserved keywords (likeorderoruser) or contained special characters (likemy-column), wrapping them in quotes would prevent syntax errors. For your valid, plain column names, the quotes are just harmless extra syntax—PostgreSQL parses them the same as if they weren't there. - To confirm: Try running both versions of your query (with and without quotes) and you'll get identical results. The quoted version is just more robust for edge cases you might not have encountered yet.
For example, if you had a column named order, a query like COPY parts (order, ...) would throw an error because order is a reserved keyword—but COPY parts ("order", ...) works flawlessly.
So while you could omit the quotes for your current column names, Psycopg2's approach is a smart, safe default that ensures your queries work no matter what identifiers you're using.
内容的提问来源于stack exchange,提问作者Florian

