python - 不带引号的 sql.Identifier

标签 python postgresql psycopg2

我在网络上搜索了“sql.Identifier without quoting”和 this post仅相关。建议使用 .format(sql.Identifier.

但是,此方法向标识符添加双引号,据我所知,它不能用于 PostgreSQL 中不带引号的标识符。正如我在 here 中读到的那样专家建议不要在 Postgres 中引用标识符。

我在 sql.Identifier 中没有看到跳过 the document 中引用的选项以及 psycopg2 的 sql 模块中的替代方法。如何以注入(inject)安全的方式从 Python 使用 PostgreSQL 来处理不带引号的标识符?

添加:我的困惑是由于我使用“public.abc”作为 sql.Identifier,正如 @klin 的答案中指出的那样,我应该使用两个标识符。整理之后,我发现引用仅用于区分大小写(和/或使用点等“其他”符号的情况)。

最佳答案

您应该区分两种不同的情况。当您想在区分大小写的标识符中使用大写字母时,您必须使用双引号。如果仅使用小写字母作为标识符,则可以使用双引号。专家通常建议避免第一种情况。在第二种情况下,psycopg2自动添加的引号没有问题。

请注意,public.abc 不是一个标识符,它是一个包含两个标识符的表达式。因此你应该像这样使用它:

sql.SQL("select * from {}.{}").format(sql.Identifier(schema_name), sql.Identifier(table_name))

或者这个:

sql.SQL("select * from {}").format(sql.Identifier(schema_name, table_name))

如(根据 the documentation ):

Multiple strings can be passed to the object to represent a qualified name, i.e. a dot-separated sequence of identifiers.

关于python - 不带引号的 sql.Identifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59943128/

相关文章:

Python:使用自定义比较器对字典数组进行排序?

python - 将 NetworkX 节点属性放入 Pandas Dataframe 列

拆分后 Python 更改数据框中的值

python - 使用 django 在 postgres ArrayField 上进行不区分大小写的搜索

python - 在 Cloud Functions 中使用 Cloud SQL (Postgres)

python - 转移到 GPU 时张量类型不匹配

postgresql - Postgres : authentication fails when try to login with different unix user

Postgresql 检查查询是否仍在运行

python - 无法从 Redshift 读取列名包含空格的数据

python - 使用 Python 接口(interface)查询 OLAP Mondrian(MDX、XMLA)?