diff options
Diffstat (limited to 'cogs/utils/database.py')
| -rw-r--r-- | cogs/utils/database.py | 17 |
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 @@ | |||
| 1 | import os | 1 | import os |
| 2 | import sqlite3 | 2 | import sqlite3 |
| 3 | import logging | 3 | import logging |
| 4 | from contextlib import contextmanager | ||
| 4 | 5 | ||
| 5 | logger = logging.getLogger(__name__) | 6 | logger = logging.getLogger(__name__) |
| 6 | 7 | ||
| @@ -10,7 +11,8 @@ _initialized = False | |||
| 10 | 11 | ||
| 11 | 12 | ||
| 12 | def get_connection(): | 13 | def get_connection(): |
| 13 | return sqlite3.connect(get_db_path()) | 14 | conn = sqlite3.connect(get_db_path()) |
| 15 | return _ConnectionContextManager(conn) | ||
| 14 | 16 | ||
| 15 | 17 | ||
| 16 | def get_db_path(): | 18 | def get_db_path(): |
| @@ -22,6 +24,19 @@ def set_db_path(path): | |||
| 22 | DB_PATH = path | 24 | DB_PATH = path |
| 23 | 25 | ||
| 24 | 26 | ||
| 27 | class _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 | |||
| 25 | def init_database(): | 40 | def init_database(): |
| 26 | global _initialized | 41 | global _initialized |
| 27 | if _initialized: | 42 | if _initialized: |
