streamrecord/libs/database.py

49 lines
2.0 KiB
Python
Raw Normal View History

2014-08-26 11:46:47 -07:00
#!/usr/bin/env python3
import sqlite3
2014-08-30 14:55:59 -07:00
import os.path
2020-02-06 18:47:34 -08:00
from contextlib import closing
2014-08-26 11:46:47 -07:00
class database:
2014-08-26 11:46:47 -07:00
def __init__(self):
self.createDatabase()
self.db = self.openDB()
2020-02-06 18:47:34 -08:00
2014-08-26 11:54:44 -07:00
def createDatabase(self):
queries = [
"CREATE TABLE 'streams' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'user' INTEGER, 'name' TEXT, 'url' TEXT, 'directory' TEXT, 'status' INTEGER, 'message' TEXT);",
2014-08-30 14:55:59 -07:00
"CREATE TABLE 'times' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'streamid' INTEGER, 'su' BOOLEAN, 'm' BOOLEAN, 't' BOOLEAN, 'w' BOOLEAN, 'r' BOOLEAN, 'f' BOOLEAN, 'sa' BOOLEAN, 'starthour' INTEGER, 'startmin' INTEGER, 'endhour' INTEGER, 'endmin' INTEGER)",
"""INSERT INTO "streams" ("id","user","name","url","directory","status","message") VALUES (NULL,NULL,'WCMF Breakroom','http://1681.live.streamtheworld.com/WCMFFMAAC','wcmf-breakroom','0','')""",
"""INSERT INTO "times" ("id","streamid","su","m","t","w","r","f","sa","starthour","startmin","endhour","endmin") VALUES (NULL,'1','0','1','1','1','1','1','0','2','0','7','15')"""
2014-08-26 11:54:44 -07:00
]
2016-06-02 19:22:35 -07:00
if not os.path.exists("db.sqlite") or os.path.getsize("db.sqlite")==0: # TODO: query and see if the tables exist instead
2014-08-30 14:55:59 -07:00
db = sqlite3.connect("db.sqlite", check_same_thread=False, cached_statements=0, isolation_level=None)
cursor = db.cursor()
for query in queries:
print("Executing: %s" % query)
2014-08-30 14:55:59 -07:00
cursor.execute(query)
db.close()
2020-02-06 18:47:34 -08:00
2014-08-26 11:46:47 -07:00
def openDB(self):
db = sqlite3.connect("db.sqlite", check_same_thread=False, cached_statements=0, isolation_level=None)
db.row_factory = self.dict_factory
return db
2020-02-06 18:47:34 -08:00
2014-08-26 11:46:47 -07:00
def dict_factory(self, cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
2020-02-06 18:47:34 -08:00
2014-08-26 11:46:47 -07:00
def execute(self, sql, params=None):
db = self.db
2020-02-06 18:47:34 -08:00
with closing(db.cursor()) as cursor:
if params:
cursor.execute(sql, params)
else:
cursor.execute(sql)
data = cursor.fetchall()
if sql.lower().startswith("insert "):
return cursor.lastrowid
cursor.close()
return data