2021-05-15 01:56:49 +02:00
#!/usr/bin/python3
from datetime import datetime
from datastore import Datastore
def detect_schema ( conn ) :
with conn . cursor ( ) as cursor :
qry = " SELECT meta->> ' _schema ' AS schema, tstamp, age(current_timestamp, tstamp) age FROM real_time_inputs WHERE meta ? ' _schema ' AND age(current_timestamp, tstamp) < ' 02:00:00 ' ORDER BY tstamp DESC LIMIT 1 "
cursor . execute ( qry )
res = cursor . fetchone ( )
if res and len ( res ) :
return res [ 0 ]
return None
if __name__ == ' __main__ ' :
import argparse
2022-04-29 14:48:21 +02:00
2021-05-15 01:56:49 +02:00
ap = argparse . ArgumentParser ( )
ap . add_argument ( " -s " , " --schema " , required = False , default = None , help = " survey where to insert the event " )
ap . add_argument ( " -t " , " --tstamp " , required = False , default = None , help = " event timestamp " )
ap . add_argument ( " -l " , " --label " , required = False , default = None , action = " append " , help = " event label " )
ap . add_argument ( ' remarks ' , type = str , nargs = " + " , help = " event message " )
args = vars ( ap . parse_args ( ) )
db = Datastore ( )
db . connect ( )
if args [ " schema " ] :
schema = args [ " schema " ]
else :
schema = detect_schema ( db . conn )
2022-04-29 14:48:21 +02:00
2021-05-15 01:56:49 +02:00
if args [ " tstamp " ] :
tstamp = args [ " tstamp " ]
else :
tstamp = datetime . utcnow ( ) . isoformat ( )
2022-04-29 14:48:21 +02:00
2021-05-15 01:56:49 +02:00
message = " " . join ( args [ " remarks " ] )
2022-04-29 14:48:21 +02:00
2022-05-12 22:15:09 +02:00
print ( " new event: " , schema , tstamp , message , args [ " label " ] )
2022-04-29 14:48:21 +02:00
2021-05-15 01:56:49 +02:00
if schema and tstamp and message :
db . set_survey ( schema )
with db . conn . cursor ( ) as cursor :
2022-05-12 22:15:09 +02:00
qry = " INSERT INTO event_log (tstamp, remarks, labels) VALUES ( %s , replace_placeholders( %s , %s , NULL, NULL), %s ); "
cursor . execute ( qry , ( tstamp , message , tstamp , args [ " label " ] ) )
2021-05-15 01:56:49 +02:00
db . maybe_commit ( )