aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/utils/database.py
diff options
context:
space:
mode:
Diffstat (limited to 'cogs/utils/database.py')
-rw-r--r--cogs/utils/database.py17
1 files changed, 16 insertions, 1 deletions
diff --git a/cogs/utils/database.py b/cogs/utils/database.py
index 67cbc9f..ea7d356 100644
--- a/cogs/utils/database.py
+++ b/cogs/utils/database.py
@@ -1,6 +1,7 @@
1import os 1import os
2import sqlite3 2import sqlite3
3import logging 3import logging
4from contextlib import contextmanager
4 5
5logger = logging.getLogger(__name__) 6logger = logging.getLogger(__name__)
6 7
@@ -10,7 +11,8 @@ _initialized = False
10 11
11 12
12def get_connection(): 13def get_connection():
13 return sqlite3.connect(get_db_path()) 14 conn = sqlite3.connect(get_db_path())
15 return _ConnectionContextManager(conn)
14 16
15 17
16def get_db_path(): 18def get_db_path():
@@ -22,6 +24,19 @@ def set_db_path(path):
22 DB_PATH = path 24 DB_PATH = path
23 25
24 26
27class _ConnectionContextManager:
28 """Context manager for sqlite3 connections that auto-closes."""
29 def __init__(self, conn):
30 self.conn = conn
31
32 def __enter__(self):
33 return self.conn
34
35 def __exit__(self, exc_type, exc_val, exc_tb):
36 self.conn.close()
37 return False
38
39
25def init_database(): 40def init_database():
26 global _initialized 41 global _initialized
27 if _initialized: 42 if _initialized: