diff --git a/soitool/database.py b/soitool/database.py new file mode 100644 index 0000000000000000000000000000000000000000..d5bbe29ed9ac62059d47eb9fc07e5dbffcce5457 --- /dev/null +++ b/soitool/database.py @@ -0,0 +1,39 @@ +"""Database.""" +import os +import sqlite3 + +DBNAME = 'Database' +CURDIR = os.path.dirname(__file__) +DBPATH = os.path.join(CURDIR, DBNAME) + +# DDL-statements for creating tables +CODEBOOK = 'CREATE TABLE CodeBook(Word VARCHAR PRIMARY KEY, Category VARCHAR, Type int DEFAULT 0)' +CATEGORYWORDS = 'CREATE TABLE CategoryWords(Word VARCHAR PRIMARY KEY, Category VARCHAR)' +BYHEART = 'CREATE TABLE ByHeart(Word VARCHAR PRIMARY KEY)' + + +class Database(): + """Holds connection to database.""" + + def __init__(self): + """Connect to existing db if found, creates new db if not.""" + db_exists = os.path.exists(DBPATH) + + if db_exists: + print('connecting to existing DB.') + self.conn = sqlite3.connect(DBPATH) + print('DB-connection established.') + else: + print('Creating new DB.') + self.conn = sqlite3.connect(DBPATH) + self.create_tables() + print('DB created.') + + def create_tables(self): + """Create tables Codebook, CategoryWords and ByHeart.""" + stmts = [CODEBOOK, CATEGORYWORDS, BYHEART] + + for stmt in stmts: + self.conn.execute(stmt) + + self.conn.commit()