Refactor internal schema function api

This commit is contained in:
Marty Oehme 2021-12-15 17:51:14 +01:00
parent 704f2520ae
commit 92678ea6bf
Signed by: Marty
GPG key ID: B7538B8F50A1C800

View file

@ -1,7 +1,8 @@
import sqlite3 import sqlite3
import sys
def create_database(db_file: str) -> sqlite3.Connection: def create_database(db_file: str = ":memory:") -> sqlite3.Connection:
"""create a database connection to the SQLite database """create a database connection to the SQLite database
specified by db_file specified by db_file
:param db_file: database file :param db_file: database file
@ -13,10 +14,10 @@ def create_database(db_file: str) -> sqlite3.Connection:
return conn return conn
except sqlite3.Error as e: except sqlite3.Error as e:
print(e) print(e)
sys.exit(1)
def create_tables(db): def create_tables(c: sqlite3.Cursor):
c = db.cursor()
c.execute( c.execute(
""" CREATE TABLE IF NOT EXISTS Habits ( """ CREATE TABLE IF NOT EXISTS Habits (
id integer PRIMARY KEY AUTOINCREMENT, id integer PRIMARY KEY AUTOINCREMENT,
@ -49,8 +50,7 @@ def create_tables(db):
) )
def create_constraints(db): def create_constraints(c: sqlite3.Cursor):
c = db.cursor()
c.execute( c.execute(
""" CREATE UNIQUE INDEX IF NOT EXISTS idx_repetitions_habit_timestamp """ CREATE UNIQUE INDEX IF NOT EXISTS idx_repetitions_habit_timestamp
on Repetitions( habit, timestamp); on Repetitions( habit, timestamp);
@ -58,15 +58,15 @@ def create_constraints(db):
) )
def create_pragma(db): def create_pragma(c: sqlite3.Cursor):
c = db.cursor()
c.execute(""" PRAGMA user_version = 24; """) c.execute(""" PRAGMA user_version = 24; """)
c.execute(""" PRAGMA schema_version = 30; """) c.execute(""" PRAGMA schema_version = 30; """)
def migrate(name): def migrate(fname):
db = create_database(name) db = create_database(fname)
create_tables(db) c = db.cursor()
create_constraints(db) create_tables(c)
create_pragma(db) create_constraints(c)
create_pragma(c)
return db return db