-
Notifications
You must be signed in to change notification settings - Fork 1
/
gsup_sql.py
1549 lines (1203 loc) · 53 KB
/
gsup_sql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
gsup_sql.py - GeigerLog commands to handle sqlite3 databases
include in programs with:
include gsup_sql
"""
###############################################################################
# This file is part of GeigerLog.
#
# GeigerLog is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GeigerLog is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GeigerLog. If not, see <http://www.gnu.org/licenses/>.
###############################################################################
# select CPM3rd, CPS3rd, T, datetime(julianday) as dj from data where (dj >= "2023-05-04 18:25:05" and dj <= "2023-05-04 18:25:08")
# Update myTable set MyColumn = NULL where Field = Condition.
# Update data set CPS3rd = NULL where (datetime(julianday) >= "2023-05-04 18:25:12" and datetime(julianday) <= "2023-05-04 18:25:22") #!!!
# The apperance of a "*.logdb-journal" file:
# see: https://www.sqlite.org/tempfiles.html
#
# "The rollback journal is always located in the same directory as the
# database file and has the same name as the database file except with
# the 8 characters "-journal" appended. The rollback journal is usually
# created when a transaction is first started and is usually deleted
# when a transaction commits or rolls back. The rollback journal file
# is essential for implementing the atomic commit and rollback capabilities
# of SQLite. Without a rollback journal, SQLite would be unable to rollback
# an incomplete transaction, and if a crash or power loss occurred in the
# middle of a transaction the entire database would likely go corrupt
# without a rollback journal.
# The rollback journal is usually created and destroyed at the start and end
# of a transaction, respectively. But there are exceptions to this rule."
__author__ = "ullix"
__copyright__ = "Copyright 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024"
__credits__ = [""]
__license__ = "GPL3"
from gsup_utils import *
def DB_getLocaltime():
"""gets the localtime as both Julianday as well as timetag, like:
res: (2458512.928904213, '2019-01-29 10:17:37') """
# sql = "select julianday('0001-01-01 00:00:00', 'localtime')"
# xsel = g.currentConn.execute(sql)
# res = xsel.fetchone()
# rdprint("DB_getLocaltime: sql: {}, res:".format(sql), res, type(res))
# sql = "select julianday('0001-01-01 00:00:00')"
# xsel = g.currentConn.execute(sql)
# res = xsel.fetchone()
# rdprint("DB_getLocaltime: sql: {}, res:".format(sql), res, type(res))
# sql = "select julianday('1970-01-01 01:00:00', 'localtime')"
# xsel = g.currentConn.execute(sql)
# res = xsel.fetchone()
# rdprint("DB_getLocaltime: sql: {}, res:".format(sql), res, type(res))
# sql = "select julianday('1970-01-01 01:00:00')"
# xsel = g.currentConn.execute(sql)
# res = xsel.fetchone()
# rdprint("DB_getLocaltime: sql: {}, res:".format(sql), res, type(res))
sql = "select julianday('NOW', 'localtime'), DateTime('NOW', 'localtime')"
# sql = "select julianday('NOW', 'localtime'), DateTime('NOW', 'localtime'), strftime('%Y-%m-%d %H:%M:%S', 'localtime')" # strftime is NOT localtime
# sql = "select julianday('NOW', 'localtime'), DateTime('NOW', 'localtime'), strftime('%Y-%m-%d %H:%M:%S')" # strftime is NOT localtime; strftime mit localtime modifier geht icht
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()
# rdprint("DB_getLocaltime: sql: {}, res:".format(sql), res, type(res))
return res[0], res[1]
# return res
def DB_JulianToDate(juliandate):
"""convert Julian=2458403.02342593 to datetime=2018-10-11 12:33:44 """
defname = "DB_JulianToDate: "
sql = "select DateTime({})".format(juliandate)
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()
gdprint(defname, "sql: {}, res:".format(sql), res)
# sql = "select julianday('NOW', 'localtime'), DateTime('NOW', 'localtime')"
# sql = "select julianday('NOW', 'localtime'), DateTime('NOW', None)" # --> no such column: None
sql = "select julianday('NOW', 'localtime'), DateTime('NOW')" # --> ergibt UTC time
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()
gdprint(defname, "sql: {}, res:".format(sql), res)
sql = "select julianday('NOW', 'localtime'), DateTime({})".format(g.JULIANUNIXZERO + (time.time() / 86400)) # --> ergibt
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()
gdprint(defname, "sql: {}, res:".format(sql), res)
sql = "select julianday('1970-01-01 01:00:00')"
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()
gdprint(defname, "sql: {}, res:".format(sql), res)
sql = "select julianday('1970-01-01 00:00:00')"
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()
gdprint(defname, "sql: {}, res:".format(sql), res)
tutc = res[0]
sql = "select julianday('1970-01-01 00:00:00', 'localtime')"
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()
gdprint(defname, "sql: {}, res:".format(sql), res)
tlocal = res[0]
gdprint(defname, "Delta l - utc: ", (tlocal - tutc) * 86400)
sql = "select julianday('0001-01-01 00:00:00')"
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()
gdprint(defname, "sql: {}, res:".format(sql), res)
ts = time.time()
local = str(dt.datetime.fromtimestamp(ts, tz=None))[0:19]
utc = str(dt.datetime.fromtimestamp(ts, tz=datetime.timezone.utc))[0:19]
ts_local = dt.datetime.strptime(local, "%Y-%m-%d %H:%M:%S").timestamp()
ts_utc = dt.datetime.strptime(utc , "%Y-%m-%d %H:%M:%S").timestamp()
mdprint(defname, "local: ", local , ts_local )
mdprint(defname, "utxc: ", utc , ts_utc)
mdprint(defname, "delta: ", ts_local - ts_utc )
return res
def DB_DateToJulian(ddate):
"""Convert "2018-10-11 12:33:44" to Julian=2458403.10675926,
or "NOW" to Julian=2458500.15535483 """
defname = "DB_DateToJulian: "
sql = "select julianday('{}')".format(ddate)
xsel = g.currentConn.execute(sql)
res = xsel.fetchone()[0]
dprint(defname, "swl: {}, res:".format(sql), res)
return res
def DB_openDatabase(DB_Connection, DB_FilePath):
"""Open the database"""
defname = "DB_openDatabase: "
dprint(defname + "DBpath: '{}'".format(DB_FilePath))
setIndent(1)
DB_Connection = sqlite3.connect(DB_FilePath, isolation_level="EXCLUSIVE", check_same_thread = False)
# edprint("os.access(DB_FilePath, os.W_OK): ", os.access(DB_FilePath, os.W_OK))
### testing - use storage to memory #################################################################
# DB_Connection.close()
# DB_Connection = sqlite3.connect(":memory:", isolation_level="EXCLUSIVE", check_same_thread = False)
#####################################################################################################
g.currentConn = DB_Connection
DB_createStructure(DB_Connection) # does no harm if structure already exists
# find number of tables in file
res = DB_Connection.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;")
tables = res.fetchall()
ntables = len(tables)
# find number of views in file
res = DB_Connection.execute("SELECT name FROM sqlite_master WHERE type='view' ORDER BY name;")
views = res.fetchall()
nviews = len(views)
# find number of rows in table data
res = DB_Connection.execute("SELECT count(*) FROM data")
rows = res.fetchone()
dnrows = rows[0]
# find number of rows in table comments
res = DB_Connection.execute("SELECT count(*) FROM comments")
rows = res.fetchone()
cnrows = rows[0]
dprint(defname + "Database has {} tables, {} views, with {:n} rows in table data, {:n} rows in table comments".format(ntables, nviews, dnrows, cnrows))
setIndent(0)
return DB_Connection
def DB_closeDatabase(DBtype):
"""Close the database."""
# NOTE: any changes not committed will be lost!
defname = "DB_closeDatabase: "
dprint(defname, "Closing database: '{}'".format(DBtype))
setIndent(1)
if DBtype == "Log": DB_Connection = g.logConn
else: DB_Connection = g.hisConn
if DB_Connection is None:
dprint(defname + "Database was not open")
else:
try:
DB_Connection.close()
dprint(defname + "Closing done")
except Exception as e:
srcinfo = defname + "Exception: connection is: {}".format(DB_Connection)
exceptPrint(e, srcinfo)
setIndent(0)
def DB_deleteDatabase(DBtype, DB_FilePath): # DBtype = "Log" or "His"
"""Try to close database at DB_Connection, then delete database file at DB_FilePath"""
defname = "DB_deleteDatabase: "
dprint(defname + "Deleting {} DB file: '{}'".format(DBtype, DB_FilePath))
setIndent(1)
try: DB_closeDatabase (DBtype) # try to close DB
except: pass
try: os.remove (DB_FilePath) # try to remove DB file
except: pass
setIndent(0)
def DB_commit(DB_Connection):
"""Commit all changes on connection DB_Connection"""
try:
DB_Connection.commit()
# rdprint("DB_commit done")
except Exception as e:
exceptPrint(e, "DB_commit: FAILURE commit")
def DB_createStructure(DB_Connection):
"""Create the database with tables and views"""
defname = "DB_createStructure: "
while g.blockDBwriting: pass
g.blockDBwriting = True
dprint(defname)
setIndent(1)
# execute all sql to create database structure
for sql in sqlCreate:
try:
DB_Connection.execute(sql)
sqls = sql.strip()
vprint(defname + "sql done: ", sqls[:sqls.find("\n")], "...")
except Exception as e:
if not ("already exists" in str(e)):
srcinfo = defname
exceptPrint(e, srcinfo)
dprint(defname + "complete")
DB_commit(DB_Connection)
setIndent(0)
g.blockDBwriting = False
def DB_insertData(DB_Connection, datalist):
"""Insert many rows of data into the table data"""
defname = "DB_insertData: "
sql = sqlInsertData
# gdprint(defname, "SQL:", sql, ", Data: len: ", len(datalist), " ", datalist)
try:
DB_Connection.executemany(sql, datalist)
except Exception as e:
srcinfo = defname + "Exception:" + sql
exceptPrint(e, srcinfo)
DB_commit(DB_Connection)
def DB_insertParse(DB_Connection, datalist):
"""Insert many rows of data into the table parse
ATTENTION: datalist MUST be a list of lists to 'executemany' !!!"""
defname = "DB_insertParse: "
sql = sqlInsertParse
#wprint(defname + "SQL:", sql, ", Data: ", datalist[0:10])
try:
DB_Connection.executemany(sql, datalist)
except Exception as e:
srcinfo = defname + "Exception: " + sql
exceptPrint(e, srcinfo)
DB_commit(DB_Connection)
def DB_insertComments(DB_Connection, datalist):
"""Insert many rows of data into the table comments
ATTENTION: datalist MUST be a list of lists to 'executemany' !!!"""
defname = "DB_insertComments: "
sql = sqlInsertComments # sqlInsertComments = """INSERT INTO comments (ctype, cJulianday, cinfo) VALUES (?, julianday(?), ?)"""
# rdprint(defname, "SQL: ", sql)
# for dl in datalist:
# rdprint(defname, "Datalist: ", dl)
try:
DB_Connection.executemany(sql, datalist)
except Exception as e:
exceptPrint(e, defname + sql)
DB_commit(DB_Connection)
def DB_insertBin(DB_Connection, binblob):
"""Insert a row of data into the table bin - should be the only row!"""
defname = "DB_insertBin: "
sql = sqlInsertBin
#wprint(defname + "SQL:", sql, ", Data: ", binblob[0:10])
try:
DB_Connection.execute(sql, (binblob,))
except Exception as e:
srcinfo = defname + "Exception: " + sql
exceptPrint(e, srcinfo)
DB_commit(DB_Connection)
def DB_insertDevice(DB_Connection, ddatetime, dname):
"""Insert a row of data into the table bin - should be the only row!"""
defname = "DB_insertDevice: "
sql = sqlInsertDevice
#wprint(defname + "SQL:", sql, ", Data: ", ddatetime, dname)
try:
DB_Connection.execute(sql, (ddatetime, dname))
except Exception as e:
srcinfo = defname + "Exception: " + sql
exceptPrint(e, srcinfo)
DB_commit(DB_Connection)
def DB_readData(DB_Connection, sql, limit=0):
"""Read the data from the database data table
if limit=0, the std sql is called, otherwise the lower or upper LIMIT limit"""
res = DB_Connection.execute(sql)
try:
rows = res.fetchall()
except Exception as e:
msg = "Coding Error in Database"
exceptPrint(e, msg)
edprint("sql: ", sql)
return msg
# ### testing
# for r in rows: cdprint("rows:", r)
# ###
if limit > 0:
if len(rows) > limit * 2: rows = rows[0:limit] + rows[-limit:]
ddd = [x[1:2][0] for x in rows]
return ddd
def DB_readComments(DB_Connection):
"""Read the data from the database table comments"""
sql = """
select
cjulianday as julianday,
printf("#%8s, %19s, %s",
ctype ,
datetime(cjulianday),
cinfo
) as commentstr,
ctype
from comments
order by julianday asc, rowid asc
"""
res = DB_Connection.execute(sql)
rows = res.fetchall()
#cdprint("rows:", nrows, "\n", rows)
ddd = [x[1:2][0] for x in rows] # make a list of only the commentstr
return ddd
def DB_readBinblob(DB_Connection):
"""Read the data from the database table bin"""
sql = """
select
bblob
from bin
"""
res = DB_Connection.execute(sql) # res is a sqlite3.Cursor object
blob = res.fetchone()
if blob is None:
return None
else:
return blob[0]
def DB_readParse(DB_Connection):
"""Read the data from the database table parse
return: True if at least 1 parse record, False if no records
"""
sql = """
select
pindex,
pinfo
from parse
"""
res = DB_Connection.execute(sql) # res is a sqlite3.Cursor object
parse0 = res.fetchone() # 1st record only
if parse0 is None: return False
else: return True
def DB_readTableDevice(DB_Connection):
"""Read the data from the database table device"""
sql = """
select
ddatetime,
dname
from device
"""
res = DB_Connection.execute(sql)
rows = res.fetchone()
#print("DB_readTableDevice: fetched 1 rows with items: ", len(rows), rows)
return rows
def DB_readLogcycle(DB_Connection):
"""Read the data from the database table LogCycle"""
sql = """
select
lcycle
from logCycle
"""
res = DB_Connection.execute(sql) # res is a sqlite3.Cursor object
parse0 = res.fetchone() # 1st record only
if parse0 is None:
return None
else:
return parse0[0]
def DB_insertLogcycle(DB_Connection, value):
"""Insert the value into the database table Log Cycle"""
defname = "DB_insertLogcycle: "
sql = """INSERT INTO logCycle (lcycle) VALUES (?)"""
# vprint(defname + "SQL: ", sql, ", Data: ", value)
try:
DB_Connection.execute(sql, (value,))
except Exception as e:
srcinfo = defname + "Exception: " + sql
exceptPrint(e, srcinfo)
DB_commit(DB_Connection)
def DB_updateLogcycle(DB_Connection, value):
"""Update database table Log Cycle in rowid=1 with value"""
# DB_Connection:
# g.logConn
# g.hisConn
defname = "DB_updateLogcycle: "
sql = """UPDATE logCycle SET lcycle=(?) where ROWID=1"""
vprint(defname + "SQL:", sql, ", Data: ", value)
try:
DB_Connection.execute(sql, (value,))
except Exception as e:
srcinfo = defname + "Exception: " + sql
exceptPrint(e, srcinfo)
DB_commit(DB_Connection)
def DB_setValuesToNull(DB_Connection, variable, leftdate, rightdate):
"""Set a range of values in the table data to Null which are between leftdata and right date"""
defname = "DB_setValuesToNull: "
# remove selected var within given range
DBvarname = g.VarsCopy[variable][5]
sql = "UPDATE data SET {}=NULL where (datetime(julianday) >= '{}' and datetime(julianday) <= '{}')".format(DBvarname, leftdate, rightdate)
vprint(defname + "Data: variable: {}, leftdate: {}, rightdate: {}".format(variable, leftdate, rightdate))
vprint(defname + "SQL:", sql,)
try:
DB_Connection.execute(sql)
except Exception as e:
srcinfo = defname + "Exception: " + sql
exceptPrint(e, srcinfo)
# DB is locked before commit
DB_commit(DB_Connection)
# remove all rows where all vars are NULL (DateTime may be not NULL)
sql2 = """DELETE FROM data WHERE (cpm is NULL and cps is NULL and cpm1st is NULL and cps1st is NULL
and cpm2nd is NULL and cps2nd is NULL and cpm3rd is NULL and cps3rd is NULL
and t is NULL and p is NULL and h is NULL and x is NULL)"""
try:
DB_Connection.execute(sql2)
except Exception as e:
srcinfo = defname + "Exception: " + sql2
exceptPrint(e, srcinfo)
# DB is locked before commit
DB_commit(DB_Connection)
def createByteMapFromDB(value):
"""Read data from table bin as blob and print map of value into notePad.
Value is meant ot be FF (=empty value) or AA (=DateTime String)"""
if g.hisConn is None:
g.exgg.showStatusMessage("No data available")
return
start = time.time()
fprint(header("Show History Binary Data as Map of 0xAA and 0xFF"))
fprint("from: {}\n".format(g.hisDBPath))
hist = DB_readBinblob(g.hisConn)
#print("createByteMapFromDB: hist:", hist)
if hist is None:
efprint("No binary data found in this database")
return
setBusyCursor()
ruler = "Byte No|"
for i in range(127, 1024, 128): ruler += " {:4d}|".format(i)
ruler += "\n"
lenLine = 1024
lenChunk = 16
lenHist = len(hist)
lstlines = ""
lstlines += "One single printed character maps a chunk of 16 bytes of data\n"
lstlines += "'A' marks occurence of value 0xAA in chunk (AA => DateTime String)\n"
lstlines += "'F' marks occurence of value 0xFF in chunk (FF => empty value)\n"
lstlines += ruler
counter = 0
batch = 100
for i in range(0, lenHist, lenLine):
if counter == batch:
fprint(lstlines[:-1])
lstlines = ""
counter = 0
lstline ="{:7d}|".format(i)
for j in range(0, lenLine, lenChunk):
l = i + j
if l >= lenHist: break
if 0xAA in hist[l:l + lenChunk]: s = "A" # check first for AA, may miss FF
elif 0xFF in hist[l:l + lenChunk]: s = "F"
else: s = "."
lstline += s
lstlines += lstline + "\n"
counter += 1
lstlines += ruler
fprint(lstlines)
vprint("timing 16b per char chunks: {:7.2f}ms".format((time.time() -start)*1000))
setNormalCursor()
def createParseFromDB(lmax=12, full=True):
"""Read the data from the database data table include comments and parse comments """
if g.hisConn is None:
g.exgg.showStatusMessage("No data available")
return
fprint(header("Show History Data with Parse Comments"))
fprint("from: {}\n".format(g.hisDBPath))
if not DB_readParse(g.hisConn):
efprint("No Parse Comments data found in this database")
return
setBusyCursor()
sql = """
select
julianday,
printf(" %8s, %19s, %6s, %6s, %6s, %6s, %6s, %6s, %6s, %6s, %s",
data.dindex ,
datetime(julianday) ,
ifnull(cpm, ""),
ifnull(cps, ""),
ifnull(cpm1st, ""),
ifnull(cps1st, ""),
ifnull(cpm2nd, ""),
ifnull(cps2nd, ""),
ifnull(cpm3rd, ""),
ifnull(cps3rd, ""),
ifnull(parse.pinfo, "")
) as datastr,
data.dindex
from data
LEFT JOIN parse
ON data.dindex = parse.pindex
union
select
cjulianday as julianday,
printf("#%8s, %19s, %s",
ctype ,
datetime(cjulianday),
cinfo
) as commentstr,
ctype
from comments
order by julianday asc, data.dindex asc
"""
res = g.hisConn.execute(sql)
data = res.fetchall()
#print("createParseFromDB: sql:", sql, "\nlen(data):", len(data), "data:\n", data)
ruler = "# Index, DateTime, CPM, CPS, CPM1st, CPS1st, CPM2nd, CPS2nd, CPM3rd, CPS3rd, ParseInfo"
fprint(ruler)
counter = 0
counter_max = 64
printstring = ""
g.stopPrinting = False
if full:
for a in data:
printstring += a[1] + "\n"
# print("createParseFromDB: a[1]:", a[1])
if counter >= counter_max:
fprint(printstring[:-1])
printstring = ""
counter = 0
QtUpdate()
# print("counter_max: ", counter_max)
if counter_max < 5000: counter_max *= 2
if g.stopPrinting: break
counter += 1
g.stopPrinting = False
else:
for a in data[:+lmax]: fprint(a[1])
fprint('...')
for a in data[-lmax:]: fprint(a[1])
fprint(printstring[:-1])
fprint(ruler)
setNormalCursor()
def createLstFromDB(*args, lmax=12, full=True):
"""create Binary Data in Human-Readable Form from the database table bin"""
#vprint("createLstFromDB: lmax={}, full={}".format(lmax, full))
if g.hisConn is None:
g.exgg.showStatusMessage("No data available")
return
if full: addh = "" # all lines
else: addh = " Excerpt" # excerpt only
fprint(header("Show History Binary Data in Human Readable Form" + addh))
fprint("from: {}\n".format(g.hisDBPath))
hist = DB_readBinblob(g.hisConn)
#print("createLstFromDB: hist:", hist)
if hist is None:
efprint("No binary data found in this database")
return
setBusyCursor()
histlen = len(hist) # Total length; could be any length e.g. when read from file
histRC = hist.rstrip(b'\xFF') # after right-clip FF (removal of all trailing 0xff)
histRClen = len(histRC) # total byte count
ppagesize = 1024 # for the breaks in printing
data_origin = "Download Date: {} from device {}".format(* DB_readTableDevice(g.hisConn))
# header
lstlines = "#History Download - Binary Data in Human-Readable Form\n"
lstlines += "#{}\n".format(data_origin)
lstlines += " address :value | address :value | address :value | address :value |\n"
lstlines += " hex=dec hex=dec| hex=dec hex=dec| hex=dec hex=dec| hex=dec hex=dec|\n"
# This takes the full hist data clipped for FF, independent of the
# memory setting of the currently selected counter
for i in range(0, histRClen, ppagesize):
for j in range(0, ppagesize, 4):
lstline =""
for k in range(0, 4):
if j + k >= ppagesize: break
l = i + j + k
if l >= histRClen: break
lstline += "{:05x}={:<7d}:{:02x}={:<3d}|".format(l, l, histRC[l], histRC[l])
# lstlines += lstline[:-1] + "\n"
lstlines += lstline + "\n"
if l >= histRClen: break
if l < histRClen:
lstlines += "Reading Page {:5.0f} of size {} Bytes complete; next address: 0x{:05x}={:7d} {}\n\n"\
.format(i/ppagesize + 1, ppagesize, i+ppagesize, i+ppagesize, "-" * 6)
if (l + 1) % 4096 == 0 :
lstlines += "Reading Page {:5.0f} of size {} Bytes complete {}\n\n".format((l + 1)/4096, 4096, "-" * 37)
if l >= histRClen: break
if histRClen < histlen:
lstlines += "Remaining {} Bytes to the end of history (size:{}) are all 0xFF\n".format(histlen -histRClen, histlen)
else:
lstlines += "End of history reached\n"
listlstlines = lstlines.split('\n')[:-1]
counter = 0
counter_max = 64
printstring = ""
g.stopPrinting = False
if full:
for a in listlstlines:
printstring += a + "\n"
if counter >= counter_max:
fprint(printstring[:-1])
printstring = ""
counter = 0
QtUpdate()
# print("counter_max: ", counter_max)
if counter_max < 8100: counter_max *= 2
if g.stopPrinting: break
counter += 1
g.stopPrinting = False
fprint(printstring[:-1])
else: #excerpt only
for a in listlstlines[:+lmax]: fprint(a)
fprint('...')
for a in listlstlines[-lmax:]: fprint(a)
fprint("")
setNormalCursor()
###############################################################################
# Variable definitions:
sqlGetLogUnionAsString = """
select
julianday,
printf(" %8s, %19s, %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s",
dindex ,
datetime(julianday),
ifnull(cpm, ""),
ifnull(cps, ""),
ifnull(cpm1st, ""),
ifnull(cps1st, ""),
ifnull(cpm2nd, ""),
ifnull(cps2nd, ""),
ifnull(cpm3rd, ""),
ifnull(cps3rd, ""),
ifnull(T, ""),
ifnull(P, ""),
ifnull(H, ""),
ifnull(X, "")
) as datastr,
dindex
from data
union
select
cjulianday as julianday,
printf("#%8s, %19s, %s",
ctype ,
datetime(cjulianday),
cinfo
) as commentstr,
ctype
from comments
order by julianday asc, dindex asc
"""
# sql INSERT commands
# NOTE: when the argument to julianday is already julianday, sqlite does not change it!
# Julianday: julianday(timestring [, modifier1, ...])
# timestring: now: now is a literal used to return the current date
# modifier: localtime: Adjusts date to localtime, assuming the timestring was expressed in UTC
# modifier: utc: Adjusts date to UTC, assuming the timestring was expressed in localtime
# sqlInsertData = """INSERT INTO data (dindex, Julianday, cpm, cps, cpm1st, cps1st, cpm2nd, cps2nd, cpm3rd, cps3rd, t, p, h, x) VALUES (?,julianday(?,?),?,?,?,?,?,?,?,?,?,?,?,?)"""
sqlInsertData = """INSERT INTO data (dindex, Julianday, cpm, cps, cpm1st, cps1st, cpm2nd, cps2nd, cpm3rd, cps3rd, t, p, h, x) VALUES (?,julianday(?),?,?,?,?,?,?,?,?,?,?,?,?)"""
# sqlInsertComments = """INSERT INTO comments (ctype, cJulianday, cinfo) VALUES (?, julianday(?, ?), ?)"""
sqlInsertComments = """INSERT INTO comments (ctype, cJulianday, cinfo) VALUES (?, julianday(?), ?)"""
sqlInsertParse = """INSERT INTO parse (pindex, pinfo) VALUES (?, ?)"""
sqlInsertDevice = """INSERT INTO device (ddatetime, dname) VALUES (?, ?)"""
sqlInsertBin = """INSERT INTO bin (bblob) VALUES (?)"""
# assemble all the commands needed to make the database structure as a list,
# and any commands needed to run after openeing/creating the db
sqlCreate = []
# make table data
# Index, DateTime, CPM, CPS, CPM1st, CPS1st, CPM2nd, CPS2nd, CPM3rd, CPS3rd, Temp, Press, Humid, RMCPM
sqlCreate.append('''
CREATE TABLE data
(
dindex INTEGER,
Julianday REAL,
CPM REAL,
CPS REAL,
CPM1st REAL,
CPS1st REAL,
CPM2nd REAL,
CPS2nd REAL,
CPM3rd REAL,
CPS3rd REAL,
T REAL,
P REAL,
H REAL,
X REAL
)
''')
# make table comments
# ctype, DateTime, cinfo
sqlCreate.append('''
CREATE TABLE comments
(
ctype INTEGER,
cJulianday REAL,
cinfo TEXT
)
''')
# make table parse
# pindex (for joining with data table), pinfo (the parse text)
sqlCreate.append('''
CREATE TABLE parse
(
pindex INTEGER,
pinfo TEXT
)
''')
# make table bin
# storing the binary data as a blob
sqlCreate.append('''
CREATE TABLE bin
(
bblob BLOB
)
''')
# make table device
# storing the download datetime string and the device name
sqlCreate.append('''
CREATE TABLE device
(
ddatetime TEXT,
dname TEXT
)
''')
# make table logCycle
# storing the Log Cycle in sec
sqlCreate.append('''
CREATE TABLE logCycle
(
lcycle FLOAT
)
''')
sqlCreate.append("""CREATE VIEW ViewData AS Select ROWID, Datetime(Julianday), * from data order by Julianday, dindex""")
sqlCreate.append("""CREATE VIEW ViewComments AS Select ROWID, Datetime(cJulianday), * from comments order by cJulianday, ctype """)
sqlCreate.append("""CREATE VIEW ViewUnion AS {}""".format(sqlGetLogUnionAsString))
def getShowCompactDataSql(varchckd):
"""gets unioned data & comments, but only for variables existing in DB"""
defname = "getShowCompactDataSql: "
# First 12 {} are for the format for the 12 vars, like '%7.7g'
# next 12 {} are for the values of the 12 vars
sqlprintftmplt = """
printf(" %8s, %19s{}{}{}{}{}{}{}{}{}{}{}{}",
dindex,
datetime(julianday)
{}{}{}{}{}{}{}{}{}{}{}{}
)
""" # needs a filler with 24 places
ruler = "# Index, DateTime"
filler = [""] * 24
for i, vname in enumerate(g.VarsCopy):
########################################################################
# After the T, P, H, X variables were renamed to Temp, Press, Humid, Xtra
# but the database structure left on the old style, this renaming became
# necessary:
oldvname = g.VarsCopy[vname][5]
########################################################################
# NOTE: in printf format '%7.7g' a SQL NULL will be printed as '0" (zero)
# in printf format '%8s' a SQL NULL will be an empty string
# print("i:{:2d}, vname: {:6s}, oldvname: {}".format(i, vname, oldvname))
nan = g.NAN
if varchckd[vname]:
# filler [i] = ", %8.6g" # 1 ... 12 for the format
filler [i] = ", %8s" # 1 ... 12 for the format
filler [i+12] = ", ifnull({}, 'nan')".format(oldvname) # 13 ... 24 for the values
# ### testing