-
Notifications
You must be signed in to change notification settings - Fork 1
/
db_from_datafile.py
1203 lines (995 loc) · 37.5 KB
/
db_from_datafile.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
"""Load datafile records into TagTracker database.
Options:
--force: reload given datafiles even if already loaded (default behaviour
is to successfully load any given file only once, as identified
by its file fingerprint (md5hash))
--quiet: no output except error output (to stderr)
--verbose: extra-chatty output
This should run on the tagtracker server.
Supersedes "tracker2db.py"
This is a script to update a persistent SQLite database in a configurable
directory with data from all available (by default) or specific TagTracker
data files. It uses some modules that it shares in common with the TT client.
Before running this, the database will need to be created.
See "create_database.sql".
By default this avoids repeating a previously successful datafile load
by keeping a datafile_loads table in the database. The --force option
will force reloading.
Copyright (C) 2024 Todd Glover & Julias Hocking
Notwithstanding the licensing information below, this code may not
be used in a commercial (for-profit, non-profit or government) setting
without the copyright-holder's written consent.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import glob
import os
import sqlite3
import sys
from dataclasses import dataclass, field
import subprocess
from datetime import datetime
import hashlib
# import tt_datafile
import common.tt_dbutil as db
from common.tt_dbutil import SQL_CRITICAL_ERRORS, SQL_MODERATE_ERRORS
# import tt_globals
import common.tt_util as ut
from common.tt_trackerday import TrackerDay, TrackerDayError
from common.tt_biketag import BikeTagError
from common.tt_bikevisit import BikeVisit
from common.tt_daysummary import DaySummary, PeriodDetail
# from common.tt_time import VTime
from common.tt_constants import REGULAR, OVERSIZE, COMBINED
# Pre-declare this global for linting purposes.
args = None
# Default org_handle -- make this match default text in CREATE_DATABASE sql script
DEFAULT_ORG = "no_org"
# Values for good & bad status
STATUS_GOOD = "GOOD" # File has not (yet) been rejected or had errors
STATUS_BAD = "BAD" # File has errors
STATUS_SKIP_GOOD = "SKIP_PRIOR" # Skip file because was loaded ok previously
STATUS_SKIP_LATER = "SKIP_TAIL" # Skip file because another same-named is later
STATUS_SKIP_NEWER = "SKIP_NEWER" # Skip file because another same-named is newer
# Names for tables and columns.s
# Table for logging datafile loads
TABLE_LOADS = "dataloads"
COL_DAYID = "day_id"
COL_FINGERPRINT = "datafile_fingerprint"
COL_DATAFILE = "datafile_name"
COL_TIMESTAMP = "datafile_timestamp"
COL_BATCH = "batch"
## COL_DATE = "date" FIXME: v2 this uses a DAY_ID
# (Also uses COL_DATE and COL_BATCH)
# # Table of individual bike visits
# TABLE_VISITS = "visit"
# COL_ID = "id" # text date.tag PK
# COL_DATE = "date"
# COL_TAG = "tag"
# COL_BIKETYPE = "type"
# COL_TIME_IN = "time_in"
# COL_TIME_OUT = "time_out"
# COL_DURATION = "duration"
# COL_NOTES = "notes"
# COL_BATCH = "batch"
# # Table of day summaries
# TABLE_DAYS = "day"
# # COL_DATE name reused - text date PK
# COL_REGULAR = "parked_regular" # int count
# COL_OVERSIZE = "parked_oversize" # int count
# COL_TOTAL = "parked_total" # int sum of 2 above
# COL_TOTAL_LEFTOVER = "leftover" # int count
# COL_MAX_REGULAR = "max_reg" # int count of max regular bikes
# COL_MAX_REGULAR_TIME = "time_max_reg" # HHMM time
# COL_MAX_OVERSIZE = "max_over" # int count of max oversize bikes
# COL_MAX_OVERSIZE_TIME = "time_max_over" # HHMM time
# COL_MAX_TOTAL = "max_total" # int sum of 2 above
# COL_MAX_TOTAL_TIME = "time_max_total" # HHMM
# COL_TIME_OPEN = "time_open" # HHMM opening time
# COL_TIME_CLOSE = "time_closed" # HHMM closing time
# COL_DAY_OF_WEEK = "weekday" # ISO 8601-compliant 1-7 M-S
# COL_PRECIP_MM = "precip_mm" # mm (bulk pop from EnvCan dat)
# COL_TEMP = "temp"
# COL_SUNSET = "sunset" # HHMM time at sunset - same
# COL_EVENT = "event" # brief name of nearby event
# COL_EVENT_PROX = "event_prox_km" # est. num of km to event
# COL_REGISTRATIONS = "registrations" # num of bike registrations recorded
# # COL_NOTES name reused
# # COL_BATCH name reused
# # Table of tags contexts
# TABLE_TAGS_CONTEXT = "taglist"
# COL_REGULAR_CONTEXT = "regular"
# COL_OVERSIZE_CONTEXT = "oversize"
# COL_RETIRED_CONTEXT = "retired"
# Bike-type codes. Must match check constraint in code table TYPES.CODE
# REGULAR = "R"
# OVERSIZE = "O"
class DBError(Exception):
pass
# @dataclass
# class DayStats:
# # Summary stats & such for one day.
# # This makes up most of a record for a DAY row,
# date: str
# regular_parked: int = 0
# oversize_parked: int = 0
# total_parked: int = 0
# total_leftover: int = 0
# max_regular_num: int = 0
# max_regular_time: VTime = ""
# max_oversize_num: int = 0
# max_oversize_time: VTime = ""
# max_total_num: int = 0
# max_total_time: VTime = ""
# time_open: VTime = ""
# time_close: VTime = ""
# weekday: int = None
# registrations: int = 0
@dataclass
class Statuses:
"""Keep track of status of individual files & overall program."""
start_time: str = ut.iso_timestamp()
status: str = STATUS_GOOD
errors: int = 0
error_list: list = field(default_factory=list)
files: dict = field(default_factory=dict)
@classmethod
def set_bad(cls, error_msg: str = "Unspecified error", silent: bool = False):
cls.status = STATUS_BAD
cls.errors += 1
cls.error_list += [error_msg]
if not silent:
print(error_msg, file=sys.stderr)
@classmethod
def num_files(cls, status: str = "") -> int:
"""Return count of files in a given status.
status is a known status code, or "".
If "", returns the total number of files."""
if status:
return len([f for f in cls.files.values() if f.status == status])
return len(cls.files)
@dataclass
class FileInfo:
name: str
basename: str = ""
status: str = STATUS_GOOD
fingerprint: str = None
timestamp: str = None
errors: int = 0
error_list: list = field(default_factory=list)
def set_bad(self, error_msg: str = "Unspecified error", silent: bool = False):
"""Set a file's info to a fail state, emit error."""
def print_first_line(msg: str):
"""Format for printing top line of error list."""
print(f"{msg} [{self.name}]", file=sys.stderr)
self.status = STATUS_BAD
self.errors += 1
self.error_list += [error_msg]
if not silent:
if isinstance(error_msg, list):
print_first_line(error_msg[0] if error_msg else "")
for line in error_msg[1:]:
print(line, file=sys.stderr)
else:
print_first_line(error_msg)
# def create_logtable(dbconx: sqlite3.Connection):
# """Creates the load-logging table in the database."""
# if args.verbose:
# print(f"Assuring table {TABLE_LOADS} exists.")
# error_msg = sql_exec_and_error(
# f"""CREATE TABLE IF NOT EXISTS
# {TABLE_LOADS} (
# {COL_DATE} TEXT PRIMARY KEY NOT NULL,
# {COL_DATAFILE} TEXT NOT NULL,
# {COL_TIMESTAMP} TEXT NOT NULL,
# {COL_FINGERPRINT} TEXT NOT NULL,
# {COL_BATCH} TEXT NOT NULL
# );""",
# dbconx,
# )
# if error_msg:
# Statuses.set_bad(f" SQL error creating datafile_loads: {error_msg}")
# dbconx.close()
# sys.exit(1)
def is_linux() -> bool:
"""Check if running in linux."""
system_platform = sys.platform
return system_platform.startswith("linux")
def get_file_fingerprint(file_path):
"""Get a file's fingerprint."""
def get_file_md5_linux(file_path):
"""Get an md5 digest by calling the system program."""
try:
result = subprocess.run(
["md5sum", file_path], capture_output=True, text=True, check=True
)
md5sum_output = result.stdout.strip().split()[0]
return md5sum_output
except subprocess.CalledProcessError as e:
print(f" Error: {e}", file=sys.stderr)
return None
def get_file_md5_windows(file_path):
"""Calculate the MD5 checksum for a given file by reading the file.
This one would be OS independent.
"""
# Open the file in binary mode
with open(file_path, "rb") as file:
# Create an MD5 hash object
md5_hash = hashlib.md5()
# Read the file in chunks to avoid loading the entire file into memory
for chunk in iter(lambda: file.read(4096), b""):
# Update the hash object with the chunk
md5_hash.update(chunk)
# Get the hexadecimal digest of the hash
md5_checksum = md5_hash.hexdigest()
return md5_checksum
# On linux, prefer calling the system md5sum program
if is_linux():
return get_file_md5_linux(file_path)
else:
return get_file_md5_windows(file_path)
def get_load_fingerprints(dbconx: sqlite3.Connection) -> list[str]:
"""Get a list of the fingerprints of files last loaded ok."""
# FIXME: probably want to do for only this organization's scope?
cursor = dbconx.cursor()
rows = cursor.execute(f"SELECT {COL_FINGERPRINT} FROM {TABLE_LOADS}").fetchall()
fingerprints = [r[0] for r in rows]
cursor.close()
return fingerprints
def get_file_timestamp(file_path):
"""Get a file's timestamp as an iso8601 string."""
try:
timestamp = os.path.getmtime(file_path)
modified_time = datetime.fromtimestamp(timestamp)
return modified_time.strftime("%Y-%m-%dT%H:%M:%S")
except FileNotFoundError:
print(" File not found {e}.", file=sys.stderr)
return None
def fetch_existing_weather(
cursor: sqlite3.Connection.cursor, date: str, orgsite_id: int
) -> tuple[float, float]:
"""Fetch any existing temp and precip data from the given day.
This uses data and orgsite_id since day_id not known at time this is called."""
if args.verbose:
print(f" Fetching existing weather (temp/precip) for {orgsite_id=}/'{date}'.")
row = cursor.execute(
f"SELECT max_temperature, precipitation FROM day WHERE orgsite_id = {orgsite_id} AND date = '{date}';"
).fetchone()
if not row:
return None, None
return row[0], row[1]
# FIXME: use versions in tt_dbutil
def fetch_org_id(cursor: sqlite3.Connection.cursor, org_handle: str) -> int:
"""Fetch the org id."""
org_handle = org_handle.strip().lower()
if args.verbose:
print(f" Fetching org_id for '{org_handle}'.")
row = cursor.execute(
f"SELECT id FROM org WHERE org_handle = '{org_handle}';"
).fetchone()
if not row:
raise DBError(f"No match for org_handle '{org_handle}'.")
this_id = row[0]
if not isinstance(this_id, int):
raise DBError(f"Not integer: org.id '{this_id}' (type {type(this_id)})")
return this_id
# FIXME: separate making new into its own. Use fetch_*() from tt_dbutil
def fetch_orgsite_id(
cursor: sqlite3.Connection.cursor,
site_handle: str,
org_id: int,
site_name: str = "",
insert_new: bool = False,
) -> int:
"""Fetch the PK id from the orgsite table.
If not found and insert_new, will create a new record."""
site_handle = site_handle.strip().lower()
if args.verbose:
print(f" Fetching orgsite_id for '{site_handle}', org_id {org_id}.")
row = cursor.execute(
f"SELECT id FROM orgsite WHERE site_handle = '{site_handle}' AND org_id = {org_id};",
).fetchone()
if not row:
if not insert_new:
raise DBError(
f"No match for site_handle '{site_handle}' with org_id {org_id}."
)
else:
this_id = cursor.execute(
"INSERT INTO orgsite (org_id,site_handle,site_name) VALUES (?,?,?)",
(org_id, site_handle, site_name),
).lastrowid
return this_id
this_id = row[0]
if not isinstance(this_id, int):
raise DBError(f"Not integer: orgsite.id '{this_id}' (type {type(this_id)})")
return this_id
def fetch_day_id(
cursor: sqlite3.Connection.cursor, date: str, orgsite_id: int, null_ok: bool = True
) -> int:
"""Fetch the DAY id for this date/site.
If null_ok, then it's ok if no matching record; otherwise a DBError."""
if args.verbose:
print(f" Fetching day_id for {orgsite_id=}/'{date}'.")
row = cursor.execute(
f"SELECT id FROM day WHERE orgsite_id = {orgsite_id} AND date = '{date}';"
).fetchone()
if not row:
if null_ok:
return None
raise DBError(f"No match for {orgsite_id=}/{date=}.")
this_id = row[0]
if not isinstance(this_id, int):
raise DBError(f"Not integer: day.id '{this_id}' (type {type(this_id)})")
return this_id
def insert_new_orgsite(
cursor: sqlite3.Connection.cursor,
org_id: int,
site_handle: str,
site_name: str = "",
) -> int:
"""Insert new org/site into orgsite table, returns orgsite_id."""
this_id = cursor.execute(
"INSERT INTO orgsite (org_id,site_handle,site_name) VALUES (?,?,?)",
(org_id, site_handle, site_name),
).lastrowid
return this_id
def delete_one_day_data(cursor: sqlite3.Connection.cursor, date: str, orgsite_id: int):
"""Delete one complete day's data from all tables."""
day_id = db.fetch_day_id(cursor=cursor, date=date, maybe_orgsite_id=orgsite_id)
if args.verbose:
print(f" Deleting records for '{orgsite_id=}'/'{date}'.")
if day_id is not None:
cursor.execute(f"DELETE FROM VISIT WHERE day_id = {day_id}")
cursor.execute(f"DELETE FROM BLOCK WHERE day_id = {day_id}")
cursor.execute(f"DELETE FROM DATALOADS WHERE day_id = {day_id}")
cursor.execute(f"DELETE FROM DAY WHERE id = {day_id}")
def insert_into_day(
orgsite_id: int,
td: TrackerDay,
summary: DaySummary,
batch_id: str,
cursor: sqlite3.Connection.cursor,
) -> int:
"""Load into the DAY table. Returns the rowid of the record inserted. None if failed."""
# This requires some fancy footwork in order to preserve any existing
# environmental values (rain, temp, sunset)
# since the INSERT OR REPLACE really does do a REPLACE, meaning
# that (unlike an update), any columns not specifcally names are
# set to their default values
# Insert/replace this day's summary info.
# Have to delete and replace since doing an INSERT OR REPLACE
# changes the PK id. So *could* turn constraints off, update the
# FKs, then turn back on, but this seems simpler since will be adding
# new VISIT and BLOCK data anyway. The cost is that must cache the
# environmental data (temperature and precipitation).
# Fetch current temp and precip
existing_temp, existing_precip = fetch_existing_weather(
cursor=cursor, date=td.date, orgsite_id=orgsite_id
)
# Delete existing data for this day
delete_one_day_data(cursor=cursor, date=td.date, orgsite_id=orgsite_id)
if args.verbose:
print(" Adding day summary to database.")
# Save to DAY table
cursor.execute(
"""
INSERT INTO DAY (
orgsite_id,
date,
time_open,
time_closed,
weekday,
num_parked_regular,
num_parked_oversize,
num_parked_combined,
num_remaining_regular,
num_remaining_oversize,
num_remaining_combined,
num_fullest_regular,
num_fullest_oversize,
num_fullest_combined,
time_fullest_regular,
time_fullest_oversize,
time_fullest_combined,
bikes_registered,
batch,
max_temperature,
precipitation
)
VALUES (
?,?,?,?,?,
?,?,?, ?,?,?, ?,?,?, ?,?,?,
?,?,
?,?
)
""",
(
# td.org_id, # Add org_id to TrackerDay class
# td.site_id, # Add site_id to TrackerDay class
orgsite_id,
summary.whole_day.date,
summary.whole_day.time_open,
summary.whole_day.time_closed,
ut.dow_int(td.date),
summary.whole_day.num_parked_regular,
summary.whole_day.num_parked_oversize,
summary.whole_day.num_parked_combined,
summary.whole_day.num_remaining_regular,
summary.whole_day.num_remaining_oversize,
summary.whole_day.num_remaining_combined,
summary.whole_day.num_fullest_regular,
summary.whole_day.num_fullest_oversize,
summary.whole_day.num_fullest_combined,
summary.whole_day.time_fullest_regular,
summary.whole_day.time_fullest_oversize,
summary.whole_day.time_fullest_combined,
td.registrations.num_registrations,
batch_id,
existing_temp,
existing_precip,
),
)
day_id = cursor.lastrowid
return day_id
# def day_tags_context_into_db(
# file_info: FileInfo,
# day: OldTrackerDay,
# day_totals: DayStats,
# batch: str,
# dbconx: sqlite3.Connection,
# ) -> bool:
# """Load tags context into database."""
# if args.verbose:
# print(" Adding lists of retired, regular and oversize tags to database.")
# regular_tags = ",".join(sorted(list(day.regular)))
# oversize_tags = ",".join(sorted(list(day.oversize)))
# retired_tags = ",".join(sorted(list(day.retired)))
# sql_error = sql_exec_and_error(
# f"""INSERT OR REPLACE INTO {TABLE_TAGS_CONTEXT} (
# {COL_DATE},
# {COL_REGULAR_CONTEXT},
# {COL_OVERSIZE_CONTEXT},
# {COL_RETIRED_CONTEXT}
# ) VALUES (
# '{day_totals.date}',
# '{regular_tags}',
# '{oversize_tags}',
# '{retired_tags}'
# );""",
# dbconx,
# )
# # Did it work? (No error message means success.)
# if sql_error:
# file_info.set_bad(f"SQL error adding to {TABLE_TAGS_CONTEXT}: {sql_error}")
# return False
# return True
def insert_into_visit(
day: TrackerDay,
cursor: sqlite3.Connection.cursor,
day_id: int,
) -> bool:
"""Load this day's visits into the database."""
# if args.verbose:
# print(" Deleting any existing visits info for this day from database.")
# sql_error = sql_exec_and_error(
# f"DELETE FROM {TABLE_VISITS} WHERE date = '{day_totals.date}'", dbconx
# )
# if sql_error:
# file_info.set_bad(f"Error deleting VISIT rows: {sql_error}")
# return False
if args.verbose:
print(f" Adding {len(day.all_visits())} visits to database.")
for visit in day.all_visits():
visit: BikeVisit
biketype = "R" if day.biketags[visit.tagid].bike_type == REGULAR else "O"
# Save to VISIT table
cursor.execute(
"""
INSERT INTO VISIT (
day_id,
time_in,
time_out,
duration,
bike_type,
bike_id
)
VALUES (?,?,?,?,?,?)
""",
(
day_id,
visit.time_in,
visit.time_out,
visit.duration(day.time_closed,is_close_of_business=True),
biketype,
visit.tagid,
),
)
return True
def insert_into_block(
summary: DaySummary,
cursor: sqlite3.Connection.cursor,
day_id: int,
) -> bool:
"""Load this day's block data into the database."""
if args.verbose:
print(f" Adding {len(summary.blocks)} data blocks to database.")
for block in summary.blocks.values():
block: PeriodDetail
# Save to BLOCK table
cursor.execute(
"""
INSERT INTO block (
day_id,
time_start,
num_incoming_regular,
num_incoming_oversize,
num_incoming_combined,
num_outgoing_regular,
num_outgoing_oversize,
num_outgoing_combined,
num_on_hand_regular,
num_on_hand_oversize,
num_on_hand_combined,
num_fullest_regular,
num_fullest_oversize,
num_fullest_combined,
time_fullest_regular,
time_fullest_oversize,
time_fullest_combined
)
VALUES (?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?)
""",
(
day_id,
block.time_start,
block.num_incoming[REGULAR],
block.num_incoming[OVERSIZE],
block.num_incoming[COMBINED],
block.num_outgoing[REGULAR],
block.num_outgoing[OVERSIZE],
block.num_outgoing[COMBINED],
block.num_on_hand[REGULAR],
block.num_on_hand[OVERSIZE],
block.num_on_hand[COMBINED],
block.num_fullest[REGULAR],
block.num_fullest[OVERSIZE],
block.num_fullest[COMBINED],
block.time_fullest[REGULAR],
block.time_fullest[OVERSIZE],
block.time_fullest[COMBINED],
),
)
return True
def insert_into_dataloads(
file_info: FileInfo, day_id: int, batch: str, dbconx: sqlite3.Connection
) -> bool:
"""Update table that tracks load successes."""
if args.verbose:
print(f" Updating fileload info for {file_info.basename} into database.")
sql = f"""
INSERT OR REPLACE INTO {TABLE_LOADS} (
{COL_DAYID},
{COL_DATAFILE},
{COL_TIMESTAMP},
{COL_FINGERPRINT},
{COL_BATCH}
) VALUES (
'{day_id}',
'{file_info.name}',
'{file_info.timestamp}',
'{file_info.fingerprint}',
'{batch}'
) """
cursor = dbconx.cursor()
try:
cursor.execute(sql)
except tuple(SQL_MODERATE_ERRORS) as e:
print(f"Non-fatal error occurred: {e}")
return False
except tuple(SQL_CRITICAL_ERRORS) as e:
print(f"Fatal error occurred: {e}")
raise
finally:
cursor.close()
return True
def read_datafile(filename: str) -> tuple[TrackerDay, DaySummary]:
"""Read and prepare one filename into TrackerDay & DaySummary obects."""
file_info: FileInfo = Statuses.files[filename]
if not os.path.isfile(filename):
file_info.set_bad("File not found")
return None, None
if args.verbose:
print(f"Reading {filename}:")
try:
day = TrackerDay.load_from_file(filename)
except (TrackerDayError, BikeTagError) as e:
msg = f"Error reading file {filename=}: {e}. Skipping file."
file_info.set_bad(msg)
# print(msg)
return None, None
lint_msgs = day.lint_check(strict_datetimes=True, allow_quick_checkout=True)
if lint_msgs:
msg = [f"Errors reading datafile {filename}:"] + lint_msgs
file_info.set_bad(msg)
return None, None
day_summary = DaySummary(day=day, as_of_when="24:00")
return day, day_summary
def one_datafile_into_db(filename: str, batch, dbconx) -> str:
"""Record one datafile to the database, returns date.
Reads the datafile, looking for errors.
Calculates summary stats, tables.
Saves the file info & fingerprint to LOAD_INFO table.
Returns the date of the file's data if successful (else "")
Status is also Statuses.files[filename], which is a FileInfo object.
This should create then destroy a cursor, which means rollback or commit.
"""
day, day_summary = read_datafile(filename=filename)
if day is None or day_summary is None:
return None
# Datafile fully loaded, now start db stuff
cursor = sql_begin_transaction(dbconx=dbconx)
if args.verbose:
print(" Fetching org and orgsize ids")
org_id = db.fetch_org_id(cursor=cursor, org_handle=args.org)
if org_id is None:
raise DBError(f"No org matches {args.org_handle}")
orgsite_id = db.fetch_orgsite_id(
cursor=cursor, site_handle=day.site_handle, maybe_org_id=org_id, null_ok=True
)
if orgsite_id is None:
if args.verbose:
print(f" Adding new orgsite {args.org=},{day.site_handle=}")
orgsite_id = insert_new_orgsite(
cursor=cursor,
org_id=org_id,
site_handle=day.site_handle,
site_name=day.site_name,
)
if args.verbose:
print(
f" Date:{day.date} Open:{day.time_open}-{day.time_closed}"
f" Visits:{day_summary.whole_day.num_parked_combined} "
f"Leftover:{day_summary.whole_day.num_remaining_combined} "
f"Registrations:{day.registrations.num_registrations}"
)
# Save data to database
try:
day_id = insert_into_day(
td=day,
summary=day_summary,
orgsite_id=orgsite_id,
batch_id=batch,
cursor=cursor,
)
insert_into_visit(
day=day,
cursor=cursor,
day_id=day_id,
)
insert_into_block(
summary=day_summary,
cursor=cursor,
day_id=day_id,
)
# day_tags_context_into_db(file_info, day, day_totals, batch, dbconx)
# day_blocks_into_db()
insert_into_dataloads(
Statuses.files[filename], day_id=day_id, batch=batch, dbconx=dbconx
)
except (sqlite3.Error, DBError) as err:
print(f"Error:{err}", file=sys.stderr)
dbconx.rollback()
return ""
finally:
cursor.close()
dbconx.commit() # commit as one datafile transaction
if args.verbose:
print(
f" Committed {day_summary.whole_day.num_parked_combined} visits for {day.date}."
)
return day.date
def sql_begin_transaction(dbconx: sqlite3.Connection) -> sqlite3.Connection.cursor:
curs = dbconx.cursor()
curs.execute("BEGIN;")
return curs
def sql_exec_and_error(sql_statement: str, dbconx) -> int:
"""Execute a SQL statement, returns error message (if any).
Presumably there is no error if the return is empty.
Counter-intuitively this means that this returns bool(False) if
this succeeded.
Not suitable (of course) for SELECT statements.
"""
try:
curs = dbconx.cursor()
curs.execute(sql_statement)
except sqlite3.Error as sqlite_err:
print(f"SQLite error:{sqlite_err}", file=sys.stderr)
return sqlite_err if sqlite_err else "Unspecified SQLite error"
# Success
return ""
def get_args() -> argparse.Namespace:
"""Get program arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"-q", "--quiet", action="store_true", help="suppresses all non-error output"
)
parser.add_argument(
"-v", "--verbose", action="store_true", help="provides most detailed output"
)
parser.add_argument(
"-f", "--force", action="store_true", help="load even if previously loaded"
)
parser.add_argument(
"-n",
"--newest-only",
action="store_true",
help="if files have same basename, only consider the newest one",
)
parser.add_argument(
"-t",
"--tail-only",
action="store_true",
help="if files have same basename, only consider "
"the one that is closer to the tail of of the file list",
)
parser.add_argument(
"-o",
"--org",
type=str,
default=DEFAULT_ORG,
help=f"Organization org_handle (default: '{DEFAULT_ORG}')",
)
parser.add_argument(
"dataglob", type=str, nargs="+", help="Fileglob(s) of datafiles to load"
)
parser.add_argument("dbfile", type=str, help="SQLite3 database file")
prog_args = parser.parse_args()
if prog_args.verbose and prog_args.quiet:
prog_args.quiet = False
print("Arg --verbose set; ignoring arg --quiet.")
if prog_args.tail_only and prog_args.newest_only:
print(
"Error: Can not use --newest-only and --tail-only together", file=sys.stderr
)
sys.exit(1)
return prog_args
def find_datafiles(fileglob: list) -> list:
"""Return a list of files from a dataglob." """
maybe_datafiles = []
for this_glob in fileglob:
# print(f"{this_glob=}")
globbed_files = glob.glob(this_glob)
if len(globbed_files) < 1:
print(
f"Error: no files found matching glob '{this_glob}'",
file=sys.stderr,
)
sys.exit(1)
maybe_datafiles += globbed_files
# Make paths absolute
maybe_datafiles = convert_paths_to_absolute(maybe_datafiles)
# Exclude exact duplicates but preserve the file order
maybe_datafiles = dedup_filepaths(maybe_datafiles)
return maybe_datafiles
def dedup_filepaths(filepaths: list[str]) -> list[str]:
"""Deduplicate a list of filepaths, removing dups and preserving order."""
dedupped = []
dups = []
for f in filepaths:
if f in dedupped:
if f not in dups and not args.quiet:
print(
f"Warning: filepath {f} given more than once, ignoring later instances.",
file=sys.stderr,
)
dups.append(f)
else:
dedupped.append(f)
return dedupped
def convert_paths_to_absolute(files: list) -> list:
"""Convert a list of relative paths to absolute paths."""
abs_paths = []
for f in files:
abs_paths.append(os.path.abspath(f))
return abs_paths
def get_files_metadata(maybe_datafiles: list):
"""Gets metadata for the files, loads it into Statuses class."""
for f in maybe_datafiles:
f_info = FileInfo(f)
Statuses.files[f] = f_info
if not os.path.exists(f):
f_info.set_bad("File not found")
continue
f_info.basename = os.path.basename(f)
f_info.fingerprint = get_file_fingerprint(f)
if not f_info.fingerprint:
f_info.set_bad("Can not read md5sum")
continue
f_info.timestamp = get_file_timestamp(f)
if not f_info.timestamp:
f_info.set_bad("Can not read timestamp")
continue
ok_datafiles = [
f for f in Statuses.files if Statuses.files[f].status == STATUS_GOOD