如何使用SQL Alchemy和pg8000指定搜索路径?



我正在尝试使用SQL Alchemy和pg8000驱动程序连接到postgres db。我想为这个连接指定一个搜索路径。对于Psycopg驱动程序,我可以这样做:

engine = create_engine(
'postgresql+psycopg2://dbuser@dbhost:5432/dbname',
connect_args={'options': '-csearch_path={}'.format(dbschema)})

但是,这不适用于pg8000驱动程序。有什么好办法吗?

您可以像使用psycopg2一样使用pg8000,只需要从postgresql+psycopg2交换方案到postgresql+pg8000

完整的连接字符串定义在SQLAlchemypg8000文档中:

postgresql+pg8000://user:password@host:port/dbname[?key=value&key=value...]

但是当psycopg2.connect将kwargs传递给服务器时(像options和它的内容一样),pg8000.connect不会,所以没有设置search_pathpg8000

SQLAlchemy文档描述了如何做到这一点。例如:

from sqlalchemy import create_engine, event, text

engine = create_engine("postgresql+pg8000://postgres:postgres@localhost/postgres")
@event.listens_for(engine, "connect", insert=True)
def set_search_path(dbapi_connection, connection_record):
existing_autocommit = dbapi_connection.autocommit
dbapi_connection.autocommit = True
cursor = dbapi_connection.cursor()
cursor.execute("SET SESSION search_path='myschema'")
cursor.close()
dbapi_connection.autocommit = existing_autocommit

with engine.connect() as connection:
result = connection.execute(text("SHOW search_path"))
for row in result:
print(row)

但是,正如文档中所说:

SQLAlchemy通常是围绕保持这个概念组织的变量的默认值public

最新更新