X-Git-Url: http://average.org/gitweb/?a=blobdiff_plain;f=loctrkd%2Fevstore.py;h=8cf320621d74845608650c91aed5e8579af15fdc;hb=HEAD;hp=85e8c9d25767de36fbf4e30444c9caa6f7bd6d5c;hpb=ca67cd29fc86054f08bcbf4995d484bab77a4e60;p=loctrkd.git diff --git a/loctrkd/evstore.py b/loctrkd/evstore.py index 85e8c9d..8cf3206 100644 --- a/loctrkd/evstore.py +++ b/loctrkd/evstore.py @@ -3,7 +3,7 @@ from datetime import datetime from json import dumps, loads from sqlite3 import connect, OperationalError, Row -from typing import Any, Dict, List, Tuple +from typing import Any, Dict, List, Optional, Tuple __all__ = "fetch", "initdb", "stow", "stowloc" @@ -25,6 +25,11 @@ SCHEMA = ( latitude real, longitude real, remainder text +)""", + """create table if not exists pmodmap ( + imei text not null unique, + pmod text not null, + tstamp real not null default (strftime('%s')) )""", ) @@ -33,8 +38,25 @@ def initdb(dbname: str) -> None: global DB DB = connect(dbname) DB.row_factory = Row + need_populate_pmodmap = False + try: + DB.execute("select count(pmod) from pmodmap") + try: + DB.execute("select count(tstamp) from pmodmap") + except OperationalError: + need_populate_pmodmap = True + DB.execute("alter table pmodmap rename to old_pmodmap") + except OperationalError: + pass # DB was empty for stmt in SCHEMA: DB.execute(stmt) + if need_populate_pmodmap: + DB.execute( + """insert into pmodmap(imei, pmod) + select imei, pmod from old_pmodmap""" + ) + DB.execute("drop table old_pmodmap") + DB.commit() def stow(**kwargs: Any) -> None: @@ -86,6 +108,17 @@ def stowloc(**kwargs: Dict[str, Any]) -> None: DB.commit() +def stowpmod(imei: str, pmod: str) -> None: + assert DB is not None + DB.execute( + """insert or replace into pmodmap + (imei, pmod) values (:imei, :pmod) + """, + {"imei": imei, "pmod": pmod}, + ) + DB.commit() + + def fetch(imei: str, backlog: int) -> List[Dict[str, Any]]: assert DB is not None cur = DB.cursor() @@ -103,3 +136,19 @@ def fetch(imei: str, backlog: int) -> List[Dict[str, Any]]: result.append(dic) cur.close() return list(reversed(result)) + + +def fetchpmod(imei: str) -> Optional[Any]: + assert DB is not None + ret = None + cur = DB.cursor() + cur.execute( + """select pmod from pmodmap where imei = ? + and tstamp > strftime('%s') - 3600.0""", + (imei,), + ) + result = cur.fetchone() + if result: + ret = result[0] + cur.close() + return ret