1

I am currently working on a new web application that needs to execute an SQL statement before giving a session to the application itself.

In detail: I am running a PostgreSQL database server with multiple schemas and I need to execute a SET search_path statement before the application uses the session. I am also using the ZopeTransactionExtension to have transactions automatically handled at the request level.

To ensure the exectuion of the SQL statement, there seem to be two possible ways:

Since I am using a scoped session and want to keep my transactions intact, I wonder which of these ways will possibly disturb transaction management.

For example, does the Engine hand out a new connection from the Pool on every query? Or is it attached to the session for its lifetime, i.e. until the request has been processed and the session & transaction are closed/committed?

On the other hand, since I am using a scoped session, can I perform it the way zzzeek suggested it in the second link? That is, is the context preserved and automatically reset once the transaction is over?

Is there possibly a third way that I am missing?

4

1 回答 1

4

例如,引擎是否会在每次查询时从池中分发一个新连接?

仅当您有 autocommit=True 时,情况并非如此。

或者它是否在其生命周期内附加到会话,即直到请求被处理并且会话和事务被关闭/提交?

它附加在每笔交易中。但是 Postgresql 中的“search_path”是每个 postgresql 会话(不要与 SQLAlchemy 会话混淆)——它基本上是连接本身的生命周期。

如今,会话(以及引擎和池)有大量的事件挂钩,您可以抓住这些挂钩来设置这样的状态。如果您想坚持使用 Session ,可以尝试after_begin

于 2013-06-23T00:59:03.523 回答