python-ddd icon indicating copy to clipboard operation
python-ddd copied to clipboard

sqlalchemy sessions

Open SarloAkrobata opened this issue 2 years ago • 1 comments

https://github.com/pgorecki/python-ddd/blob/79f9558a8d6a7e97e7f7b3fdb084517fd43ee6b1/src/modules/bidding/application/query/get_bidding_details.py#L24

how did you ensure how many connections to the database can be made? I don't see some connection pool used, or it is injected through container?Thank you.

SarloAkrobata avatar Sep 22 '23 11:09 SarloAkrobata

I'll try to walk you through:

get_bidding_details is a GetBiddingDetails query handler as it is decorated with @bidding_module.query_handler.

When calling application.execute_query(GetBiddingDetails(...)), get_bidding_details is being called within a TransactionContext. The role of a TransactionContext is to inject any parameters required by a function (via its dependency provider).

This is the query execution flow flow:

  1. TransactionContext is entered (https://github.com/pgorecki/python-ddd/blob/79f9558a8d6a7e97e7f7b3fdb084517fd43ee6b1/src/config/container.py#L103C9-L103C37), a new session is created
  2. The handler's params are provided by TransactionContext, and the handler is executed
  3. TransactionContext is exited (https://github.com/pgorecki/python-ddd/blob/79f9558a8d6a7e97e7f7b3fdb084517fd43ee6b1/src/config/container.py#L115), the session is committed and closed.

Note that:

  1. TransactionContext uses IocProvider to provide any dependencies the handler requires.
  2. some of the dependencies are transaction scoped (i.e. session, repositories, logger), and some of them are singletons (i.e. sqlalchemy engine) - that's why we have TransactionContainer and TopLevelContainer.

Now let's back to your original question about the number of database connections. This is controlled by the pool_size parameter of create_engine, which defaults to 5. (https://docs.sqlalchemy.org/en/20/core/engines.html#sqlalchemy.create_engine.params.pool_size)

More about pooling: https://docs.sqlalchemy.org/en/20/core/pooling.html

Hope this helps.

pgorecki avatar Oct 05 '23 11:10 pgorecki