|
| 1 | +.. _ConnectionPool: |
| 2 | + |
| 3 | +Connection Pool |
| 4 | +=============== |
| 5 | + |
| 6 | +.. hint:: Connection pools can be used with Postgres and CockroachDB. |
| 7 | + |
| 8 | +Setup |
| 9 | +~~~~~ |
| 10 | + |
| 11 | +To use a connection pool, you need to first initialise it. The best place to do |
| 12 | +this is in the startup event handler of whichever web framework you are using. |
| 13 | +We also want to close the connection pool in the shutdown event handler. |
| 14 | + |
| 15 | +The recommended way for Starlette and FastAPI apps is to use the ``lifespan`` |
| 16 | +parameter: |
| 17 | + |
| 18 | +.. code-block:: python |
| 19 | +
|
| 20 | + from contextlib import asynccontextmanager |
| 21 | + from piccolo.engine import engine_finder |
| 22 | + from starlette.applications import Starlette |
| 23 | +
|
| 24 | +
|
| 25 | + @asynccontextmanager |
| 26 | + async def lifespan(app: Starlette): |
| 27 | + engine = engine_finder() |
| 28 | + assert engine |
| 29 | + await engine.start_connection_pool() |
| 30 | + yield |
| 31 | + await engine.close_connection_pool() |
| 32 | +
|
| 33 | +
|
| 34 | + app = Starlette(lifespan=lifespan) |
| 35 | +
|
| 36 | +In older versions of Starlette and FastAPI, you may need event handlers |
| 37 | +instead: |
| 38 | + |
| 39 | +.. code-block:: python |
| 40 | +
|
| 41 | + from piccolo.engine import engine_finder |
| 42 | + from starlette.applications import Starlette |
| 43 | +
|
| 44 | +
|
| 45 | + app = Starlette() |
| 46 | +
|
| 47 | +
|
| 48 | + @app.on_event('startup') |
| 49 | + async def open_database_connection_pool(): |
| 50 | + engine = engine_finder() |
| 51 | + await engine.start_connection_pool() |
| 52 | +
|
| 53 | +
|
| 54 | + @app.on_event('shutdown') |
| 55 | + async def close_database_connection_pool(): |
| 56 | + engine = engine_finder() |
| 57 | + await engine.close_connection_pool() |
| 58 | +
|
| 59 | +.. hint:: Using a connection pool helps with performance, since connections |
| 60 | + are reused instead of being created for each query. |
| 61 | + |
| 62 | +Once a connection pool has been started, the engine will use it for making |
| 63 | +queries. |
| 64 | + |
| 65 | +.. hint:: If you're running several instances of an app on the same server, |
| 66 | + you may prefer an external connection pooler - like pgbouncer. |
| 67 | + |
| 68 | +------------------------------------------------------------------------------- |
| 69 | + |
| 70 | +Configuration |
| 71 | +~~~~~~~~~~~~~ |
| 72 | + |
| 73 | +The connection pool uses the same configuration as your engine. You can also |
| 74 | +pass in additional parameters, which are passed to the underlying database |
| 75 | +adapter. Here's an example: |
| 76 | + |
| 77 | +.. code-block:: python |
| 78 | +
|
| 79 | + # To increase the number of connections available: |
| 80 | + await engine.start_connection_pool(max_size=20) |
0 commit comments