-
Notifications
You must be signed in to change notification settings - Fork 32
/
cache.py
1082 lines (904 loc) · 36.4 KB
/
cache.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
# --------------------------------------------------------------------
# Copyright (C) Oliver 'kfsone' Smith 2014 <[email protected]>:
# Copyright (C) Bernd 'Gazelle' Gollesch 2016, 2017
# Copyright (C) Jonathan 'eyeonus' Jones 2018, 2019
#
# You are free to use, redistribute, or even print and eat a copy of
# this software so long as you include this copyright notice.
# I guarantee there is at least one bug neither of us knew about.
# --------------------------------------------------------------------
# TradeDangerous :: Modules :: Cache loader
#
# TD works primarily from an SQLite3 database, but the data in that
# is sourced from text files.
# data/TradeDangerous.sql contains the less volatile data - systems,
# ships, etc
# data/TradeDangerous.prices contains a description of the price
# database that is intended to be easily editable and commitable to
# a source repository.
#
# TODO: Split prices into per-system or per-station files so that
# we can tell how old data for a specific system is.
from __future__ import annotations
from pathlib import Path
import csv
import os
import re
import sqlite3
import sys
import typing
from functools import partial as partial_fn
from .fs import file_line_count
from .tradeexcept import TradeException
from tradedangerous.misc.progress import Progress, CountingBar
from . import corrections, utils
from . import prices
# For mypy/pylint type checking
if typing.TYPE_CHECKING:
from typing import Any, Callable, Optional, TextIO # noqa
from .tradeenv import TradeEnv
######################################################################
# Regular expression patterns. Here be draegons.
# If you add new patterns:
# - use fragments and re.VERBOSE (see itemPriceRe)
# - use named captures (?P<name> ...)
# - include comments
# # Match the '@ SYSTEM/Station' line
systemStationRe = re.compile(r'^\@\s*(.*)/(.*)')
# # Price Line matching
# first part of any prices line is the item name and paying/asking price
itemPriceFrag = r"""
# match item name, allowing spaces in the name
(?P<item> .*?)
\s+
# price station is buying the item for
(?P<sell> \d+)
\s+
# price station is selling item for
(?P<buy> \d+)
"""
# time formats per https://www.sqlite.org/lang_datefunc.html
# YYYY-MM-DD HH:MM:SS
# YYYY-MM-DDTHH:MM:SS
# HH:MM:SS
# 'now'
timeFrag = r'(?P<time>(\d{4}-\d{2}-\d{2}[T ])?\d{2}:\d{2}:\d{2}|now)'
# <name> <sell> <buy> [ <demand> <supply> [ <time> | now ] ]
qtyLevelFrag = r"""
unk # You can just write 'unknown'
| \? # alias for unknown
| n/a # alias for 0L0
| - # alias for 0L0
| \d+[\?LMH] # Or <number><level> where level is L(ow), M(ed) or H(igh)
| 0 # alias for n/a
| bug
"""
newItemPriceRe = re.compile(r"""
^
{base_f}
(
\s+
# demand units and level
(?P<demand> {qtylvl_f})
\s+
# supply units and level
(?P<supply> {qtylvl_f})
# time is optional
(?:
\s+
{time_f}
)?
)?
\s*
$
""".format(base_f = itemPriceFrag, qtylvl_f = qtyLevelFrag, time_f = timeFrag),
re.IGNORECASE + re.VERBOSE)
######################################################################
# Exception classes
class BuildCacheBaseException(TradeException):
"""
Baseclass for BuildCache exceptions
Attributes:
fileName Name of file being processedStations
lineNo Line the error occurred on
error Description of the error
"""
def __init__(self, fromFile: Path, lineNo: int, error: str = None) -> None:
self.fileName = fromFile.name
self.lineNo = lineNo
self.category = "ERROR"
self.error = error or "UNKNOWN ERROR"
def __str__(self) -> str:
return f'{self.fileName}:{self.lineNo} {self.category} {self.error}'
class UnknownSystemError(BuildCacheBaseException):
"""
Raised when the file contains an unknown star name.
"""
def __init__(self, fromFile: Path, lineNo: int, key: str) -> None:
super().__init__(fromFile, lineNo, f'Unrecognized SYSTEM: "{key}"')
class UnknownStationError(BuildCacheBaseException):
"""
Raised when the file contains an unknown star/station name.
"""
def __init__(self, fromFile: Path, lineNo: int, key: str) -> None:
super().__init__(fromFile, lineNo, f'Unrecognized STAR/Station: "{key}"')
class UnknownItemError(BuildCacheBaseException):
"""
Raised in the case of an item name that we don't know.
Attributes:
itemName Key we tried to look up.
"""
def __init__(self, fromFile: Path, lineNo: int, itemName: str) -> None:
super().__init__(fromFile, lineNo, f'Unrecognized item name: "{itemName}"')
class DuplicateKeyError(BuildCacheBaseException):
"""
Raised when an item is being redefined.
"""
def __init__(self, fromFile: Path, lineNo: int, keyType: str, keyValue: str, prevLineNo: int) -> None:
super().__init__(fromFile, lineNo,
f'Second occurrance of {keyType} "{keyValue}", previous entry at line {prevLineNo}.')
class DeletedKeyError(BuildCacheBaseException):
"""
Raised when a key value in a .csv file is marked as DELETED in the
corrections file.
"""
def __init__(self, fromFile: Path, lineNo: int, keyType: str, keyValue: str) -> None:
super().__init__(
fromFile, lineNo,
f'{keyType} "{keyValue}" is marked as DELETED and should not be used.'
)
class DeprecatedKeyError(BuildCacheBaseException):
"""
Raised when a key value in a .csv file has a correction; the old
name should not appear in the .csv file.
"""
def __init__(self, fromFile: Path, lineNo: int, keyType: str, keyValue: str, newValue: str) -> None:
super().__init__(
fromFile, lineNo,
f'{keyType} "{keyValue}" is deprecated and should be replaced with "{newValue}".'
)
class MultipleStationEntriesError(DuplicateKeyError):
""" Raised when a station appears multiple times in the same file. """
def __init__(self, fromFile: Path, lineNo: int, facility: str, prevLineNo: int) -> None:
super().__init__(fromFile, lineNo, 'station', facility, prevLineNo)
class MultipleItemEntriesError(DuplicateKeyError):
""" Raised when one item appears multiple times in the same station. """
def __init__(self, fromFile: Path, lineNo: int, item: str, prevLineNo: int) -> None:
super().__init__(fromFile, lineNo, 'item', item, prevLineNo)
class InvalidLineError(BuildCacheBaseException):
"""
Raised when an invalid line is read.
Attributes:
problem The problem that occurred
text Offending text
"""
def __init__(self, fromFile: Path, lineNo: int, problem: str, text: str) -> None:
super().__init__(fromFile, lineNo, f'{problem},\ngot: "{text.strip()}".')
class SupplyError(BuildCacheBaseException):
"""
Raised when a supply field is incorrectly formatted.
"""
def __init__(self, fromFile: Path, lineNo: int, category: str, problem: str, value: Any) -> None:
super().__init__(fromFile, lineNo, f'Invalid {category} supply value: {problem}. Got: {value}')
######################################################################
# Helpers
# supply/demand levels are one of '?' for unknown, 'L', 'M' or 'H'
# for low, medium, or high. We turn these into integer values for
# ordering convenience, and we include both upper and lower-case
# so we don't have to sweat ordering.
#
SUPPLY_LEVEL_VALUES = {
'?': -1,
'L': 1, 'l': 1,
'M': 2, 'm': 2,
'H': 3, 'h': 3,
}
def parseSupply(pricesFile: Path, lineNo: int, category: str, reading: str) -> tuple[int, int]:
""" Parse a supply specifier which is expected to be in the <number><?, L, M, or H>, and
returns the units as an integer and a numeric level value suitable for ordering,
such that ? = -1, L/l = 0, M/m = 1, H/h = 2 """
# supply_level <- digit+ level;
# digit <- [0-9];
# level <- Unknown / Low / Medium / High;
# Unknown <- '?';
# Low <- 'L';
# Medium <- 'M';
# High <- 'H';
if reading == '?':
return -1, -1
if reading == '-':
return 0, 0
# extract the left most digits into unit and the last character into the level reading.
units, level = reading[0:-1], reading[-1]
# Extract the right most character as the "level" and look up its numeric value.
levelNo = SUPPLY_LEVEL_VALUES.get(level)
if levelNo is None:
raise SupplyError(
pricesFile, lineNo, category, reading,
f'Unrecognized level suffix: "{level}": expected one of "L", "M", "H" or "?"'
)
# Expecting a numeric value in units, e.g. 123? -> (units=123, level=?)
try:
unitsNo = int(units)
if unitsNo < 0:
# Use the same code-path as if the units fail to parse.
raise ValueError('negative unit count')
except ValueError:
raise SupplyError(
pricesFile, lineNo, category, reading,
f'Unrecognized units/level value: "{level}": expected "-", "?", or a number followed by a level (L, M, H or ?).'
) from None # don't forward the exception itself
# Normalize the units and level when there are no units.
if unitsNo == 0:
return 0, 0
return unitsNo, levelNo
######################################################################
# Code
######################################################################
def getSystemByNameIndex(cur: sqlite3.Cursor) -> dict[str, int]:
""" Build station index in STAR/Station notation """
cur.execute("""
SELECT system_id, UPPER(system.name)
FROM System
""")
return { name: ID for (ID, name) in cur }
def getStationByNameIndex(cur: sqlite3.Cursor) -> dict[str, int]:
""" Build station index in STAR/Station notation """
cur.execute("""
SELECT station_id,
system.name || '/' || station.name
FROM System
INNER JOIN Station
USING (system_id)
""")
return { name.upper(): ID for (ID, name) in cur }
def getItemByNameIndex(cur: sqlite3.Cursor) -> dict[str, int]:
"""
Generate item name index.
"""
cur.execute("SELECT item_id, UPPER(name) FROM item")
return { name: itemID for (itemID, name) in cur }
# The return type of process prices is complicated, should probably have been a type
# in its own right. I'm going to define some aliases to try and persuade IDEs to be
# more helpful about what it is trying to return.
if typing.TYPE_CHECKING:
# A list of the IDs of stations that were modified so they can be updated
ProcessedStationIds= tuple[tuple[int]]
ProcessedItem = tuple[
int, # station ID
int, # item ID
Optional[int | float |str], # modified
int, # demandCR
int, # demandUnits
int, # demandLevel
int, # supplyCr
int, # supplyUnits
int, # supplyLevel
]
ProcessedItems = list[ProcessedItem]
ZeroItems = list[tuple[int, int]] # stationID, itemID
def processPrices(tdenv: TradeEnv, priceFile: Path, db: sqlite3.Connection, defaultZero: bool) -> tuple[ProcessedStationIds, ProcessedItems, ZeroItems, int, int, int, int]:
"""
Yields SQL for populating the database with prices
by reading the file handle for price lines.
:param tdenv: The environment we're working in
:param priceFile: File to read
:param db: SQLite3 database to write to
:param defaultZero: Whether to create default zero-availability/-demand records for data that's not present
(if this is a partial update, you don't want this to be False)
"""
DEBUG0, DEBUG1 = tdenv.DEBUG0, tdenv.DEBUG1
DEBUG0("Processing prices file: {}", priceFile)
cur = db.cursor()
ignoreUnknown = tdenv.ignoreUnknown
quiet = tdenv.quiet
merging = tdenv.mergeImport
systemByName = getSystemByNameIndex(cur)
stationByName = getStationByNameIndex(cur)
stationByName.update(
(sys, ID)
for sys, ID in corrections.stations.items()
if isinstance(ID, int)
)
sysCorrections = corrections.systems
stnCorrections = {
stn: alt
for stn, alt in corrections.stations.items()
if isinstance(alt, str)
}
itemByName = getItemByNameIndex(cur)
defaultUnits = -1 if not defaultZero else 0
defaultLevel = -1 if not defaultZero else 0
stationID = None
facility = None
processedStations = {}
processedSystems = set()
processedItems = {}
stationItemDates = {}
DELETED = corrections.DELETED
items, zeros = [], []
lineNo, localAdd = 0, 0
if not ignoreUnknown:
def ignoreOrWarn(error: Exception) -> None:
raise error
elif not quiet:
ignoreOrWarn = tdenv.WARN
def changeStation(matches: re.Match) -> None:
nonlocal facility, stationID
nonlocal processedStations, processedItems, localAdd
nonlocal stationItemDates
# ## Change current station
stationItemDates = {}
systemNameIn, stationNameIn = matches.group(1, 2)
systemName, stationName = systemNameIn.upper(), stationNameIn.upper()
corrected = False
facility = f'{systemName}/{stationName}'
# Make sure it's valid.
stationID = DELETED
newID = stationByName.get(facility, -1) # why -1 and not None?
DEBUG0("Selected station: {}, ID={}", facility, newID)
if newID is DELETED:
DEBUG1("DELETED Station: {}", facility)
return
if newID < 0:
if utils.checkForOcrDerp(tdenv, systemName, stationName):
return
corrected = True
altName = sysCorrections.get(systemName)
if altName is DELETED:
DEBUG1("DELETED System: {}", facility)
return
if altName:
DEBUG1("SYSTEM '{}' renamed '{}'", systemName, altName)
systemName, facility = altName, "/".join((altName, stationName))
systemID = systemByName.get(systemName, -1) # why -1 and not None?
if systemID < 0:
ignoreOrWarn(
UnknownSystemError(priceFile, lineNo, facility)
)
return
altStation = stnCorrections.get(facility)
if altStation:
if altStation is DELETED:
DEBUG1("DELETED Station: {}", facility)
return
DEBUG1("Station '{}' renamed '{}'", facility, altStation)
stationName = altStation.upper()
facility = f'{systemName}/{stationName}'
newID = stationByName.get(facility, -1)
if newID is DELETED:
DEBUG1("Renamed station DELETED: {}", facility)
return
if newID < 0:
if not ignoreUnknown:
DEBUG0(f'Key value: "{list(stationByName.keys())[list(stationByName.values()).index(128893178)]}"')
ignoreOrWarn(
UnknownStationError(priceFile, lineNo, facility)
)
return
name = utils.titleFixup(stationName)
inscur = db.cursor()
inscur.execute("""
INSERT INTO Station (
system_id, name,
ls_from_star,
blackmarket,
max_pad_size,
market,
shipyard,
modified
) VALUES (
?, ?, 0, '?', '?', '?', '?',
DATETIME('now')
)
""", [systemID, name])
newID = inscur.lastrowid
stationByName[facility] = newID
tdenv.NOTE(
"Added local station placeholder for {} (#{})", facility, newID
)
localAdd += 1
elif newID in processedStations:
# Check for duplicates
if not corrected:
raise MultipleStationEntriesError(
priceFile, lineNo, facility,
processedStations[newID]
)
stationID = newID
processedSystems.add(systemName)
processedStations[stationID] = lineNo
processedItems = {}
cur = db.execute("""
SELECT item_id, modified
FROM StationItem
WHERE station_id = ?
""", [stationID])
stationItemDates = dict(cur)
addItem, addZero = items.append, zeros.append
getItemID = itemByName.get
newItems, updtItems, ignItems = 0, 0, 0
def processItemLine(matches):
nonlocal newItems, updtItems, ignItems
itemName, modified = matches.group('item', 'time')
itemName = itemName.upper()
# Look up the item ID.
itemID = getItemID(itemName, -1)
if itemID < 0:
oldName = itemName
itemName = corrections.correctItem(itemName)
if itemName == DELETED:
DEBUG1("DELETED {}", oldName)
return
itemName = itemName.upper()
itemID = getItemID(itemName, -1)
if itemID < 0:
ignoreOrWarn(
UnknownItemError(priceFile, lineNo, itemName)
)
return
DEBUG1("Renamed {} -> {}", oldName, itemName)
lastModified = stationItemDates.get(itemID, None)
if lastModified and merging:
if modified and modified != 'now' and modified <= lastModified:
DEBUG1("Ignoring {} @ {}: {} <= {}".format(
itemName, facility,
modified, lastModified,
))
if modified < lastModified:
ignItems += 1
return
# Check for duplicate items within the station.
if itemID in processedItems:
ignoreOrWarn(
MultipleItemEntriesError(
priceFile, lineNo,
f'{itemName}',
processedItems[itemID]
)
)
return
demandCr, supplyCr = matches.group('sell', 'buy')
demandCr, supplyCr = int(demandCr), int(supplyCr)
demandString, supplyString = matches.group('demand', 'supply')
if demandCr == 0 and supplyCr == 0:
if lastModified:
addZero((stationID, itemID))
else:
if lastModified:
updtItems += 1
else:
newItems += 1
if demandString:
demandUnits, demandLevel = parseSupply(
priceFile, lineNo, 'demand', demandString
)
else:
demandUnits, demandLevel = defaultUnits, defaultLevel
if demandString and supplyString:
supplyUnits, supplyLevel = parseSupply(
priceFile, lineNo, 'supply', supplyString
)
else:
supplyUnits, supplyLevel = defaultUnits, defaultLevel
if modified == 'now':
modified = None # Use CURRENT_FILESTAMP
addItem((
stationID, itemID, modified,
demandCr, demandUnits, demandLevel,
supplyCr, supplyUnits, supplyLevel,
))
processedItems[itemID] = lineNo
space_cleanup = re.compile(r'\s{2,}').sub
for line in priceFile:
lineNo += 1
text = line.split('#', 1)[0] # Discard comments
text = space_cleanup(' ', text).strip() # Remove leading/trailing whitespace, reduce multi-spaces
if not text:
continue
########################################
# ## "@ STAR/Station" lines.
if text.startswith('@'):
matches = systemStationRe.match(text)
if not matches:
raise InvalidLineError(priceFile, lineNo, "Unrecognized '@' line", text)
changeStation(matches)
continue
if not stationID:
# Need a station to process any other type of line.
raise InvalidLineError(priceFile, lineNo, "Expecting '@ SYSTEM / Station' line", text)
if stationID == DELETED:
# Ignore all values from a deleted station/system.
continue
########################################
# ## "+ Category" lines
if text.startswith('+'):
# we now ignore these.
continue
########################################
# ## "Item sell buy ..." lines.
matches = newItemPriceRe.match(text)
if not matches:
raise InvalidLineError(priceFile, lineNo, "Unrecognized line/syntax", text)
processItemLine(matches)
numSys = len(processedSystems)
if localAdd > 0:
tdenv.NOTE(
"Placeholder stations are added to the local DB only "
"(not the .CSV).\n"
"Use 'trade.py export --table Station' "
"if you /need/ to persist them."
)
stations = tuple((ID,) for ID in processedStations)
return stations, items, zeros, newItems, updtItems, ignItems, numSys
######################################################################
def processPricesFile(tdenv: TradeEnv, db: sqlite3.Connection, pricesPath: Path, pricesFh: Optional[TextIO] = None, defaultZero: bool = False) -> None:
tdenv.DEBUG0("Processing Prices file '{}'", pricesPath)
with (pricesFh or pricesPath.open('r', encoding='utf-8')) as fh:
stations, items, zeros, newItems, updtItems, ignItems, numSys = processPrices(
tdenv, fh, db, defaultZero
)
if not tdenv.mergeImport:
db.executemany("""
DELETE FROM StationItem
WHERE station_id = ?
""", stations)
if zeros:
db.executemany("""
DELETE FROM StationItem
WHERE station_id = ?
AND item_id = ?
""", zeros)
removedItems = len(zeros)
if items:
for item in items:
try:
db.execute("""
INSERT OR REPLACE INTO StationItem (
station_id, item_id, modified,
demand_price, demand_units, demand_level,
supply_price, supply_units, supply_level
) VALUES (
?, ?, IFNULL(?, CURRENT_TIMESTAMP),
?, ?, ?,
?, ?, ?
)
""", item)
except sqlite3.IntegrityError as e:
print(e)
print(item)
raise e
# db.executemany("""
# INSERT OR REPLACE INTO StationItem (
# station_id, item_id, modified,
# demand_price, demand_units, demand_level,
# supply_price, supply_units, supply_level
# ) VALUES (
# ?, ?, IFNULL(?, CURRENT_TIMESTAMP),
# ?, ?, ?,
# ?, ?, ?
# )
# """, items)
tdenv.DEBUG0("Marking populated stations as having a market")
db.execute(
"UPDATE Station SET market = 'Y'"
" WHERE EXISTS"
" (SELECT station_id FROM StationItem"
" WHERE StationItem.station_id = Station.station_id"
")"
)
tdenv.DEBUG0('Committing...')
db.commit()
db.close()
changes = " and ".join("{} {}".format(v, k) for k, v in {
"new": newItems,
"updated": updtItems,
"removed": removedItems,
}.items() if v) or "0"
tdenv.NOTE(
"Import complete: "
"{:s} items "
"over {:n} stations "
"in {:n} systems",
changes,
len(stations),
numSys,
)
if ignItems:
tdenv.NOTE("Ignored {} items with old data", ignItems)
######################################################################
def depCheck(importPath, lineNo, depType, key, correctKey):
if correctKey == key:
return
if correctKey == corrections.DELETED:
raise DeletedKeyError(importPath, lineNo, depType, key)
raise DeprecatedKeyError(importPath, lineNo, depType, key, correctKey)
def deprecationCheckSystem(importPath, lineNo, line):
depCheck(
importPath, lineNo, 'System',
line[0], corrections.correctSystem(line[0]),
)
def deprecationCheckStation(importPath, lineNo, line):
depCheck(
importPath, lineNo, 'System',
line[0], corrections.correctSystem(line[0]),
)
depCheck(
importPath, lineNo, 'Station',
line[1], corrections.correctStation(line[0], line[1]),
)
def deprecationCheckCategory(importPath, lineNo, line):
depCheck(
importPath, lineNo, 'Category',
line[0], corrections.correctCategory(line[0]),
)
def deprecationCheckItem(importPath, lineNo, line):
depCheck(
importPath, lineNo, 'Category',
line[0], corrections.correctCategory(line[0]),
)
depCheck(
importPath, lineNo, 'Item',
line[1], corrections.correctItem(line[1]),
)
def processImportFile(tdenv, db, importPath, tableName, *, line_callback: Optional[Callable] = None, call_args: Optional[dict] = None):
tdenv.DEBUG0(
"Processing import file '{}' for table '{}'",
str(importPath), tableName
)
call_args = call_args or {}
if line_callback:
line_callback = partial_fn(line_callback, **call_args)
fkeySelectStr = (
"("
" SELECT {newValue}"
" FROM {table}"
" WHERE {stmt}"
")"
)
uniquePfx = "unq:"
uniqueLen = len(uniquePfx)
ignorePfx = "!"
with importPath.open('r', encoding='utf-8') as importFile:
csvin = csv.reader(
importFile, delimiter=',', quotechar="'", doublequote=True
)
# first line must be the column names
columnDefs = next(csvin)
columnCount = len(columnDefs)
# split up columns and values
# this is necessary because the insert might use a foreign key
bindColumns = []
bindValues = []
joinHelper = []
uniqueIndexes = []
for (cIndex, cName) in enumerate(columnDefs):
colName, _, srcKey = cName.partition('@')
# is this a unique index?
if colName.startswith(uniquePfx):
uniqueIndexes.append(cIndex)
colName = colName[uniqueLen:]
if not srcKey:
# no foreign key, straight insert
bindColumns.append(colName)
bindValues.append('?')
continue
queryTab, _, queryCol = srcKey.partition('.')
if colName.startswith(ignorePfx):
# this column is only used to resolve an FK
assert srcKey
colName = colName[len(ignorePfx):]
joinHelper.append((colName, queryTab, queryCol))
continue
# foreign key, we need to make a select
joinTable = [ queryTab ]
joinStmt = []
for nextCol, nextTab, nextJoin in joinHelper:
joinTable.append(
"INNER JOIN {} USING({})".format(nextTab, nextJoin)
)
joinStmt.append(
"{}.{} = ?".format(nextTab, nextCol)
)
joinHelper = []
joinStmt.append("{}.{} = ?".format(queryTab, colName))
bindColumns.append(queryCol)
bindValues.append(
fkeySelectStr.format(
newValue = srcKey,
table = " ".join(joinTable),
stmt = " AND ".join(joinStmt),
)
)
# now we can make the sql statement
sql_stmt = """
INSERT OR REPLACE INTO {table} ({columns}) VALUES({values})
""".format(
table=tableName,
columns=','.join(bindColumns),
values=','.join(bindValues)
)
tdenv.DEBUG0("SQL-Statement: {}", sql_stmt)
# Check if there is a deprecation check for this table.
deprecationFn = getattr(
sys.modules[__name__],
"deprecationCheck" + tableName,
None
)
# import the data
importCount = 0
uniqueIndex = {}
for linein in csvin:
if line_callback:
line_callback()
if not linein:
continue
lineNo = csvin.line_num
if len(linein) == columnCount:
tdenv.DEBUG1(" Values: {}", ', '.join(linein))
if deprecationFn:
try:
deprecationFn(importPath, lineNo, linein)
except (DeprecatedKeyError, DeletedKeyError) as e:
if not tdenv.ignoreUnknown:
raise e
e.category = "WARNING"
tdenv.NOTE("{}", e)
continue
if uniqueIndexes:
# Need to construct the actual unique index key as
# something less likely to collide with manmade
# values when it's a compound.
keyValues = [
str(linein[col]).upper()
for col in uniqueIndexes
]
key = ":!:".join(keyValues)
prevLineNo = uniqueIndex.get(key, 0)
if prevLineNo:
# Make a human-readable key
key = "/".join(keyValues)
raise DuplicateKeyError(
importPath, lineNo,
"entry", key,
prevLineNo
)
uniqueIndex[key] = lineNo
try:
db.execute(sql_stmt, linein)
importCount += 1
except Exception as e: # pylint: disable=broad-exception-caught
tdenv.WARN(
"*** INTERNAL ERROR: {err}\n"
"CSV File: {file}:{line}\n"
"SQL Query: {query}\n"
"Params: {params}\n"
.format(
err = str(e),
file = str(importPath),
line = lineNo,
query = sql_stmt.strip(),
params = linein
)
)
pass
else:
tdenv.NOTE(
"Wrong number of columns ({}:{}): {}",
importPath,
lineNo,
', '.join(linein)
)
db.commit()
tdenv.DEBUG0("{count} {table}s imported",
count = importCount,
table = tableName)
######################################################################
def buildCache(tdb, tdenv):
"""
Rebuilds the SQlite database from source files.
TD's data is either "stable" - information that rarely changes like Ship
details, star systems etc - and "volatile" - pricing information, etc.
The stable data starts out in data/TradeDangerous.sql while other data
is stored in custom-formatted text files, e.g. ./TradeDangerous.prices.
We load both sets of data into an SQLite database, after which we can
avoid the text-processing overhead by simply checking if the text files
are newer than the database.
"""
tdenv.NOTE(
"Rebuilding cache file: this may take a few moments.",
stderr=True,
)
dbPath = tdb.dbPath
sqlPath = tdb.sqlPath
pricesPath = tdb.pricesPath
# Create an in-memory database to populate with our data.
tempPath = dbPath.with_suffix(".new")
backupPath = dbPath.with_suffix(".old")
if tempPath.exists():
tempPath.unlink()
tempDB = sqlite3.connect(str(tempPath))
tempDB.execute("PRAGMA foreign_keys=ON")
# Read the SQL script so we are ready to populate structure, etc.
tdenv.DEBUG0("Executing SQL Script '{}' from '{}'", sqlPath, os.getcwd())
with sqlPath.open('r', encoding = 'utf-8') as sqlFile:
sqlScript = sqlFile.read()
tempDB.executescript(sqlScript)
# import standard tables
with Progress(max_value=len(tdb.importTables) + 1, prefix="Importing", width=25, style=CountingBar) as prog:
for importName, importTable in tdb.importTables:
import_path = Path(importName)
import_lines = file_line_count(import_path, missing_ok=True)
with prog.sub_task(max_value=import_lines, description=importTable) as child:
prog.increment(value=1)
call_args = {'task': child, 'advance': 1}
try:
processImportFile(tdenv, tempDB, import_path, importTable, line_callback=prog.update_task, call_args=call_args)
except FileNotFoundError:
tdenv.DEBUG0(
"WARNING: processImportFile found no {} file", importName
)