How to make psycopg2 emit nested quotes?

怎甘沉沦 提交于 2019-12-11 10:16:44

问题


As per "relation does not exist" in pg_table_size, I need to emit nested single and double quotes:

import psycopg2  as pg
from psycopg2 import sql

conn = pg.connect("dbname=test user=test")
table_name = "testDB"
cu = conn.cursor()
cu.execute(sql.SQL("SELECT pg_table_size(%s)"), (table_name,))

emits SELECT pg_table_size('testDB') which raises

psycopg2.ProgrammingError: relation "testdb" does not exist

while

cu.execute(sql.SQL("SELECT pg_table_size({t})").format(t=sql.Identifier(table_name)))

emits SELECT pg_table_size("testDB") which raises

psycopg2.ProgrammingError: column "testDB" does not exist

Obviously,

cu.execute(sql.SQL("SELECT pg_table_size(%s)"),('"testDB"',))

works fine, but I want to find the "official" way to emit SELECT pg_table_size('"testDB"').

Experimentally, the following works:

cu.execute(sql.SQL("SELECT pg_table_size(%s)"),
           (sql.Identifier(table_name).as_string(conn), ))

is this TRT?


回答1:


You can use the Postgres function quote_ident(string text):

cu.execute("SELECT pg_table_size(quote_ident(%s))", (table_name, ))

I think your last example is a good alternative for the above solution.



来源:https://stackoverflow.com/questions/52670840/how-to-make-psycopg2-emit-nested-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!