]> 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 b1950210555adb532e0cf645941857ca95bc3131..ec463c7c988990e3360cc67d741f87024bedb290 100644 (file)
@@ -1,39 +1,62 @@
-from sqlite3 import connect
+""" sqlite event store """
 
-__all__ = ("initdb", "stow")
+from sqlite3 import connect, OperationalError
+
+__all__ = "fetch", "initdb", "stow"
 
 DB = None
 
 SCHEMA = """create table if not exists events (
-    timestamp real not null,
+    tstamp real not null,
     imei text,
-    clntaddr text not null,
-    length int,
+    peeraddr text not null,
+    is_incoming int not null default TRUE,
     proto int not null,
-    payload blob
+    packet blob
 )"""
 
 
 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(clntaddr, timestamp, imei, length, proto, payload):
+def stow(**kwargs):
     assert DB is not None
-    parms = dict(
-        zip(
-            ("clntaddr", "timestamp", "imei", "length", "proto", "payload"),
-            (str(clntaddr), timestamp, imei, length, proto, payload),
+    parms = {
+        k: kwargs[k] if k in kwargs else v
+        for k, v in (
+            ("peeraddr", None),
+            ("when", 0.0),
+            ("imei", None),
+            ("proto", -1),
+            ("packet", b""),
         )
-    )
+    }
+    assert len(kwargs) <= len(parms)
     DB.execute(
         """insert or ignore into events
-                (timestamp, imei, clntaddr, length, proto, payload)
+                (tstamp, imei, peeraddr, proto, packet)
                 values
-                (:timestamp, :imei, :clntaddr, :length, :proto, :payload)
+                (:when, :imei, :peeraddr, :proto, :packet)
         """,
         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