-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlhelper.py
98 lines (83 loc) · 2.54 KB
/
sqlhelper.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
87
88
89
90
91
92
93
94
95
96
97
98
import psycopg2
from datetime import datetime, timedelta
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import logging
logger = logging.getLogger("parking_db")
def get_db_connection():
return psycopg2.connect(
dbname="test_db",
user="root",
password="root",
host="db", # This is the service name in docker-compose
port="5432",
)
def insert_garage_data(dbfile: str, garage, fullness, timestamp):
conn = get_db_connection()
cur = conn.cursor()
try:
query = """
INSERT INTO parking_data (garage_name, garage_fullness, timestamp)
VALUES (%s, %s, %s)
"""
cur.execute(query, (garage, fullness, timestamp))
conn.commit()
logger.info(f"Data inserted into {garage} at {timestamp}")
# Verify the insertion
cur.execute(
"""
SELECT * FROM parking_data
WHERE garage_name = %s
ORDER BY timestamp DESC
LIMIT 1
""",
(garage,),
)
logger.debug(f"Inserted data: {cur.fetchone()}")
except Exception as e:
logger.error(f"Error inserting data: {e}")
return False
finally:
cur.close()
conn.close()
def get_garage_data(dbfile: str, garage, time=None):
conn = get_db_connection()
cur = conn.cursor()
try:
if time:
query = """
SELECT * FROM parking_data
WHERE garage_name = %s AND timestamp >= %s
ORDER BY timestamp DESC
"""
cur.execute(query, (garage, time))
else:
query = """
SELECT * FROM parking_data
WHERE garage_name = %s
ORDER BY timestamp DESC
"""
cur.execute(query, (garage,))
return cur.fetchall()
except Exception as e:
logger.error(f"Error fetching data: {e}")
return []
finally:
cur.close()
conn.close()
def delete_garage_data(dbfile: str, garage):
conn = get_db_connection()
cur = conn.cursor()
try:
time_threshold = datetime.now() - timedelta(weeks=2)
query = """
DELETE FROM parking_data
WHERE garage_name = %s AND timestamp < %s
"""
cur.execute(query, (garage, time_threshold))
conn.commit()
logger.info(f"Old data deleted for {garage}")
except Exception as e:
logger.error(f"Error deleting data: {e}")
finally:
cur.close()
conn.close()