+ self.server_version = 0
+
+ self._engine_lock = asyncio.Lock()
+ self._engine: Optional[sa_asyncio.AsyncEngine] = None
+
+
+ async def setup_database(self) -> None:
+ """ Set up the engine and connection parameters.
+
+ This function will be implicitly called when the database is
+ accessed for the first time. You may also call it explicitly to
+ avoid that the first call is delayed by the setup.
+ """
+ async with self._engine_lock:
+ if self._engine:
+ return
+
+ dsn = self.config.get_database_params()
+
+ dburl = sa.engine.URL.create(
+ 'postgresql+asyncpg',
+ database=dsn.get('dbname'),
+ username=dsn.get('user'), password=dsn.get('password'),
+ host=dsn.get('host'), port=int(dsn['port']) if 'port' in dsn else None,
+ query={k: v for k, v in dsn.items()
+ if k not in ('user', 'password', 'dbname', 'host', 'port')})
+ engine = sa_asyncio.create_async_engine(
+ dburl, future=True,
+ connect_args={'server_settings': {
+ 'DateStyle': 'sql,european',
+ 'max_parallel_workers_per_gather': '0'
+ }})
+
+ try:
+ async with engine.begin() as conn:
+ result = await conn.scalar(sa.text('SHOW server_version_num'))
+ self.server_version = int(result)
+ except asyncpg.PostgresError:
+ self.server_version = 0
+
+ if self.server_version >= 110000:
+ @sa.event.listens_for(engine.sync_engine, "connect") # type: ignore[misc]
+ def _on_connect(dbapi_con: Any, _: Any) -> None:
+ cursor = dbapi_con.cursor()
+ cursor.execute("SET jit_above_cost TO '-1'")
+ # Make sure that all connections get the new settings
+ await self.close()
+
+ self._engine = engine