|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from fastapi import FastAPI |
| 4 | + |
| 5 | +import asyncpg |
| 6 | +import typing |
| 7 | + |
| 8 | + |
| 9 | +async def noop(db: asyncpg.Connection): |
| 10 | + return |
| 11 | + |
| 12 | + |
| 13 | +class configure_asyncpg: |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + app: FastAPI, |
| 17 | + dsn: str, |
| 18 | + *, |
| 19 | + init_db: typing.Callable = None, # callable for running sql on init |
| 20 | + pool=None, # usable on testing |
| 21 | + **options, |
| 22 | + ): |
| 23 | + self.app = app |
| 24 | + self.dsn = dsn |
| 25 | + self.init_db = init_db |
| 26 | + self.con_opts = options |
| 27 | + self._pool = pool |
| 28 | + self.app.router.add_event_handler("startup", self.on_connect) |
| 29 | + self.app.router.add_event_handler("shutdown", self.on_disconnect) |
| 30 | + |
| 31 | + async def on_connect(self): |
| 32 | + if self._pool: |
| 33 | + self.app.state.pool = self._pool |
| 34 | + return |
| 35 | + pool = await asyncpg.create_pool(dsn=self.dsn, **self.con_opts) |
| 36 | + async with pool.acquire() as db: |
| 37 | + await self.init_db(db) |
| 38 | + self.app.state.pool = pool |
| 39 | + |
| 40 | + async def on_disconnect(self): |
| 41 | + await self.app.state.pool.close() |
| 42 | + |
| 43 | + def on_init(self, func): |
| 44 | + self.init_db = func |
| 45 | + return func |
| 46 | + |
| 47 | + @property |
| 48 | + def pool(self): |
| 49 | + return self.app.state.pool |
| 50 | + |
| 51 | + async def connection(self): |
| 52 | + async with self.pool.acquire() as db: |
| 53 | + yield db |
| 54 | + |
| 55 | + async def transaction(self): |
| 56 | + async with self.pool.acquire() as db: |
| 57 | + txn = db.transaction() |
| 58 | + await txn.start() |
| 59 | + try: |
| 60 | + yield db |
| 61 | + except: |
| 62 | + await txn.rollback() |
| 63 | + raise |
| 64 | + else: |
| 65 | + await txn.commit() |
| 66 | + |
| 67 | + atomic = transaction |
| 68 | + |
| 69 | + |
| 70 | +class SingleConnectionTestingPool: |
| 71 | + """A fake pool that simulates pooling, but runs on |
| 72 | + a single transaction that it's rolled back after |
| 73 | + each test. |
| 74 | + With some large schemas this seems to be faster than |
| 75 | + the other approach |
| 76 | + """ |
| 77 | + |
| 78 | + def __init__( |
| 79 | + self, |
| 80 | + conn: asyncpg.Connection, |
| 81 | + initialize: typing.Callable = None, |
| 82 | + add_logger_postgres: bool = False, |
| 83 | + ): |
| 84 | + self._conn = conn |
| 85 | + self.tx = None |
| 86 | + self.started = False |
| 87 | + self.add_logger_postgres = add_logger_postgres |
| 88 | + self.initialize = initialize |
| 89 | + |
| 90 | + def acquire(self, *, timeout=None): |
| 91 | + return ConAcquireContext(self._conn, self) |
| 92 | + |
| 93 | + async def start(self): |
| 94 | + if self.started: |
| 95 | + return |
| 96 | + |
| 97 | + def log_postgresql(con, message): |
| 98 | + print(message) |
| 99 | + |
| 100 | + if self.add_logger_postgres: |
| 101 | + self._conn.add_log_listener(log_postgresql) |
| 102 | + self.tx = self._conn.transaction() |
| 103 | + await self.tx.start() |
| 104 | + await self.initialize(self._conn) |
| 105 | + self.started = True |
| 106 | + |
| 107 | + async def release(self): |
| 108 | + if self.tx: |
| 109 | + await self.tx.rollback() |
| 110 | + |
| 111 | + def __getattr__(self, key): |
| 112 | + return getattr(self._conn, key) |
| 113 | + |
| 114 | + |
| 115 | +async def create_pool_test( |
| 116 | + dsn: str, |
| 117 | + *, |
| 118 | + initialize: typing.Callable = None, |
| 119 | + add_logger_postgres: bool = False, |
| 120 | +): |
| 121 | + """This part is only used for testing, |
| 122 | + we create a fake "pool" that just starts a connecion, |
| 123 | + that does a transaction inside it""" |
| 124 | + conn = await asyncpg.connect(dsn=dsn) |
| 125 | + pool = SingleConnectionTestingPool( |
| 126 | + conn, initialize=initialize, add_logger_postgres=add_logger_postgres |
| 127 | + ) |
| 128 | + return pool |
| 129 | + |
| 130 | + |
| 131 | +class ConAcquireContext: |
| 132 | + def __init__(self, conn, manager): |
| 133 | + self._conn = conn |
| 134 | + self.manager = manager |
| 135 | + |
| 136 | + async def __aenter__(self): |
| 137 | + if not self.manager.tx: |
| 138 | + await self.manager.start() |
| 139 | + self.tr = self._conn.transaction() |
| 140 | + await self.tr.start() |
| 141 | + return self._conn |
| 142 | + |
| 143 | + async def __aexit__(self, exc_type, exc, tb): |
| 144 | + if exc_type: |
| 145 | + await self.tr.rollback() |
| 146 | + else: |
| 147 | + await self.tr.commit() |
0 commit comments