]> www.average.org Git - loctrkd.git/blobdiff - gps303/evstore.py
Update evstore schema to support in and out msgs
[loctrkd.git] / gps303 / evstore.py
index 70a3ac6618bec9bd67f53ff7fa9a30a6d92484c4..ec463c7c988990e3360cc67d741f87024bedb290 100644 (file)
@@ -1,8 +1,8 @@
 """ sqlite event store """
 
-from sqlite3 import connect
+from sqlite3 import connect, OperationalError
 
-__all__ = "initdb", "stow"
+__all__ = "fetch", "initdb", "stow"
 
 DB = None
 
@@ -10,6 +10,7 @@ SCHEMA = """create table if not exists events (
     tstamp real not null,
     imei text,
     peeraddr text not null,
+    is_incoming int not null default TRUE,
     proto int not null,
     packet blob
 )"""
@@ -18,7 +19,11 @@ SCHEMA = """create table if not exists events (
 def initdb(dbname):
     global DB
     DB = connect(dbname)
-    DB.execute(SCHEMA)
+    try:
+        DB.execute("""alter table events add column
+                is_incoming int not null default TRUE""")
+    except OperationalError:
+        DB.execute(SCHEMA)
 
 
 def stow(**kwargs):
@@ -43,3 +48,15 @@ def stow(**kwargs):
         parms,
     )
     DB.commit()
+
+def fetch(imei, protos, backlog):
+    assert DB is not None
+    protosel = ", ".join(["?" for _ in range(len(protos))])
+    cur = DB.cursor()
+    cur.execute(f"""select packet from events
+                    where proto in ({protosel}) and imei = ?
+                    order by tstamp desc limit ?""",
+                protos + (imei, backlog))
+    result = [row[0] for row in cur]
+    cur.close()
+    return result