2021-03-18 16:00:01 +00:00
|
|
|
import asyncpg
|
2021-03-19 15:26:19 +00:00
|
|
|
import logging
|
|
|
|
from typing import Optional
|
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:
|
|
|
|
connection: Optional[asyncpg.Pool] = None
|
2021-03-18 16:00:01 +00:00
|
|
|
|
2021-03-20 12:42:54 +00:00
|
|
|
async def setup_connection(self):
|
|
|
|
# Establish a connection to an existing database named "test"
|
|
|
|
# as a "postgres" user.
|
|
|
|
logger.debug("Setting up the Database connection...")
|
|
|
|
self.connection = await asyncpg.create_pool(user=settings["pg_user"], host=settings.get("pg_host", "localhost"),
|
2021-03-20 13:44:29 +00:00
|
|
|
database=settings.get("pg_db", "rcgcdb"), password=settings.get("pg_pass"),
|
2021-10-26 23:16:04 +00:00
|
|
|
port=settings.get("pg_port", 5432), min_size=10, max_size=40)
|
2021-03-20 12:42:54 +00:00
|
|
|
logger.debug("Database connection established! Connection: {}".format(self.connection))
|
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...")
|
2021-03-20 12:42:54 +00:00
|
|
|
await self.connection.close()
|
|
|
|
|
|
|
|
def pool(self) -> asyncpg.Pool:
|
|
|
|
return self.connection
|
|
|
|
|
|
|
|
# Tried to make it a decorator but tbh won't probably work
|
|
|
|
# async def in_transaction(self, func):
|
|
|
|
# async def single_transaction():
|
|
|
|
# async with self.connection.acquire() as connection:
|
|
|
|
# async with connection.transaction():
|
|
|
|
# await func()
|
|
|
|
# return single_transaction
|
|
|
|
|
|
|
|
# async def query(self, string, *arg):
|
|
|
|
# async with self.connection.acquire() as connection:
|
|
|
|
# async with connection.transaction():
|
|
|
|
# return connection.cursor(string, *arg)
|
|
|
|
|
|
|
|
|
|
|
|
db = db_connection()
|