方言特定的sqlalchemy配置

时间:2014-03-08 11:16:42

标签: sqlalchemy

当使用sqlalchemy和多种方言时,只需添加特定于方言的配置,例如sqlite's foreign key support或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.

但是,sqlite不需要此配置,因为它会自动传输结果。类似地,postgres不需要启用外键支持,因为这是默认值。

如何以一种不破坏其他方言的方式应用这种特定于方言的配置?是否有一些sqlalchemy促进这种分支?有没有比isinstance测试更好的东西?

1 个答案:

答案 0 :(得分:5)

如果创建了engine,则应该分支engine.dialect.name(此处为sqlitepostgresql)或engine.dialect.driver(例如pysqlite }或psycopg2)。因此,外键支持应该在engine.dialect.name == "sqlite"上分支,因为它适用于所有驱动程序,但server_side_cursors设置应该分支在engine.dialect.driver == "psycopg2",因为Postgres的其他驱动程序不支持此设置。

感谢Freenode#sqlalchemy上的nosklo指针。