fulvia/db.py

40 lines
863 B
Python
Raw Normal View History

2018-03-16 03:13:43 -04:00
#!/usr/bin/env python3
"""
The bot's database connection class.
"""
import os
import sqlite3
2018-03-25 14:26:48 -04:00
import threading
2018-03-16 03:13:43 -04:00
2019-10-08 12:39:13 -04:00
import config
class FulviaDB:
2018-03-16 03:13:43 -04:00
"""
Defines a basic interface and some convenience functionsfor the bot's
database.
"""
2019-10-08 12:39:13 -04:00
def __init__(self):
path = config.db_filename
2018-03-16 03:13:43 -04:00
self.filename = path
2018-03-25 14:26:48 -04:00
self.db_lock = threading.Lock()
2018-03-16 03:13:43 -04:00
def connect(self):
"""Return a raw database connection object."""
2020-01-16 15:23:56 -05:00
return sqlite3.connect(self.filename,
timeout=10,
detect_types=sqlite3.PARSE_DECLTYPES)
2018-03-16 03:13:43 -04:00
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:
2018-03-25 14:26:48 -04:00
self.db_lock.acquire()
2018-03-16 03:13:43 -04:00
cur = conn.cursor()
2018-03-25 14:26:48 -04:00
res = cur.execute(*args, **kwargs)
self.db_lock.release()
return res