2021-03-18 16:00:01 +00:00
|
|
|
import asyncpg
|
2021-03-19 15:26:19 +00:00
|
|
|
import logging
|
2022-06-22 17:17:20 +00:00
|
|
|
from typing import Optional, Callable
|
2020-07-25 13:27:15 +00:00
|
|
|
from src.config import settings
|
2020-07-09 22:24:23 +00:00
|
|
|
|
2021-03-19 15:26:19 +00:00
|
|
|
logger = logging.getLogger("rcgcdb.database")
|
2021-03-20 12:42:54 +00:00
|
|
|
# connection: Optional[asyncpg.Connection] = None
|
2021-03-18 16:00:01 +00:00
|
|
|
|
|
|
|
|
2021-03-20 12:42:54 +00:00
|
|
|
class db_connection:
|
2022-06-22 17:17:20 +00:00
|
|
|
listener_connection: Optional[asyncpg.Connection] = None
|
|
|
|
connection_pool: Optional[asyncpg.Pool] = None
|
|
|
|
|
|
|
|
async def create_pubsub_interface(self, callback: Callable):
|
|
|
|
await self.listener_connection.add_listener("webhookupdates", callback)
|
2021-03-18 16:00:01 +00:00
|
|
|
|
2021-03-20 12:42:54 +00:00
|
|
|
async def setup_connection(self):
|
2022-06-22 17:17:20 +00:00
|
|
|
logger.debug("Setting up the Database connections...")
|
|
|
|
# First, setup a separate connection for pub/sub listener
|
|
|
|
# It's mainly because I'm afraid that connection pool will be aggressive about inactive connections
|
|
|
|
self.listener_connection = await asyncpg.connect(user=settings["pg_user"], host=settings.get("pg_host", "localhost"),
|
|
|
|
database=settings.get("pg_db", "rcgcdb"), password=settings.get("pg_pass"),
|
|
|
|
port=settings.get("pg_port", 5432))
|
|
|
|
self.connection_pool = await asyncpg.create_pool(user=settings["pg_user"], host=settings.get("pg_host", "localhost"),
|
|
|
|
database=settings.get("pg_db", "rcgcdb"), password=settings.get("pg_pass"),
|
|
|
|
port=settings.get("pg_port", 5432))
|
|
|
|
logger.debug("Database connection established! Connection: {}".format(self.connection_pool))
|
2021-03-18 16:00:01 +00:00
|
|
|
|
2021-03-20 12:42:54 +00:00
|
|
|
async def shutdown_connection(self):
|
2021-03-20 12:55:56 +00:00
|
|
|
logger.debug("Shutting down database connection...")
|
2022-06-22 17:17:20 +00:00
|
|
|
await self.listener_connection.close()
|
|
|
|
await self.connection_pool.close()
|
2021-03-20 12:42:54 +00:00
|
|
|
|
|
|
|
def pool(self) -> asyncpg.Pool:
|
2022-06-22 17:17:20 +00:00
|
|
|
return self.connection_pool
|
2021-03-20 12:42:54 +00:00
|
|
|
|
2022-11-04 14:59:26 +00:00
|
|
|
|
|
|
|
db = db_connection()
|