-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsqlite_helpers.py
More file actions
55 lines (48 loc) · 1.53 KB
/
sqlite_helpers.py
File metadata and controls
55 lines (48 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from datetime import datetime
import logging
import sqlite3
import datetime
logger = logging.getLogger(__name__)
def maybe_create_table(sqlite_file: str) -> bool:
db = sqlite3.connect(sqlite_file)
cursor = db.cursor()
try:
create_table_query = """
CREATE TABLE IF NOT EXISTS logs (
date DATETIME DEFAULT CURRENT_TIMESTAMP,
job_id TEXT NOT NULL,
status TEXT CHECK (status IN ('pending', 'completed')) NOT NULL DEFAULT 'pending',
PRIMARY KEY (date, job_id)
)
"""
cursor.execute(create_table_query)
db.commit()
return True
except Exception:
logger.exception("Unable to create printer table")
return False
def insert_print_job(sqlite_file: str, job_id: str):
try:
with sqlite3.connect(sqlite_file, timeout=10.0) as db:
cursor = db.cursor()
timestamp = datetime.datetime.now()
db = sqlite3.connect(sqlite_file)
sql = "INSERT INTO logs (job_id) VALUES (?)"
cursor.execute(sql, (job_id,))
db.commit()
return timestamp
except sqlite3.IntegrityError:
return None
except Exception:
logger.exception("Inserting print job had an error")
return None
def get_logs(sqlite_file):
db = sqlite3.connect(sqlite_file)
cursor = db.cursor()
sql = f"""
SELECT * FROM logs
ORDER BY date
"""
cursor.execute(sql)
result = cursor.fetchall()
return result