-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
86 lines (72 loc) · 1.79 KB
/
db.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import sqlite3
schema_sql = """
CREATE TABLE IF NOT EXISTS rides (
id VARCHAR(32), -- PRIMARY KEY
driver_id VARCHAR(32),
kind VARCHAR(16), -- regular, shared
start_time TIMESTAMP,
end_time TIMESTAMP,
distance REAL
);
"""
start_sql = """
INSERT INTO rides
(id, driver_id, kind, start_time)
VALUES
(:id, :driver_id, :kind, :start_time)
;
"""
end_sql = """
UPDATE rides
SET
end_time = :end_time,
distance = :distance
WHERE
id = :id AND
distance IS NULL
;
"""
get_sql = """
SELECT
id, driver_id, kind, start_time, end_time, distance
FROM
rides
WHERE
id = :id
"""
class DBError(Exception):
pass
class DB:
def __init__(self, db_path):
self.conn = sqlite3.connect(
db_path,
detect_types=sqlite3.PARSE_DECLTYPES,
check_same_thread=False,
)
self.conn.row_factory = sqlite3.Row
self.conn.execute(schema_sql)
self.conn.commit()
def close(self):
if not self.conn:
return
self.conn.close()
self.conn = None
def start_ride(self, id, driver_id, kind, start_time):
params = {
'id': id,
'driver_id': driver_id,
'kind': kind,
'start_time': start_time,
}
with self.conn as cur:
cur.execute(start_sql, params)
def end_ride(self, id, distance, end_time):
params = {'id': id, 'end_time': end_time, 'distance': distance}
with self.conn:
cur = self.conn.execute(end_sql, params)
num_changes = cur.rowcount
if num_changes == 0:
raise DBError(f'ride {id!r} does not exist or already ended')
def get_ride(self, id):
row = self.conn.execute(get_sql, {'id': id}).fetchone()
return dict(row)