在psycopg2中为连接的所有查询设置模式:在设置search_path时获取竞争条件

And*_*sen 13 python postgresql schema psycopg2 python-3.x

我们的系统运行在Ubuntu,python 3.4,postgres 9.4.x和psycopg2上.

我们(将在未来编)之间的分裂dev,test以及prod环境的使用模式.我创建了一种方便的方法来创建与数据库的连接.它使用json连接配置文件来创建连接字符串.我想配置连接以使用返回的连接为所有后续查询使用特定模式.我不希望我的查询有硬编码模式,因为我们应该能够轻松地在它们之间切换,具体取决于我们是处于开发,测试还是生产阶段/环境.

目前,便捷方法如下所示:

def connect(conn_config_file = 'Commons/config/conn_commons.json'):
    with open(conn_config_file) as config_file:    
        conn_config = json.load(config_file)

    conn = psycopg2.connect(
        "dbname='" + conn_config['dbname'] + "' " +
        "user='" + conn_config['user'] + "' " +
        "host='" + conn_config['host'] + "' " +
        "password='" + conn_config['password'] + "' " +
        "port=" + conn_config['port'] + " "
    )
    cur = conn.cursor()
    cur.execute("SET search_path TO " + conn_config['schema'])

    return conn
Run Code Online (Sandbox Code Playgroud)

只要你给它时间来执行set search_path查询,它就可以正常工作.不幸的是,如果我执行以下查询的速度太快,则会在search_path没有设置的情况下发生竞争条件.我试图在执行conn.commit()之前强制执行return conn,但是,这会将其重置search_path为默认架构,postgres以便它不会使用,比如说prod.在数据库或应用程序层的建议是可取的,但是,我知道我们可能也可以在操作系统级别解决这个问题,也欢迎任何有关这方面的建议.

示例json配置文件如下所示:

{
    "dbname": "thedatabase",
    "user": "theuser",
    "host": "localhost",
    "password": "theusers_secret_password",
    "port": "6432",
    "schema": "prod"
}
Run Code Online (Sandbox Code Playgroud)

任何建议都非常感谢.

but*_*tla 16

我认为更优雅的解决方案是设置search_pathin options参数connect(),如下:

def connect(conn_config_file = 'Commons/config/conn_commons.json'):
    with open(conn_config_file) as config_file:    
        conn_config = json.load(config_file)

    schema = conn_config['schema']
    conn = psycopg2.connect(
        dbname=conn_config['dbname'],
        user=conn_config['user'],
        host=conn_config['host'],
        password=conn_config['password'],
        port=conn_config['port'],
        options=f'-c search_path={schema}',
    )
    return conn
Run Code Online (Sandbox Code Playgroud)

当然,您可以使用"options"作为连接字符串的一部分.但是使用关键字参数可以防止字符串连接的所有麻烦.

我在这个psycopg2功能请求中找到了这个解决方案.至于"选项"参数本身,这里提到它.


小智 6

我认为更好的想法是让像DatabaseCursor这样的东西返回你用来执行"SET search_path ..."而不是连接的查询的游标.我的意思是这样的:

class DatabaseCursor(object):

    def __init__(self, conn_config_file):
        with open(conn_config_file) as config_file:     
            self.conn_config = json.load(config_file)

    def __enter__(self):
        self.conn = psycopg2.connect(
            "dbname='" + self.conn_config['dbname'] + "' " + 
            "user='" + self.conn_config['user'] + "' " + 
            "host='" + self.conn_config['host'] + "' " + 
            "password='" + self.conn_config['password'] + "' " + 
            "port=" + self.conn_config['port'] + " " 
        )   
        self.cur = self.conn.cursor()
        self.cur.execute("SET search_path TO " + self.conn_config['schema'])

        return self.cur

    def __exit__(self, exc_type, exc_val, exc_tb):
        # some logic to commit/rollback
        self.conn.close()
Run Code Online (Sandbox Code Playgroud)

with DatabaseCursor('Commons/config/conn_commons.json') as cur:
    cur.execute("...")
Run Code Online (Sandbox Code Playgroud)