""" sqlite event store """
-from sqlite3 import connect
+from sqlite3 import connect, OperationalError
-__all__ = "initdb", "stow"
+__all__ = "fetch", "initdb", "stow"
DB = None
tstamp real not null,
imei text,
peeraddr text not null,
+ is_incoming int not null default TRUE,
proto int not null,
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(**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