1+ import datetime
2+ from typing import Any , Optional
3+
4+ from . import abc
5+
6+ try :
7+ import sqlite3 as sqlite
8+ except :
9+ try :
10+ import pysqlite3 as sqlite # type: ignore
11+ except :
12+ print ("Error: sqlite3 or pysqlite3 not found" )
13+ exit (1 )
14+
15+ class SqliteDB (abc .DataBase ):
16+ def __init__ (
17+ self ,
18+ database_name : str
19+ ):
20+ super ().__init__ (database_name )
21+
22+ self .clusters = sqlite .connect (
23+ abc .ROOT / f'{ self .database_name } _clusters.db'
24+ )
25+
26+ self .clusters .execute ('create table if not exists logs (timestamp text, cluster_id text, type text, event text, data text)' )
27+ # hits, bytes unsigned big integer
28+ self .clusters .execute ('create table if not exists counters (hour text, cluster_id text, hits unsigned big integer, bytes unsigned big integer, primary key (hour, cluster_id))' )
29+ self .clusters .commit ()
30+
31+ async def insert_cluster_info (self , cluster_id : str , type : str , event : str , data : Optional [Any ] = None ):
32+ self .clusters .execute (
33+ 'insert into logs values (?, ?, ?, ?, ?)' ,
34+ (datetime .datetime .now ().isoformat (), cluster_id , type , event , data )
35+ )
36+ self .clusters .commit ()
37+
38+ async def upsert_cluster_counter (self , cluster_id : str , hits : int , bytes : int ):
39+ hour = self .get_hour ()
40+ self .clusters .execute (
41+ 'insert into counters values (?, ?, ?, ?) on conflict (hour, cluster_id) do update set hits = hits + ?, bytes = bytes + ?' ,
42+ (hour , cluster_id , hits , bytes , hits , bytes )
43+ )
44+ self .clusters .commit ()
45+
46+ async def get_cluster_counter (self , cluster_id : str , before_hour : int = 0 ) -> list [abc .ClusterCounterInfo ]:
47+ return [
48+ abc .ClusterCounterInfo (
49+ time = datetime .datetime .fromtimestamp (row [0 ] * 3600 ),
50+ hits = row [1 ],
51+ bytes = row [2 ]
52+ ) for row in self .clusters .execute (
53+ 'select hour, hits, bytes from counters where cluster_id = ? and hour >= ? and hour <= ?' ,
54+ (cluster_id , before_hour , self .get_hour ())
55+ )
56+ ]
57+
58+ def __del__ (self ):
59+ self .clusters .close ()
0 commit comments