matrix-alertbot/my_project_name/storage.py

51 lines
1.3 KiB
Python
Raw Normal View History

2019-09-25 14:31:56 +02:00
import logging
2020-08-10 00:02:07 +02:00
import os.path
import sqlite3
2019-09-25 14:26:29 +02:00
latest_db_version = 0
2019-09-25 14:31:56 +02:00
logger = logging.getLogger(__name__)
2019-09-25 14:26:29 +02:00
2019-09-25 14:26:29 +02:00
class Storage(object):
def __init__(self, db_path):
"""Setup the database
Runs an initial setup or migrations depending on whether a database file has already
been created
Args:
db_path (str): The name of the database file
"""
self.db_path = db_path
# Check if a database has already been connected
if os.path.isfile(self.db_path):
self._run_migrations()
else:
self._initial_setup()
def _initial_setup(self):
"""Initial setup of the database"""
2019-09-25 14:31:56 +02:00
logger.info("Performing initial database setup...")
2019-09-25 14:26:29 +02:00
# Initialize a connection to the database
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()
2019-09-25 14:26:29 +02:00
# Sync token table
2020-08-10 00:02:07 +02:00
self.cursor.execute(
"CREATE TABLE sync_token ("
"dedupe_id INTEGER PRIMARY KEY, "
"token TEXT NOT NULL"
")"
)
2019-09-25 14:26:29 +02:00
2019-09-25 14:31:56 +02:00
logger.info("Database setup complete")
2019-09-25 14:26:29 +02:00
def _run_migrations(self):
"""Execute database migrations"""
# Initialize a connection to the database
2019-10-26 03:51:38 +02:00
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()