1 """ sqlite event store """
3 from sqlite3 import connect, OperationalError
5 __all__ = "fetch", "initdb", "stow"
9 SCHEMA = """create table if not exists events (
12 peeraddr text not null,
13 is_incoming int not null default TRUE,
24 """alter table events add column
25 is_incoming int not null default TRUE"""
27 except OperationalError:
34 k: kwargs[k] if k in kwargs else v
36 ("is_incoming", True),
44 assert len(kwargs) <= len(parms)
46 """insert or ignore into events
47 (tstamp, imei, peeraddr, proto, packet, is_incoming)
49 (:when, :imei, :peeraddr, :proto, :packet, :is_incoming)
56 def fetch(imei, matchlist, backlog):
57 # matchlist is a list of tuples (is_incoming, proto)
58 # returns a list of tuples (is_incoming, timestamp, packet)
60 selector = " or ".join(
61 (f"(is_incoming = ? and proto = ?)" for _ in range(len(matchlist)))
65 f"""select is_incoming, tstamp, packet from events
66 where ({selector}) and imei = ?
67 order by tstamp desc limit ?""",
68 tuple(item for sublist in matchlist for item in sublist)
73 return list(reversed(result))