使用 psycopg cur.execute 创建 postgres 模式

ala*_*ter 3 postgresql psycopg2

我的 python 应用程序允许用户创建他们命名的模式。我需要一种保护应用程序免受 sql 注入的方法。

要执行的SQL读取

CREATE SCHEMA schema_name AUTHORIZATION user_name;
Run Code Online (Sandbox Code Playgroud)

psycopg 文档(通常)建议像这样传递参数来执行

conn = psycopg2.connect("dbname=test user=postgres")
cur = conn.cursor()
query = 'CREATE SCHEMA IF NOT EXISTS %s AUTHORIZATION %s;'
params = ('schema_name', 'user_name')
cur.execute(query, params)
Run Code Online (Sandbox Code Playgroud)

但这会导致带有单引号的查询失败:

CREATE SCHEMA 'schema_name' AUTHORIZATION 'user_name';
> fail
Run Code Online (Sandbox Code Playgroud)

有没有办法删除引号,或者我应该满足于从模式名称中删除非字母数字字符并称之为一天?后者看起来有点丑,但应该仍然有效。

Clo*_*eto 5

要传递标识符,请使用AsIs. 但这暴露于 SQL 注入:

import psycopg2
from psycopg2.extensions import AsIs

conn = psycopg2.connect(database='cpn')
cursor = conn.cursor()
query = """CREATE SCHEMA %s AUTHORIZATION %s;"""
param = (AsIs('u1'), AsIs('u1; select * from user_table'))
print cursor.mogrify(query, param)
Run Code Online (Sandbox Code Playgroud)

输出:

CREATE SCHEMA u1 AUTHORIZATION u1; select * from user_table;
Run Code Online (Sandbox Code Playgroud)