问题
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