当将sqlalchemy与多个方言一起使用时,仅添加方言特定的配置(例如sqlite的外键支持或postgres的server_side_cursors)会带来问题,因为所有其他方言均不了解该配置或事件。例如:
# applying postgres configuration to a sqlite3 database fails
>>> sqlalchemy.create_engine("sqlite3:///test.sqlite3", server_side_cursors=True)
...
TypeError: Invalid argument(s) 'server_side_cursors' sent to create_engine(), using configuration SQLiteDialect_pysqlite/NullPool/Engine. Please check that the keyword arguments are appropriate for this combination of components.
Run Code Online (Sandbox Code Playgroud)
但是,sqlite不需要此配置,因为它会自动流式传输结果。同样,postgres不需要启用外键支持,因为这是默认设置。
如何以一种不会破坏其他方言的方式应用该方言特定的配置?是否有一些sqlalchemy促进了此分支?有比isinstance测试更好的东西吗?
给定一个created engine,应该在engine.dialect.name(being sqlite或postgresqlhere)或engine.dialect.driver(例如eg pysqlite或psycopg2)分支。因此,外键支持应该分支,engine.dialect.name == "sqlite"因为它可以与所有驱动程序一起使用,但是该server_side_cursors设置应该分支于engine.dialect.driver == "psycopg2",因为Postgres的其他驱动程序不支持此设置。
感谢Freenode#sqlalchemy上的nosklo作为指针。
| 归档时间: |
|
| 查看次数: |
726 次 |
| 最近记录: |