Skip to content

Commit

Permalink
Add create database pool into its own function so that it can more ea…
Browse files Browse the repository at this point in the history
…sily be used in other projects
  • Loading branch information
4Kaylum committed Mar 22, 2024
1 parent e910d73 commit c16bef7
Showing 1 changed file with 31 additions and 16 deletions.
47 changes: 31 additions & 16 deletions novus/ext/database/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,29 +58,22 @@ def acquire(cls, *args: Any, **kwargs: Any) -> PoolAcquireContext:
)
return cls.pool.acquire(*args, **kwargs) # pyright: ignore

async def on_load(self) -> None:
async def create_pool(
self,
dsn: str,
max_connections: int = 10,
min_connections: int = 10) -> None:
"""
Open a database connection, store it in the class, continue.
Does the actual process of opening and storing a database pool.
"""

# Make sure we have a DSN
Database._log = self.log
if not hasattr(self.bot.config, "database_dsn"):
self.log.error("Missing database DSN from config")
return
if not self.bot.config.database_dsn:
self.log.error("Missing database DSN from config")
return
if self.bot.config.database_max_connections is None:
self.bot.config.database_max_connections = 10

# Open a pool
try:
created = (
await asyncpg.create_pool(
self.bot.config.database_dsn,
max_size=self.bot.config.database_max_connections,
min_size=min(self.bot.config.database_max_connections, 10),
dsn,
max_size=max_connections,
min_size=min(max_connections, min_connections),
)
)
if created is None:
Expand All @@ -97,6 +90,28 @@ async def on_load(self) -> None:
else:
await self.create_tables()

async def on_load(self) -> None:
"""
Open a database connection, store it in the class, continue.
"""

# Make sure we have a DSN
if not hasattr(self.bot.config, "database_dsn"):
self.log.error("Missing database DSN from config")
return
if not self.bot.config.database_dsn:
self.log.error("Missing database DSN from config")
return
if self.bot.config.database_max_connections is None:
self.bot.config.database_max_connections = 10

# Create pool
await self.create_pool(
self.bot.config.database_dsn,
self.bot.config.database_max_connections,
min(self.bot.config.database_max_connections, 10)
)

async def create_tables(self) -> None:
"""
Create any tables that have been instantiated with the database class.
Expand Down

0 comments on commit c16bef7

Please sign in to comment.