fulvia/db.py
2019-10-08 12:39:13 -04:00

38 lines
817 B
Python
Executable File

#!/usr/bin/env python3
"""
The bot's database connection class.
"""
import os
import sqlite3
import threading
import config
class FulviaDB:
"""
Defines a basic interface and some convenience functionsfor the bot's
database.
"""
def __init__(self):
path = config.db_filename
self.filename = path
self.db_lock = threading.Lock()
def connect(self):
"""Return a raw database connection object."""
return sqlite3.connect(self.filename, timeout=10)
def execute(self, *args, **kwargs):
"""
Execute an arbitrary SQL query against the database.
Returns a cursor object, on which things like `.fetchall()` can be
called per PEP 249.
"""
with self.connect() as conn:
self.db_lock.acquire()
cur = conn.cursor()
res = cur.execute(*args, **kwargs)
self.db_lock.release()
return res