【问题标题】:psycopg2's sql.Identifier throwing "No function matching..." errorpsycopg2 的 sql.Identifier 抛出“没有函数匹配...”错误
【发布时间】:2021-07-08 23:10:26
【问题描述】:

sql.SQL() 可以正常工作,但是我遇到了 sql.Identifier 和 sql.Literal 的问题。两者都会抛出这样的错误:

cur.execute(sql.SQL("""
psycopg2.errors.UndefinedFunction: function identifier(unknown) does not exist
LINE 3:      Identifier('table_name')
             ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

这是我正在使用的代码:

cur.execute(sql.SQL("""
select 
  {}
from
  information_schema.tables
where
  table_schema = 'my_schema';
""".format(sql.Identifier('table_name'))))

我已尽可能按照说明进行操作,而且据我所知,一切都是正确的。我也从 psycopg2 导入了 sql 并建立了我的连接。如果我删除 sql.SQL 和 sql.Identifier 并将 sql 作为字符串传递以执行,它可以完美运行,但是,我希望它尽可能安全,因为其他部分可能有用户输入。我做错了什么,或者有没有办法让它工作,我还没有偶然发现?

Psycopg2 也完全是最新的。

【问题讨论】:

  • 不幸的是,我也尝试过,结果相同。我已将错误更新为完整错误,以防万一,就像现在使用单引号一样。
  • 刚试了一下,结果一样。据我所知,是 Identifier 函数不起作用。

标签: python sql postgresql psycopg2


【解决方案1】:

我在深入研究 psycopg2 中的 sql.py 文件时找到了答案。似乎说明没有列出它,但它需要.as_string(conn) 在标识符/文字之前。添加后,一切正常。

【讨论】:

    【解决方案2】:

    您遇到错误是因为您正在格式化查询字符串而不是 sql.SQL 对象。

    长话短说:

    from psycopg2 import sql
    
    $> sql.SQL.format
    >>> <function psycopg2.sql.SQL.format(self, *args, **kwargs)>
    

    所以,如果你直接格式化你的字符串,你最终会得到一个错误的 SQL 查询(格式不正确):

    $> query = sql.SQL("""
        select {} from information_schema.tables where table_schema = 'my_schema';
        """.format(sql.Identifier('table_name')))                              
    $> query.as_string(conn)                                                 
    >>> "select Identifier('table_name') from information_schema.tables where table_schema = 'my_schema'; "
    

    否则,如果您格式化 sql.SQL 对象:

    $> query = sql.SQL("""
       select {} from information_schema.tables where table_schema = 'my_schema';
       """).format(sql.Identifier('table_name'))
    $> query.as_string(conn)
    >>> 'select "table_name" from information_schema.tables where table_schema = \'my_schema\';'
    

    More informations about: sql.SQL.format(*args, **kwargs)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 2012-12-28
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多