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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
|
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program 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 2 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "DB2FileLoader.h"
#include "ByteConverter.h"
#include "DB2Meta.h"
#include "Errors.h"
#include "Log.h"
#include <limits>
#include <sstream>
#include <system_error>
#include <cstring>
enum class DB2ColumnCompression : uint32
{
None,
Immediate,
CommonData,
Pallet,
PalletArray,
SignedImmediate
};
#pragma pack(push, 1)
struct DB2FieldEntry
{
int16 UnusedBits;
uint16 Offset;
};
struct DB2CatalogEntry
{
uint32 FileOffset;
uint16 RecordSize;
};
struct DB2ColumnMeta
{
uint16 BitOffset;
uint16 BitSize;
uint32 AdditionalDataSize;
DB2ColumnCompression CompressionType;
union
{
struct
{
uint32 BitOffset;
uint32 BitWidth;
bool Signed;
} immediate;
struct
{
uint32 Value;
} commonData;
struct
{
uint32 BitOffset;
uint32 BitWidth;
uint32 ArraySize;
} pallet;
} CompressionData;
};
struct DB2CommonValue
{
uint32 RecordId;
uint32 Value;
};
struct DB2PalletValue
{
uint32 Value;
};
struct DB2IndexDataInfo
{
uint32 NumEntries;
uint32 MinId;
uint32 MaxId;
};
struct DB2IndexEntry
{
uint32 ParentId;
uint32 RecordIndex;
};
#pragma pack(pop)
struct DB2IndexData
{
std::vector<DB2IndexEntry> Entries;
};
uint32 DB2FileLoadInfo::GetStringFieldCount(bool localizedOnly) const
{
uint32 stringFields = 0;
for (std::size_t i = 0; i < FieldCount; ++i)
if (Fields[i].Type == FT_STRING || (Fields[i].Type == FT_STRING_NOT_LOCALIZED && !localizedOnly))
++stringFields;
return stringFields;
}
std::pair<int32, int32> DB2FileLoadInfo::GetFieldIndexByName(char const* fieldName) const
{
std::size_t ourIndex = Meta->HasIndexFieldInData() ? 0 : 1;
for (uint32 i = 0; i < Meta->FieldCount; ++i)
{
for (uint8 arr = 0; arr < Meta->Fields[i].ArraySize; ++arr)
{
if (!strcmp(Fields[ourIndex].Name, fieldName))
return std::make_pair(int32(i), int32(arr));
++ourIndex;
}
}
return std::make_pair(-1, -1);
}
int32 DB2FileLoadInfo::GetFieldIndexByMetaIndex(uint32 metaIndex) const
{
ASSERT(metaIndex < Meta->FieldCount);
int32 ourIndex = Meta->HasIndexFieldInData() ? 0 : 1;
for (uint32 i = 0; i < metaIndex; ++i)
ourIndex += Meta->Fields[i].ArraySize;
return ourIndex;
}
DB2FileSource::~DB2FileSource()
{
}
class DB2FileLoaderImpl
{
public:
virtual ~DB2FileLoaderImpl() { }
virtual void LoadColumnData(std::unique_ptr<DB2SectionHeader[]> sections, std::unique_ptr<DB2FieldEntry[]> fields, std::unique_ptr<DB2ColumnMeta[]> columnMeta,
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletValues, std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletArrayValues,
std::unique_ptr<std::unordered_map<uint32, uint32>[]> commonValues) = 0;
virtual void SkipEncryptedSection(uint32 section) = 0;
virtual bool LoadTableData(DB2FileSource* source, uint32 section) = 0;
virtual bool LoadCatalogData(DB2FileSource* source, uint32 section) = 0;
virtual void SetAdditionalData(std::vector<uint32> idTable, std::vector<DB2RecordCopy> copyTable, std::vector<std::vector<DB2IndexData>> parentIndexes) = 0;
virtual char* AutoProduceData(uint32& indexTableSize, char**& indexTable) = 0;
virtual char* AutoProduceStrings(char** indexTable, uint32 indexTableSize, uint32 locale) = 0;
virtual void AutoProduceRecordCopies(uint32 records, char** indexTable, char* dataTable) = 0;
virtual DB2Record GetRecord(uint32 recordNumber) const = 0;
virtual DB2RecordCopy GetRecordCopy(uint32 copyNumber) const = 0;
virtual uint32 GetRecordCount() const = 0;
virtual uint32 GetRecordCopyCount() const = 0;
virtual uint32 GetMaxId() const = 0;
virtual DB2FileLoadInfo const* GetLoadInfo() const = 0;
virtual DB2SectionHeader& GetSection(uint32 section) const = 0;
virtual bool IsSignedField(uint32 field) const = 0;
virtual char const* GetExpectedSignMismatchReason(uint32 field) const = 0;
private:
friend class DB2Record;
virtual unsigned char const* GetRawRecordData(uint32 recordNumber, uint32 const* section) const = 0;
virtual uint32 RecordGetId(uint8 const* record, uint32 recordIndex) const = 0;
virtual uint8 RecordGetUInt8(uint8 const* record, uint32 field, uint32 arrayIndex) const = 0;
virtual uint16 RecordGetUInt16(uint8 const* record, uint32 field, uint32 arrayIndex) const = 0;
virtual uint32 RecordGetUInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const = 0;
virtual int32 RecordGetInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const = 0;
virtual uint64 RecordGetUInt64(uint8 const* record, uint32 field, uint32 arrayIndex) const = 0;
virtual float RecordGetFloat(uint8 const* record, uint32 field, uint32 arrayIndex) const = 0;
virtual char const* RecordGetString(uint8 const* record, uint32 field, uint32 arrayIndex) const = 0;
virtual std::size_t* RecordCreateDetachedFieldOffsets(std::size_t* oldOffsets) const = 0;
virtual void RecordDestroyFieldOffsets(std::size_t*& fieldOffsets) const = 0;
};
class DB2FileLoaderRegularImpl final : public DB2FileLoaderImpl
{
public:
DB2FileLoaderRegularImpl(char const* fileName, DB2FileLoadInfo const* loadInfo, DB2Header const* header);
~DB2FileLoaderRegularImpl();
void LoadColumnData(std::unique_ptr<DB2SectionHeader[]> sections, std::unique_ptr<DB2FieldEntry[]> fields, std::unique_ptr<DB2ColumnMeta[]> columnMeta,
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletValues, std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletArrayValues,
std::unique_ptr<std::unordered_map<uint32, uint32>[]> commonValues) override;
void SkipEncryptedSection(uint32 /*section*/) override { }
bool LoadTableData(DB2FileSource* source, uint32 section) override;
bool LoadCatalogData(DB2FileSource* /*source*/, uint32 /*section*/) override { return true; }
void SetAdditionalData(std::vector<uint32> idTable, std::vector<DB2RecordCopy> copyTable, std::vector<std::vector<DB2IndexData>> parentIndexes) override;
char* AutoProduceData(uint32& indexTableSize, char**& indexTable) override;
char* AutoProduceStrings(char** indexTable, uint32 indexTableSize, uint32 locale) override;
void AutoProduceRecordCopies(uint32 records, char** indexTable, char* dataTable) override;
DB2Record GetRecord(uint32 recordNumber) const override;
DB2RecordCopy GetRecordCopy(uint32 copyNumber) const override;
uint32 GetRecordCount() const override;
uint32 GetRecordCopyCount() const override;
uint32 GetMaxId() const override;
DB2FileLoadInfo const* GetLoadInfo() const override;
DB2SectionHeader& GetSection(uint32 section) const override;
bool IsSignedField(uint32 field) const override;
char const* GetExpectedSignMismatchReason(uint32 field) const override;
private:
void FillParentLookup(char* dataTable);
uint32 GetRecordSection(uint32 recordNumber) const;
unsigned char const* GetRawRecordData(uint32 recordNumber, uint32 const* section) const override;
uint32 RecordGetId(uint8 const* record, uint32 recordIndex) const override;
uint8 RecordGetUInt8(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
uint16 RecordGetUInt16(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
uint32 RecordGetUInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
int32 RecordGetInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
uint64 RecordGetUInt64(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
float RecordGetFloat(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
char const* RecordGetString(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
template<typename T>
T RecordGetVarInt(uint8 const* record, uint32 field, uint32 arrayIndex) const;
uint64 RecordGetPackedValue(uint8 const* packedRecordData, uint32 bitWidth, uint32 bitOffset) const;
uint16 GetFieldOffset(uint32 field) const;
std::size_t* RecordCreateDetachedFieldOffsets(std::size_t* oldOffsets) const override;
void RecordDestroyFieldOffsets(std::size_t*& fieldOffsets) const override;
char const* _fileName;
DB2FileLoadInfo const* _loadInfo;
DB2Header const* _header;
std::unique_ptr<uint8[]> _data;
uint8* _stringTable;
std::unique_ptr<DB2SectionHeader[]> _sections;
std::unique_ptr<DB2ColumnMeta[]> _columnMeta;
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> _palletValues;
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> _palletArrayValues;
std::unique_ptr<std::unordered_map<uint32, uint32>[]> _commonValues;
std::vector<uint32> _idTable;
std::vector<DB2RecordCopy> _copyTable;
std::vector<std::vector<DB2IndexData>> _parentIndexes;
};
class DB2FileLoaderSparseImpl final : public DB2FileLoaderImpl
{
public:
DB2FileLoaderSparseImpl(char const* fileName, DB2FileLoadInfo const* loadInfo, DB2Header const* header, DB2FileSource* source);
~DB2FileLoaderSparseImpl();
void LoadColumnData(std::unique_ptr<DB2SectionHeader[]> sections, std::unique_ptr<DB2FieldEntry[]> fields, std::unique_ptr<DB2ColumnMeta[]> columnMeta,
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletValues, std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletArrayValues,
std::unique_ptr<std::unordered_map<uint32, uint32>[]> commonValues) override;
void SkipEncryptedSection(uint32 section) override;
bool LoadTableData(DB2FileSource* /*source*/, uint32 /*section*/) override { return true; }
bool LoadCatalogData(DB2FileSource* source, uint32 section) override;
void SetAdditionalData(std::vector<uint32> idTable, std::vector<DB2RecordCopy> copyTable, std::vector<std::vector<DB2IndexData>> parentIndexes) override;
char* AutoProduceData(uint32& indexTableSize, char**& indexTable) override;
char* AutoProduceStrings(char** indexTable, uint32 indexTableSize, uint32 locale) override;
void AutoProduceRecordCopies(uint32 records, char** indexTable, char* dataTable) override;
DB2Record GetRecord(uint32 recordNumber) const override;
DB2RecordCopy GetRecordCopy(uint32 copyNumber) const override;
uint32 GetRecordCount() const override;
uint32 GetRecordCopyCount() const override;
uint32 GetMaxId() const override;
DB2FileLoadInfo const* GetLoadInfo() const override;
DB2SectionHeader& GetSection(uint32 section) const override;
bool IsSignedField(uint32 field) const override;
char const* GetExpectedSignMismatchReason(uint32 field) const override;
private:
void FillParentLookup(char* dataTable);
uint32 GetRecordSection(uint32 recordNumber) const;
unsigned char const* GetRawRecordData(uint32 recordNumber, uint32 const* section) const override;
uint32 RecordGetId(uint8 const* record, uint32 recordIndex) const override;
uint8 RecordGetUInt8(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
uint16 RecordGetUInt16(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
uint32 RecordGetUInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
int32 RecordGetInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
uint64 RecordGetUInt64(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
float RecordGetFloat(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
char const* RecordGetString(uint8 const* record, uint32 field, uint32 arrayIndex) const override;
uint32 RecordGetVarInt(uint8 const* record, uint32 field, uint32 arrayIndex, bool isSigned) const;
uint16 GetFieldOffset(uint32 field, uint32 arrayIndex) const;
uint16 GetFieldSize(uint32 field) const;
std::size_t* RecordCreateDetachedFieldOffsets(std::size_t* oldOffsets) const override;
void RecordDestroyFieldOffsets(std::size_t*& fieldOffsets) const override;
void CalculateAndStoreFieldOffsets(uint8 const* rawRecord) const;
#pragma pack(push, 1)
#pragma pack(pop)
char const* _fileName;
DB2FileLoadInfo const* _loadInfo;
DB2Header const* _header;
DB2FileSource* const _source;
std::size_t _totalRecordSize;
uint16 _maxRecordSize;
std::unique_ptr<uint8[]> _recordBuffer;
std::unique_ptr<DB2SectionHeader[]> _sections;
std::unique_ptr<DB2FieldEntry[]> _fields;
std::unique_ptr<std::size_t[]> _fieldAndArrayOffsets;
std::vector<uint32> _catalogIds;
std::vector<DB2CatalogEntry> _catalog;
std::vector<DB2RecordCopy> _copyTable;
std::vector<std::vector<DB2IndexData>> _parentIndexes;
};
DB2FileLoaderRegularImpl::DB2FileLoaderRegularImpl(char const* fileName, DB2FileLoadInfo const* loadInfo, DB2Header const* header) :
_fileName(fileName),
_loadInfo(loadInfo),
_header(header),
_stringTable(nullptr)
{
}
void DB2FileLoaderRegularImpl::LoadColumnData(std::unique_ptr<DB2SectionHeader[]> sections, std::unique_ptr<DB2FieldEntry[]> /*fields*/, std::unique_ptr<DB2ColumnMeta[]> columnMeta,
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletValues, std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletArrayValues,
std::unique_ptr<std::unordered_map<uint32, uint32>[]> commonValues)
{
_sections = std::move(sections);
_columnMeta = std::move(columnMeta);
_palletValues = std::move(palletValues);
_palletArrayValues = std::move(palletArrayValues);
_commonValues = std::move(commonValues);
}
bool DB2FileLoaderRegularImpl::LoadTableData(DB2FileSource* source, uint32 section)
{
if (!_data)
{
_data = std::make_unique<uint8[]>(_header->RecordSize * _header->RecordCount + _header->StringTableSize + 8);
_stringTable = &_data[_header->RecordSize * _header->RecordCount];
}
uint32 sectionDataStart = 0;
uint32 sectionStringTableStart = 0;
for (uint32 i = 0; i < section; ++i)
{
sectionDataStart += _header->RecordSize * _sections[i].RecordCount;
sectionStringTableStart += _sections[i].StringTableSize;
}
if (_sections[section].RecordCount && !source->Read(&_data[sectionDataStart], _header->RecordSize * _sections[section].RecordCount))
return false;
if (_sections[section].StringTableSize && !source->Read(&_stringTable[sectionStringTableStart], _sections[section].StringTableSize))
return false;
return true;
}
void DB2FileLoaderRegularImpl::SetAdditionalData(std::vector<uint32> idTable, std::vector<DB2RecordCopy> copyTable, std::vector<std::vector<DB2IndexData>> parentIndexes)
{
_idTable = std::move(idTable);
_copyTable = std::move(copyTable);
_parentIndexes = std::move(parentIndexes);
}
DB2FileLoaderRegularImpl::~DB2FileLoaderRegularImpl()
{
}
static char const* const nullStr = "";
char* DB2FileLoaderRegularImpl::AutoProduceData(uint32& indexTableSize, char**& indexTable)
{
//get struct size and index pos
uint32 recordsize = _loadInfo->Meta->GetRecordSize();
uint32 maxi = GetMaxId() + 1;
using index_entry_t = char*;
indexTableSize = maxi;
indexTable = new index_entry_t[maxi];
memset(indexTable, 0, maxi * sizeof(index_entry_t));
char* dataTable = new char[(_header->RecordCount + _copyTable.size()) * recordsize];
uint32 offset = 0;
uint32 recordIndex = 0;
for (uint32 section = 0; section < _header->SectionCount; ++section)
{
DB2SectionHeader const& sectionHeader = GetSection(section);
if (sectionHeader.TactId)
{
offset += recordsize * sectionHeader.RecordCount;
recordIndex += sectionHeader.RecordCount;
continue;
}
for (uint32 sr = 0; sr < sectionHeader.RecordCount; ++sr, ++recordIndex)
{
unsigned char const* rawRecord = GetRawRecordData(recordIndex, §ion);
if (!rawRecord)
continue;
uint32 indexVal = RecordGetId(rawRecord, recordIndex);
indexTable[indexVal] = &dataTable[offset];
uint32 fieldIndex = 0;
if (!_loadInfo->Meta->HasIndexFieldInData())
{
*((uint32*)(&dataTable[offset])) = indexVal;
offset += 4;
++fieldIndex;
}
for (uint32 x = 0; x < _header->FieldCount; ++x)
{
for (uint32 z = 0; z < _loadInfo->Meta->Fields[x].ArraySize; ++z)
{
switch (_loadInfo->Fields[fieldIndex].Type)
{
case FT_FLOAT:
*((float*)(&dataTable[offset])) = RecordGetFloat(rawRecord, x, z);
offset += 4;
break;
case FT_INT:
*((uint32*)(&dataTable[offset])) = RecordGetVarInt<uint32>(rawRecord, x, z);
offset += 4;
break;
case FT_BYTE:
*((uint8*)(&dataTable[offset])) = RecordGetUInt8(rawRecord, x, z);
offset += 1;
break;
case FT_SHORT:
*((uint16*)(&dataTable[offset])) = RecordGetUInt16(rawRecord, x, z);
offset += 2;
break;
case FT_LONG:
*((uint64*)(&dataTable[offset])) = RecordGetUInt64(rawRecord, x, z);
offset += 8;
break;
case FT_STRING:
for (char const*& localeStr : ((LocalizedString*)(&dataTable[offset]))->Str)
localeStr = nullStr;
offset += sizeof(LocalizedString);
break;
case FT_STRING_NOT_LOCALIZED:
*(char const**)(&dataTable[offset]) = nullStr;
offset += sizeof(char*);
break;
default:
ABORT_MSG("Unknown format character '%c' found in %s meta for field %s",
_loadInfo->Fields[fieldIndex].Type, _fileName, _loadInfo->Fields[fieldIndex].Name);
break;
}
++fieldIndex;
}
}
for (uint32 x = _header->FieldCount; x < _loadInfo->Meta->FieldCount; ++x)
{
for (uint32 z = 0; z < _loadInfo->Meta->Fields[x].ArraySize; ++z)
{
switch (_loadInfo->Fields[fieldIndex].Type)
{
case FT_INT:
*((uint32*)(&dataTable[offset])) = 0;
offset += 4;
break;
case FT_BYTE:
*((uint8*)(&dataTable[offset])) = 0;
offset += 1;
break;
case FT_SHORT:
*((uint16*)(&dataTable[offset])) = 0;
offset += 2;
break;
default:
ABORT_MSG("Unknown format character '%c' found in %s meta for parent field %s",
_loadInfo->Fields[fieldIndex].Type, _fileName, _loadInfo->Fields[fieldIndex].Name);
break;
}
++fieldIndex;
}
}
}
}
if (!_parentIndexes.empty())
FillParentLookup(dataTable);
return dataTable;
}
char* DB2FileLoaderRegularImpl::AutoProduceStrings(char** indexTable, uint32 indexTableSize, uint32 locale)
{
if (!(_header->Locale & (1 << locale)))
{
char const* sep = "";
std::ostringstream str;
for (uint32 i = 0; i < TOTAL_LOCALES; ++i)
{
if (_header->Locale & (1 << i))
{
str << sep << localeNames[i];
sep = ", ";
}
}
TC_LOG_ERROR("", "Attempted to load {} which has locales {} as {}. Check if you placed your localized db2 files in correct directory.", _fileName, str.str(), localeNames[locale]);
return nullptr;
}
if (!_loadInfo->GetStringFieldCount(false))
return nullptr;
char* stringPool = new char[_header->StringTableSize];
memcpy(stringPool, _stringTable, _header->StringTableSize);
uint32 y = 0;
for (uint32 section = 0; section < _header->SectionCount; ++section)
{
DB2SectionHeader const& sectionHeader = GetSection(section);
if (sectionHeader.TactId)
{
y += sectionHeader.RecordCount;
continue;
}
for (uint32 sr = 0; sr < sectionHeader.RecordCount; ++sr, ++y)
{
unsigned char const* rawRecord = GetRawRecordData(y, §ion);
if (!rawRecord)
continue;
uint32 indexVal = RecordGetId(rawRecord, y);
if (indexVal >= indexTableSize)
continue;
char* recordData = indexTable[indexVal];
if (!recordData)
continue;
uint32 offset = 0;
uint32 fieldIndex = 0;
if (!_loadInfo->Meta->HasIndexFieldInData())
{
offset += 4;
++fieldIndex;
}
for (uint32 x = 0; x < _loadInfo->Meta->FieldCount; ++x)
{
for (uint32 z = 0; z < _loadInfo->Meta->Fields[x].ArraySize; ++z)
{
switch (_loadInfo->Fields[fieldIndex].Type)
{
case FT_FLOAT:
case FT_INT:
offset += 4;
break;
case FT_BYTE:
offset += 1;
break;
case FT_SHORT:
offset += 2;
break;
case FT_LONG:
offset += 8;
break;
case FT_STRING:
{
char const* string = RecordGetString(rawRecord, x, z);
if (string >= reinterpret_cast<char const*>(_stringTable)) // ensure string is inside _stringTable
reinterpret_cast<LocalizedString*>(&recordData[offset])->Str[locale] = stringPool + (string - reinterpret_cast<char const*>(_stringTable));
offset += sizeof(LocalizedString);
break;
}
case FT_STRING_NOT_LOCALIZED:
{
char const* string = RecordGetString(rawRecord, x, z);
if (string >= reinterpret_cast<char const*>(_stringTable)) // ensure string is inside _stringTable
*reinterpret_cast<char**>(&recordData[offset]) = stringPool + (string - reinterpret_cast<char const*>(_stringTable));
offset += sizeof(char*);
break;
}
default:
ABORT_MSG("Unknown format character '%c' found in %s meta for field %s",
_loadInfo->Fields[fieldIndex].Type, _fileName, _loadInfo->Fields[fieldIndex].Name);
break;
}
++fieldIndex;
}
}
}
}
return stringPool;
}
void DB2FileLoaderRegularImpl::AutoProduceRecordCopies(uint32 records, char** indexTable, char* dataTable)
{
uint32 recordCopies = GetRecordCopyCount();
if (!recordCopies)
return;
uint32 recordsize = _loadInfo->Meta->GetRecordSize();
uint32 offset = _header->RecordCount * recordsize;
uint32 idFieldOffset = _loadInfo->Meta->HasIndexFieldInData() ? GetFieldOffset(_loadInfo->Meta->GetIndexField()) : 0;
for (uint32 c = 0; c < recordCopies; ++c)
{
DB2RecordCopy copy = GetRecordCopy(c);
if (copy.SourceRowId && copy.SourceRowId < records && copy.NewRowId < records && indexTable[copy.SourceRowId])
{
indexTable[copy.NewRowId] = &dataTable[offset];
memcpy(indexTable[copy.NewRowId], indexTable[copy.SourceRowId], recordsize);
*((uint32*)(&dataTable[offset + idFieldOffset])) = copy.NewRowId;
offset += recordsize;
}
}
}
void DB2FileLoaderRegularImpl::FillParentLookup(char* dataTable)
{
int32 parentIdOffset = _loadInfo->Meta->GetParentIndexFieldOffset();
uint32 recordSize = _loadInfo->Meta->GetRecordSize();
uint32 recordIndexOffset = 0;
for (uint32 i = 0; i < _header->SectionCount; ++i)
{
DB2SectionHeader const& section = GetSection(i);
if (!section.TactId)
{
for (std::size_t j = 0; j < _parentIndexes[i][0].Entries.size(); ++j)
{
uint32 parentId = _parentIndexes[i][0].Entries[j].ParentId;
char* recordData = &dataTable[(_parentIndexes[i][0].Entries[j].RecordIndex + recordIndexOffset) * recordSize];
switch (_loadInfo->Meta->Fields[_loadInfo->Meta->ParentIndexField].Type)
{
case FT_SHORT:
{
if (_loadInfo->Meta->ParentIndexField >= int32(_loadInfo->Meta->FileFieldCount))
{
// extra field at the end
*reinterpret_cast<uint32*>(&recordData[parentIdOffset]) = parentId;
}
else
{
// in data block, must fit
ASSERT(parentId <= std::numeric_limits<uint16>::max(), "ParentId value %u does not fit into uint16 field (%s in %s)",
parentId, _loadInfo->Fields[_loadInfo->GetFieldIndexByMetaIndex(_loadInfo->Meta->ParentIndexField)].Name, _fileName);
*reinterpret_cast<uint16*>(&recordData[parentIdOffset]) = parentId;
}
break;
}
case FT_BYTE:
{
if (_loadInfo->Meta->ParentIndexField >= int32(_loadInfo->Meta->FileFieldCount))
{
// extra field at the end
*reinterpret_cast<uint32*>(&recordData[parentIdOffset]) = parentId;
}
else
{
// in data block, must fit
ASSERT(parentId <= std::numeric_limits<uint8>::max(), "ParentId value %u does not fit into uint8 field (%s in %s)",
parentId, _loadInfo->Fields[_loadInfo->GetFieldIndexByMetaIndex(_loadInfo->Meta->ParentIndexField)].Name, _fileName);
*reinterpret_cast<uint8*>(&recordData[parentIdOffset]) = parentId;
}
break;
}
case FT_INT:
*reinterpret_cast<uint32*>(&recordData[parentIdOffset]) = parentId;
break;
default:
ABORT_MSG("Unhandled parent id type '%c' found in %s", _loadInfo->Meta->Fields[_loadInfo->Meta->ParentIndexField].Type, _fileName);
break;
}
}
}
recordIndexOffset += section.RecordCount;
}
}
DB2Record DB2FileLoaderRegularImpl::GetRecord(uint32 recordNumber) const
{
return DB2Record(*this, recordNumber, nullptr);
}
DB2RecordCopy DB2FileLoaderRegularImpl::GetRecordCopy(uint32 copyNumber) const
{
if (copyNumber >= GetRecordCopyCount())
return DB2RecordCopy{};
return _copyTable[copyNumber];
}
uint32 DB2FileLoaderRegularImpl::GetRecordCount() const
{
return _header->RecordCount;
}
uint32 DB2FileLoaderRegularImpl::GetRecordCopyCount() const
{
return _copyTable.size();
}
uint32 DB2FileLoaderRegularImpl::GetRecordSection(uint32 recordNumber) const
{
uint32 section = 0;
for (; section < _header->SectionCount; ++section)
{
DB2SectionHeader const& sectionHeader = GetSection(section);
if (recordNumber < sectionHeader.RecordCount)
break;
recordNumber -= sectionHeader.RecordCount;
}
return section;
}
unsigned char const* DB2FileLoaderRegularImpl::GetRawRecordData(uint32 recordNumber, uint32 const* section) const
{
if (recordNumber >= _header->RecordCount)
return nullptr;
if (GetSection(section ? *section : GetRecordSection(recordNumber)).TactId)
return nullptr;
return &_data[recordNumber * _header->RecordSize];
}
uint32 DB2FileLoaderRegularImpl::RecordGetId(uint8 const* record, uint32 recordIndex) const
{
if (_loadInfo->Meta->HasIndexFieldInData())
return RecordGetVarInt<uint32>(record, _loadInfo->Meta->GetIndexField(), 0);
return _idTable[recordIndex];
}
uint8 DB2FileLoaderRegularImpl::RecordGetUInt8(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
return RecordGetVarInt<uint8>(record, field, arrayIndex);
}
uint16 DB2FileLoaderRegularImpl::RecordGetUInt16(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
return RecordGetVarInt<uint16>(record, field, arrayIndex);
}
uint32 DB2FileLoaderRegularImpl::RecordGetUInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
return RecordGetVarInt<uint32>(record, field, arrayIndex);
}
int32 DB2FileLoaderRegularImpl::RecordGetInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
return RecordGetVarInt<int32>(record, field, arrayIndex);
}
uint64 DB2FileLoaderRegularImpl::RecordGetUInt64(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
return RecordGetVarInt<uint64>(record, field, arrayIndex);
}
float DB2FileLoaderRegularImpl::RecordGetFloat(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
return RecordGetVarInt<float>(record, field, arrayIndex);
}
char const* DB2FileLoaderRegularImpl::RecordGetString(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
uint32 fieldOffset = GetFieldOffset(field) + sizeof(uint32) * arrayIndex;
uint32 stringOffset = RecordGetVarInt<uint32>(record, field, arrayIndex);
ASSERT(stringOffset < _header->RecordSize * _header->RecordCount + _header->StringTableSize);
return reinterpret_cast<char const*>(record + fieldOffset + stringOffset);
}
template<typename T>
T DB2FileLoaderRegularImpl::RecordGetVarInt(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
ASSERT(field < _header->FieldCount);
DB2ColumnCompression compressionType = _columnMeta ? _columnMeta[field].CompressionType : DB2ColumnCompression::None;
switch (compressionType)
{
case DB2ColumnCompression::None:
{
T val = *reinterpret_cast<T const*>(record + GetFieldOffset(field) + sizeof(T) * arrayIndex);
EndianConvert(val);
return val;
}
case DB2ColumnCompression::Immediate:
{
ASSERT(arrayIndex == 0);
uint64 immediateValue = RecordGetPackedValue(record + GetFieldOffset(field),
_columnMeta[field].CompressionData.immediate.BitWidth, _columnMeta[field].CompressionData.immediate.BitOffset);
EndianConvert(immediateValue);
T value;
memcpy(&value, &immediateValue, std::min(sizeof(T), sizeof(immediateValue)));
return value;
}
case DB2ColumnCompression::CommonData:
{
uint32 id = RecordGetId(record, (_data.get() - record) / _header->RecordSize);
T value;
auto valueItr = _commonValues[field].find(id);
if (valueItr != _commonValues[field].end())
memcpy(&value, &valueItr->second, std::min(sizeof(T), sizeof(uint32)));
else
memcpy(&value, &_columnMeta[field].CompressionData.commonData.Value, std::min(sizeof(T), sizeof(uint32)));
return value;
}
case DB2ColumnCompression::Pallet:
{
ASSERT(arrayIndex == 0);
uint64 palletIndex = RecordGetPackedValue(record + GetFieldOffset(field),
_columnMeta[field].CompressionData.pallet.BitWidth, _columnMeta[field].CompressionData.pallet.BitOffset);
EndianConvert(palletIndex);
uint32 palletValue = _palletValues[field][palletIndex].Value;
EndianConvert(palletValue);
T value;
memcpy(&value, &palletValue, std::min(sizeof(T), sizeof(palletValue)));
return value;
}
case DB2ColumnCompression::PalletArray:
{
uint64 palletIndex = RecordGetPackedValue(record + GetFieldOffset(field),
_columnMeta[field].CompressionData.pallet.BitWidth, _columnMeta[field].CompressionData.pallet.BitOffset);
EndianConvert(palletIndex);
uint32 palletValue = _palletArrayValues[field][palletIndex * _columnMeta[field].CompressionData.pallet.ArraySize + arrayIndex].Value;
EndianConvert(palletValue);
T value;
memcpy(&value, &palletValue, std::min(sizeof(T), sizeof(palletValue)));
return value;
}
case DB2ColumnCompression::SignedImmediate:
{
ASSERT(arrayIndex == 0);
uint64 immediateValue = RecordGetPackedValue(record + GetFieldOffset(field),
_columnMeta[field].CompressionData.immediate.BitWidth, _columnMeta[field].CompressionData.immediate.BitOffset);
EndianConvert(immediateValue);
uint64 mask = UI64LIT(1) << (_columnMeta[field].CompressionData.immediate.BitWidth - 1);
immediateValue = (immediateValue ^ mask) - mask;
T value;
memcpy(&value, &immediateValue, std::min(sizeof(T), sizeof(immediateValue)));
return value;
}
default:
ABORT_MSG("Unhandled compression type %u in %s", uint32(_columnMeta[field].CompressionType), _fileName);
break;
}
return 0;
}
uint64 DB2FileLoaderRegularImpl::RecordGetPackedValue(uint8 const* packedRecordData, uint32 bitWidth, uint32 bitOffset) const
{
uint32 bitsToRead = bitOffset & 7;
return *reinterpret_cast<uint64 const*>(packedRecordData) << (64 - bitsToRead - bitWidth) >> (64 - bitWidth);
}
uint16 DB2FileLoaderRegularImpl::GetFieldOffset(uint32 field) const
{
ASSERT(field < _header->FieldCount);
DB2ColumnCompression compressionType = _columnMeta ? _columnMeta[field].CompressionType : DB2ColumnCompression::None;
switch (compressionType)
{
case DB2ColumnCompression::None:
return _columnMeta[field].BitOffset / 8;
case DB2ColumnCompression::Immediate:
case DB2ColumnCompression::SignedImmediate:
return _columnMeta[field].CompressionData.immediate.BitOffset / 8 + _header->PackedDataOffset;
case DB2ColumnCompression::CommonData:
return 0xFFFF;
case DB2ColumnCompression::Pallet:
case DB2ColumnCompression::PalletArray:
return _columnMeta[field].CompressionData.pallet.BitOffset / 8 + _header->PackedDataOffset;
default:
ABORT_MSG("Unhandled compression type %u in %s", uint32(_columnMeta[field].CompressionType), _fileName);
break;
}
return 0;
}
std::size_t* DB2FileLoaderRegularImpl::RecordCreateDetachedFieldOffsets(std::size_t* /*oldOffsets*/) const
{
return nullptr;
}
void DB2FileLoaderRegularImpl::RecordDestroyFieldOffsets(std::size_t*& /*fieldOffsets*/) const
{
}
uint32 DB2FileLoaderRegularImpl::GetMaxId() const
{
uint32 maxId = 0;
for (uint32 row = 0; row < _header->RecordCount; ++row)
{
unsigned char const* rawRecord = GetRawRecordData(row, nullptr);
if (!rawRecord)
continue;
uint32 id = RecordGetId(rawRecord, row);
if (id > maxId)
maxId = id;
}
for (uint32 copy = 0; copy < GetRecordCopyCount(); ++copy)
{
uint32 id = GetRecordCopy(copy).NewRowId;
if (id > maxId)
maxId = id;
}
ASSERT(maxId <= _header->MaxId);
return maxId;
}
DB2FileLoadInfo const* DB2FileLoaderRegularImpl::GetLoadInfo() const
{
return _loadInfo;
}
DB2SectionHeader& DB2FileLoaderRegularImpl::GetSection(uint32 section) const
{
return _sections[section];
}
bool DB2FileLoaderRegularImpl::IsSignedField(uint32 field) const
{
if (field >= _header->TotalFieldCount)
{
ASSERT(field == _header->TotalFieldCount);
ASSERT(int32(field) == _loadInfo->Meta->ParentIndexField);
return _loadInfo->Meta->IsSignedField(field);
}
DB2ColumnCompression compressionType = _columnMeta ? _columnMeta[field].CompressionType : DB2ColumnCompression::None;
switch (compressionType)
{
case DB2ColumnCompression::None:
case DB2ColumnCompression::CommonData:
case DB2ColumnCompression::Pallet:
case DB2ColumnCompression::PalletArray:
return _loadInfo->Meta->IsSignedField(field);
case DB2ColumnCompression::SignedImmediate:
return field != uint32(_loadInfo->Meta->IndexField);
case DB2ColumnCompression::Immediate:
return false;
default:
ABORT_MSG("Unhandled compression type %u in %s", uint32(_columnMeta[field].CompressionType), _fileName);
break;
}
return false;
}
char const* DB2FileLoaderRegularImpl::GetExpectedSignMismatchReason(uint32 field) const
{
if (field >= _header->TotalFieldCount)
{
ASSERT(field == _header->TotalFieldCount);
ASSERT(int32(field) == _loadInfo->Meta->ParentIndexField);
return " (ParentIndexField must always be unsigned)";
}
DB2ColumnCompression compressionType = _columnMeta ? _columnMeta[field].CompressionType : DB2ColumnCompression::None;
switch (compressionType)
{
case DB2ColumnCompression::None:
case DB2ColumnCompression::CommonData:
case DB2ColumnCompression::Pallet:
case DB2ColumnCompression::PalletArray:
if (int32(field) == _loadInfo->Meta->IndexField)
return " (IndexField must always be unsigned)";
if (int32(field) == _loadInfo->Meta->ParentIndexField)
return " (ParentIndexField must always be unsigned)";
return "";
case DB2ColumnCompression::SignedImmediate:
return " (CompressionType is SignedImmediate)";
case DB2ColumnCompression::Immediate:
return " (CompressionType is Immediate)";
default:
ABORT_MSG("Unhandled compression type %u in %s", uint32(_columnMeta[field].CompressionType), _fileName);
break;
}
return "";
}
DB2FileLoaderSparseImpl::DB2FileLoaderSparseImpl(char const* fileName, DB2FileLoadInfo const* loadInfo, DB2Header const* header, DB2FileSource* source) :
_fileName(fileName),
_loadInfo(loadInfo),
_header(header),
_source(source),
_totalRecordSize(0),
_maxRecordSize(0),
_fieldAndArrayOffsets(loadInfo ? (std::make_unique<std::size_t[]>(loadInfo->Meta->FieldCount + loadInfo->FieldCount - (!loadInfo->Meta->HasIndexFieldInData() ? 1 : 0))) : nullptr)
{
}
DB2FileLoaderSparseImpl::~DB2FileLoaderSparseImpl()
{
}
void DB2FileLoaderSparseImpl::LoadColumnData(std::unique_ptr<DB2SectionHeader[]> sections, std::unique_ptr<DB2FieldEntry[]> fields, std::unique_ptr<DB2ColumnMeta[]> /*columnMeta*/,
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> /*palletValues*/, std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> /*palletArrayValues*/,
std::unique_ptr<std::unordered_map<uint32, uint32>[]> /*commonValues*/)
{
_sections = std::move(sections);
_fields = std::move(fields);
}
void DB2FileLoaderSparseImpl::SkipEncryptedSection(uint32 section)
{
_catalogIds.resize(_catalogIds.size() + _sections[section].CatalogDataCount);
_catalog.resize(_catalog.size() + _sections[section].CatalogDataCount);
}
bool DB2FileLoaderSparseImpl::LoadCatalogData(DB2FileSource* source, uint32 section)
{
source->SetPosition(_sections[section].CatalogDataOffset);
std::size_t oldSize = _catalog.size();
_catalogIds.resize(oldSize + _sections[section].CatalogDataCount);
if (!source->Read(&_catalogIds[oldSize], sizeof(uint32) * _sections[section].CatalogDataCount))
return false;
if (_sections[section].CopyTableCount)
{
std::size_t oldCopyTableSize = _copyTable.size();
_copyTable.resize(oldCopyTableSize + _sections[section].CopyTableCount);
if (!source->Read(&_copyTable[oldCopyTableSize], sizeof(DB2RecordCopy) * _sections[section].CopyTableCount))
return false;
}
_catalog.resize(oldSize + _sections[section].CatalogDataCount);
if (!source->Read(&_catalog[oldSize], sizeof(DB2CatalogEntry) * _sections[section].CatalogDataCount))
return false;
for (uint32 i = 0; i < _sections[section].CatalogDataCount; ++i)
{
_totalRecordSize += _catalog[oldSize + i].RecordSize;
_maxRecordSize = std::max(_maxRecordSize, _catalog[oldSize + i].RecordSize);
}
return true;
}
void DB2FileLoaderSparseImpl::SetAdditionalData(std::vector<uint32> /*idTable*/, std::vector<DB2RecordCopy> /*copyTable*/, std::vector<std::vector<DB2IndexData>> parentIndexes)
{
_parentIndexes = std::move(parentIndexes);
_recordBuffer = std::make_unique<uint8[]>(_maxRecordSize);
}
char* DB2FileLoaderSparseImpl::AutoProduceData(uint32& indexTableSize, char**& indexTable)
{
if (_loadInfo->Meta->FieldCount != _header->FieldCount)
throw DB2FileLoadException(Trinity::StringFormat("Found unsupported parent index in sparse db2 {}", _fileName));
//get struct size and index pos
uint32 recordsize = _loadInfo->Meta->GetRecordSize();
uint32 records = _catalog.size();
using index_entry_t = char*;
indexTableSize = _header->MaxId + 1;
indexTable = new index_entry_t[indexTableSize];
memset(indexTable, 0, indexTableSize * sizeof(index_entry_t));
char* dataTable = new char[(records + _copyTable.size()) * recordsize];
memset(dataTable, 0, (records + _copyTable.size()) * recordsize);
uint32 offset = 0;
uint32 y = 0;
for (uint32 section = 0; section < _header->SectionCount; ++section)
{
DB2SectionHeader const& sectionHeader = GetSection(section);
if (sectionHeader.TactId)
{
offset += recordsize * sectionHeader.RecordCount;
y += sectionHeader.RecordCount;
continue;
}
for (uint32 sr = 0; sr < sectionHeader.CatalogDataCount; ++sr, ++y)
{
unsigned char const* rawRecord = GetRawRecordData(y, §ion);
if (!rawRecord)
continue;
uint32 indexVal = _catalogIds[y];
indexTable[indexVal] = &dataTable[offset];
uint32 fieldIndex = 0;
if (!_loadInfo->Meta->HasIndexFieldInData())
{
*((uint32*)(&dataTable[offset])) = indexVal;
offset += 4;
++fieldIndex;
}
for (uint32 x = 0; x < _header->FieldCount; ++x)
{
for (uint32 z = 0; z < _loadInfo->Meta->Fields[x].ArraySize; ++z)
{
switch (_loadInfo->Fields[fieldIndex].Type)
{
case FT_FLOAT:
*((float*)(&dataTable[offset])) = RecordGetFloat(rawRecord, x, z);
offset += 4;
break;
case FT_INT:
*((uint32*)(&dataTable[offset])) = RecordGetVarInt(rawRecord, x, z, _loadInfo->Fields[fieldIndex].IsSigned);
offset += 4;
break;
case FT_BYTE:
*((uint8*)(&dataTable[offset])) = RecordGetUInt8(rawRecord, x, z);
offset += 1;
break;
case FT_SHORT:
*((uint16*)(&dataTable[offset])) = RecordGetUInt16(rawRecord, x, z);
offset += 2;
break;
case FT_LONG:
*((uint64*)(&dataTable[offset])) = RecordGetUInt64(rawRecord, x, z);
offset += 8;
break;
case FT_STRING:
for (char const*& localeStr : ((LocalizedString*)(&dataTable[offset]))->Str)
localeStr = nullStr;
offset += sizeof(LocalizedString);
break;
case FT_STRING_NOT_LOCALIZED:
*(char const**)(&dataTable[offset]) = nullStr;
offset += sizeof(char*);
break;
default:
ABORT_MSG("Unknown format character '%c' found in %s meta for field %s",
_loadInfo->Fields[fieldIndex].Type, _fileName, _loadInfo->Fields[fieldIndex].Name);
break;
}
++fieldIndex;
}
}
for (uint32 x = _header->FieldCount; x < _loadInfo->Meta->FieldCount; ++x)
{
for (uint32 z = 0; z < _loadInfo->Meta->Fields[x].ArraySize; ++z)
{
switch (_loadInfo->Fields[fieldIndex].Type)
{
case FT_INT:
*((uint32*)(&dataTable[offset])) = 0;
offset += 4;
break;
case FT_BYTE:
*((uint8*)(&dataTable[offset])) = 0;
offset += 1;
break;
case FT_SHORT:
*((uint16*)(&dataTable[offset])) = 0;
offset += 2;
break;
default:
ABORT_MSG("Unknown format character '%c' found in %s meta for parent field %s",
_loadInfo->Fields[fieldIndex].Type, _fileName, _loadInfo->Fields[fieldIndex].Name);
break;
}
++fieldIndex;
}
}
}
}
return dataTable;
}
char* DB2FileLoaderSparseImpl::AutoProduceStrings(char** indexTable, uint32 indexTableSize, uint32 locale)
{
if (_loadInfo->Meta->FieldCount != _header->FieldCount)
throw DB2FileLoadException(Trinity::StringFormat("Found unsupported parent index in sparse db2 {}", _fileName));
if (!(_header->Locale & (1 << locale)))
{
char const* sep = "";
std::ostringstream str;
for (uint32 i = 0; i < TOTAL_LOCALES; ++i)
{
if (_header->Locale & (1 << i))
{
str << sep << localeNames[i];
sep = ", ";
}
}
TC_LOG_ERROR("", "Attempted to load {} which has locales {} as {}. Check if you placed your localized db2 files in correct directory.", _fileName, str.str(), localeNames[locale]);
return nullptr;
}
uint32 records = _catalog.size();
uint32 recordsize = _loadInfo->Meta->GetRecordSize();
std::size_t stringFields = _loadInfo->GetStringFieldCount(false);
std::size_t localizedStringFields = _loadInfo->GetStringFieldCount(true);
if (!stringFields)
return nullptr;
std::size_t stringsInRecordSize = (stringFields - localizedStringFields) * sizeof(char*);
std::size_t localizedStringsInRecordSize = localizedStringFields * sizeof(LocalizedString);
// string table size is "total size of all records" - RecordCount * "size of record without strings"
std::size_t stringTableSize = _totalRecordSize - (records * ((recordsize - (!_loadInfo->Meta->HasIndexFieldInData() ? 4 : 0)) - stringsInRecordSize - localizedStringsInRecordSize));
char* stringTable = new char[stringTableSize];
memset(stringTable, 0, stringTableSize);
char* stringPtr = stringTable;
uint32 y = 0;
for (uint32 section = 0; section < _header->SectionCount; ++section)
{
DB2SectionHeader const& sectionHeader = GetSection(section);
if (sectionHeader.TactId)
{
y += sectionHeader.RecordCount;
continue;
}
for (uint32 sr = 0; sr < sectionHeader.CatalogDataCount; ++sr, ++y)
{
unsigned char const* rawRecord = GetRawRecordData(y, §ion);
if (!rawRecord)
continue;
uint32 indexVal = _catalogIds[y];
if (indexVal >= indexTableSize)
continue;
char* recordData = indexTable[indexVal];
uint32 offset = 0;
uint32 fieldIndex = 0;
if (!_loadInfo->Meta->HasIndexFieldInData())
{
offset += 4;
++fieldIndex;
}
for (uint32 x = 0; x < _header->FieldCount; ++x)
{
for (uint32 z = 0; z < _loadInfo->Meta->Fields[x].ArraySize; ++z)
{
switch (_loadInfo->Fields[fieldIndex].Type)
{
case FT_FLOAT:
offset += 4;
break;
case FT_INT:
offset += 4;
break;
case FT_BYTE:
offset += 1;
break;
case FT_SHORT:
offset += 2;
break;
case FT_LONG:
offset += 8;
break;
case FT_STRING:
{
LocalizedString* db2str = (LocalizedString*)(&recordData[offset]);
db2str->Str[locale] = stringPtr;
strcpy(stringPtr, RecordGetString(rawRecord, x, z));
stringPtr += strlen(stringPtr) + 1;
offset += sizeof(LocalizedString);
break;
}
case FT_STRING_NOT_LOCALIZED:
{
char const** db2str = (char const**)(&recordData[offset]);
*db2str = stringPtr;
strcpy(stringPtr, RecordGetString(rawRecord, x, z));
stringPtr += strlen(stringPtr) + 1;
offset += sizeof(char*);
break;
}
default:
ABORT_MSG("Unknown format character '%c' found in %s meta for field %s",
_loadInfo->Fields[fieldIndex].Type, _fileName, _loadInfo->Fields[fieldIndex].Name);
break;
}
++fieldIndex;
}
}
}
}
return stringTable;
}
void DB2FileLoaderSparseImpl::AutoProduceRecordCopies(uint32 records, char** indexTable, char* dataTable)
{
uint32 recordCopies = GetRecordCopyCount();
if (!recordCopies)
return;
uint32 recordsize = _loadInfo->Meta->GetRecordSize();
uint32 offset = _header->RecordCount * recordsize;
uint32 idFieldOffset = _loadInfo->Meta->HasIndexFieldInData() ? _loadInfo->Meta->GetIndexFieldOffset() : 0;
for (uint32 c = 0; c < recordCopies; ++c)
{
DB2RecordCopy copy = GetRecordCopy(c);
if (copy.SourceRowId && copy.SourceRowId < records && copy.NewRowId < records && indexTable[copy.SourceRowId])
{
indexTable[copy.NewRowId] = &dataTable[offset];
memcpy(indexTable[copy.NewRowId], indexTable[copy.SourceRowId], recordsize);
*((uint32*)(&dataTable[offset + idFieldOffset])) = copy.NewRowId;
offset += recordsize;
}
}
}
DB2Record DB2FileLoaderSparseImpl::GetRecord(uint32 recordNumber) const
{
return DB2Record(*this, recordNumber, _fieldAndArrayOffsets.get());
}
DB2RecordCopy DB2FileLoaderSparseImpl::GetRecordCopy(uint32 copyNumber) const
{
if (copyNumber >= GetRecordCopyCount())
return DB2RecordCopy{};
return _copyTable[copyNumber];
}
uint32 DB2FileLoaderSparseImpl::GetRecordCount() const
{
return _catalog.size();
}
uint32 DB2FileLoaderSparseImpl::GetRecordCopyCount() const
{
return _copyTable.size();
}
void DB2FileLoaderSparseImpl::FillParentLookup(char* dataTable)
{
int32 parentIdOffset = _loadInfo->Meta->GetParentIndexFieldOffset();
uint32 recordSize = _loadInfo->Meta->GetRecordSize();
uint32 recordIndexOffset = 0;
for (uint32 i = 0; i < _header->SectionCount; ++i)
{
DB2SectionHeader const& section = GetSection(i);
if (!section.TactId)
{
for (std::size_t j = 0; j < _parentIndexes[i][0].Entries.size(); ++j)
{
uint32 parentId = _parentIndexes[i][0].Entries[j].ParentId;
char* recordData = &dataTable[(_parentIndexes[i][0].Entries[j].RecordIndex + recordIndexOffset) * recordSize];
switch (_loadInfo->Meta->Fields[_loadInfo->Meta->ParentIndexField].Type)
{
case FT_SHORT:
{
if (_loadInfo->Meta->ParentIndexField >= int32(_loadInfo->Meta->FileFieldCount))
{
// extra field at the end
*reinterpret_cast<uint32*>(&recordData[parentIdOffset]) = parentId;
}
else
{
// in data block, must fit
ASSERT(parentId <= 0xFFFF, "ParentId value %u does not fit into uint16 field (%s in %s)",
parentId, _loadInfo->Fields[_loadInfo->GetFieldIndexByMetaIndex(_loadInfo->Meta->ParentIndexField)].Name, _fileName);
*reinterpret_cast<uint16*>(&recordData[parentIdOffset]) = parentId;
}
break;
}
case FT_BYTE:
{
if (_loadInfo->Meta->ParentIndexField >= int32(_loadInfo->Meta->FileFieldCount))
{
// extra field at the end
*reinterpret_cast<uint32*>(&recordData[parentIdOffset]) = parentId;
}
else
{
// in data block, must fit
ASSERT(parentId <= 0xFF, "ParentId value %u does not fit into uint8 field (%s in %s)",
parentId, _loadInfo->Fields[_loadInfo->GetFieldIndexByMetaIndex(_loadInfo->Meta->ParentIndexField)].Name, _fileName);
*reinterpret_cast<uint8*>(&recordData[parentIdOffset]) = parentId;
}
break;
}
case FT_INT:
*reinterpret_cast<uint32*>(&recordData[parentIdOffset]) = parentId;
break;
default:
ABORT_MSG("Unhandled parent id type '%c' found in %s", _loadInfo->Meta->Fields[_loadInfo->Meta->ParentIndexField].Type, _fileName);
break;
}
}
}
recordIndexOffset += section.RecordCount;
}
}
uint32 DB2FileLoaderSparseImpl::GetRecordSection(uint32 recordNumber) const
{
uint32 section = 0;
for (; section < _header->SectionCount; ++section)
{
DB2SectionHeader const& sectionHeader = GetSection(section);
if (recordNumber < sectionHeader.CatalogDataCount)
break;
recordNumber -= sectionHeader.CatalogDataCount;
}
return section;
}
unsigned char const* DB2FileLoaderSparseImpl::GetRawRecordData(uint32 recordNumber, uint32 const* section) const
{
if (recordNumber >= _catalog.size())
return nullptr;
if (GetSection(section ? *section : GetRecordSection(recordNumber)).TactId)
return nullptr;
_source->SetPosition(_catalog[recordNumber].FileOffset);
uint8* rawRecord = _recordBuffer.get();
if (!_source->Read(rawRecord, _catalog[recordNumber].RecordSize))
return nullptr;
CalculateAndStoreFieldOffsets(rawRecord);
return rawRecord;
}
uint32 DB2FileLoaderSparseImpl::RecordGetId(uint8 const* record, uint32 recordIndex) const
{
if (_loadInfo->Meta->HasIndexFieldInData())
return RecordGetVarInt(record, _loadInfo->Meta->GetIndexField(), 0, false);
return _catalogIds[recordIndex];
}
uint8 DB2FileLoaderSparseImpl::RecordGetUInt8(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
ASSERT(field < _header->FieldCount);
return *reinterpret_cast<uint8 const*>(record + GetFieldOffset(field, arrayIndex));
}
uint16 DB2FileLoaderSparseImpl::RecordGetUInt16(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
ASSERT(field < _header->FieldCount);
uint16 val = *reinterpret_cast<uint16 const*>(record + GetFieldOffset(field, arrayIndex));
EndianConvert(val);
return val;
}
uint32 DB2FileLoaderSparseImpl::RecordGetUInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
return RecordGetVarInt(record, field, arrayIndex, false);
}
int32 DB2FileLoaderSparseImpl::RecordGetInt32(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
return int32(RecordGetVarInt(record, field, arrayIndex, true));
}
uint64 DB2FileLoaderSparseImpl::RecordGetUInt64(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
ASSERT(field < _header->FieldCount);
uint64 val = *reinterpret_cast<uint64 const*>(record + GetFieldOffset(field, arrayIndex));
EndianConvert(val);
return val;
}
float DB2FileLoaderSparseImpl::RecordGetFloat(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
ASSERT(field < _header->FieldCount);
float val = *reinterpret_cast<float const*>(record + GetFieldOffset(field, arrayIndex));
EndianConvert(val);
return val;
}
char const* DB2FileLoaderSparseImpl::RecordGetString(uint8 const* record, uint32 field, uint32 arrayIndex) const
{
ASSERT(field < _header->FieldCount);
return reinterpret_cast<char const*>(record + GetFieldOffset(field, arrayIndex));
}
uint32 DB2FileLoaderSparseImpl::RecordGetVarInt(uint8 const* record, uint32 field, uint32 arrayIndex, bool isSigned) const
{
ASSERT(field < _header->FieldCount);
uint32 val = 0;
memcpy(&val, record + GetFieldOffset(field, arrayIndex), GetFieldSize(field));
EndianConvert(val);
if (isSigned)
return int32(val) << _fields[field].UnusedBits >> _fields[field].UnusedBits;
return val << _fields[field].UnusedBits >> _fields[field].UnusedBits;
}
uint16 DB2FileLoaderSparseImpl::GetFieldOffset(uint32 field, uint32 arrayIndex) const
{
return uint16(_fieldAndArrayOffsets[_fieldAndArrayOffsets[field] + arrayIndex]);
}
uint16 DB2FileLoaderSparseImpl::GetFieldSize(uint32 field) const
{
ASSERT(field < _header->FieldCount);
return 4 - _fields[field].UnusedBits / 8;
}
std::size_t* DB2FileLoaderSparseImpl::RecordCreateDetachedFieldOffsets(std::size_t* oldOffsets) const
{
if (oldOffsets != _fieldAndArrayOffsets.get())
return oldOffsets;
std::size_t size = _loadInfo->Meta->FieldCount + _loadInfo->FieldCount - (!_loadInfo->Meta->HasIndexFieldInData() ? 1 : 0);
std::size_t* newOffsets = new std::size_t[size];
memcpy(newOffsets, _fieldAndArrayOffsets.get(), size * sizeof(std::size_t));
return newOffsets;
}
void DB2FileLoaderSparseImpl::RecordDestroyFieldOffsets(std::size_t*& fieldOffsets) const
{
if (fieldOffsets == _fieldAndArrayOffsets.get())
return;
delete[] fieldOffsets;
fieldOffsets = nullptr;
}
void DB2FileLoaderSparseImpl::CalculateAndStoreFieldOffsets(uint8 const* rawRecord) const
{
std::size_t offset = 0;
uint32 combinedField = _loadInfo->Meta->FieldCount;
for (uint32 field = 0; field < _loadInfo->Meta->FieldCount; ++field)
{
_fieldAndArrayOffsets[field] = combinedField;
for (uint32 arr = 0; arr < _loadInfo->Meta->Fields[field].ArraySize; ++arr)
{
_fieldAndArrayOffsets[combinedField] = offset;
switch (_loadInfo->Meta->Fields[field].Type)
{
case FT_BYTE:
case FT_SHORT:
case FT_INT:
case FT_LONG:
offset += GetFieldSize(field);
break;
case FT_FLOAT:
offset += sizeof(float);
break;
case FT_STRING:
case FT_STRING_NOT_LOCALIZED:
offset += strlen(reinterpret_cast<char const*>(rawRecord) + offset) + 1;
break;
default:
ABORT_MSG("Unknown format character '%c' found in %s meta", _loadInfo->Meta->Fields[field].Type, _fileName);
break;
}
++combinedField;
}
}
}
uint32 DB2FileLoaderSparseImpl::GetMaxId() const
{
return _header->MaxId;
}
DB2FileLoadInfo const* DB2FileLoaderSparseImpl::GetLoadInfo() const
{
return _loadInfo;
}
DB2SectionHeader& DB2FileLoaderSparseImpl::GetSection(uint32 section) const
{
return _sections[section];
}
bool DB2FileLoaderSparseImpl::IsSignedField(uint32 field) const
{
ASSERT(field < _header->FieldCount);
return _loadInfo->Meta->IsSignedField(field);
}
char const* DB2FileLoaderSparseImpl::GetExpectedSignMismatchReason(uint32 field) const
{
ASSERT(field < _header->FieldCount);
if (int32(field) == _loadInfo->Meta->IndexField)
return " (IndexField must always be unsigned)";
if (int32(field) == _loadInfo->Meta->ParentIndexField)
return " (ParentIndexField must always be unsigned)";
return "";
}
DB2Record::DB2Record(DB2FileLoaderImpl const& db2, uint32 recordIndex, std::size_t* fieldOffsets)
: _db2(db2), _recordIndex(recordIndex), _recordData(db2.GetRawRecordData(recordIndex, nullptr)), _fieldOffsets(fieldOffsets)
{
}
DB2Record::~DB2Record()
{
_db2.RecordDestroyFieldOffsets(_fieldOffsets);
}
DB2Record::operator bool()
{
return _recordData != nullptr;
}
uint32 DB2Record::GetId() const
{
return _db2.RecordGetId(_recordData, _recordIndex);
}
uint8 DB2Record::GetUInt8(uint32 field, uint32 arrayIndex) const
{
return _db2.RecordGetUInt8(_recordData, field, arrayIndex);
}
uint8 DB2Record::GetUInt8(char const* fieldName) const
{
std::pair<int32, int32> fieldIndex = _db2.GetLoadInfo()->GetFieldIndexByName(fieldName);
ASSERT(fieldIndex.first != -1, "Field with name %s does not exist!", fieldName);
return _db2.RecordGetUInt8(_recordData, uint32(fieldIndex.first), uint32(fieldIndex.second));
}
uint16 DB2Record::GetUInt16(uint32 field, uint32 arrayIndex) const
{
return _db2.RecordGetUInt16(_recordData, field, arrayIndex);
}
uint16 DB2Record::GetUInt16(char const* fieldName) const
{
std::pair<int32, int32> fieldIndex = _db2.GetLoadInfo()->GetFieldIndexByName(fieldName);
ASSERT(fieldIndex.first != -1, "Field with name %s does not exist!", fieldName);
return _db2.RecordGetUInt16(_recordData, uint32(fieldIndex.first), uint32(fieldIndex.second));
}
uint32 DB2Record::GetUInt32(uint32 field, uint32 arrayIndex) const
{
return _db2.RecordGetUInt32(_recordData, field, arrayIndex);
}
uint32 DB2Record::GetUInt32(char const* fieldName) const
{
std::pair<int32, int32> fieldIndex = _db2.GetLoadInfo()->GetFieldIndexByName(fieldName);
ASSERT(fieldIndex.first != -1, "Field with name %s does not exist!", fieldName);
return _db2.RecordGetUInt32(_recordData, uint32(fieldIndex.first), uint32(fieldIndex.second));
}
int32 DB2Record::GetInt32(uint32 field, uint32 arrayIndex) const
{
return _db2.RecordGetInt32(_recordData, field, arrayIndex);
}
int32 DB2Record::GetInt32(char const* fieldName) const
{
std::pair<int32, int32> fieldIndex = _db2.GetLoadInfo()->GetFieldIndexByName(fieldName);
ASSERT(fieldIndex.first != -1, "Field with name %s does not exist!", fieldName);
return _db2.RecordGetInt32(_recordData, uint32(fieldIndex.first), uint32(fieldIndex.second));
}
uint64 DB2Record::GetUInt64(uint32 field, uint32 arrayIndex) const
{
return _db2.RecordGetUInt64(_recordData, field, arrayIndex);
}
uint64 DB2Record::GetUInt64(char const* fieldName) const
{
std::pair<int32, int32> fieldIndex = _db2.GetLoadInfo()->GetFieldIndexByName(fieldName);
ASSERT(fieldIndex.first != -1, "Field with name %s does not exist!", fieldName);
return _db2.RecordGetUInt64(_recordData, uint32(fieldIndex.first), uint32(fieldIndex.second));
}
float DB2Record::GetFloat(uint32 field, uint32 arrayIndex) const
{
return _db2.RecordGetFloat(_recordData, field, arrayIndex);
}
float DB2Record::GetFloat(char const* fieldName) const
{
std::pair<int32, int32> fieldIndex = _db2.GetLoadInfo()->GetFieldIndexByName(fieldName);
ASSERT(fieldIndex.first != -1, "Field with name %s does not exist!", fieldName);
return _db2.RecordGetFloat(_recordData, uint32(fieldIndex.first), uint32(fieldIndex.second));
}
char const* DB2Record::GetString(uint32 field, uint32 arrayIndex) const
{
return _db2.RecordGetString(_recordData, field, arrayIndex);
}
char const* DB2Record::GetString(char const* fieldName) const
{
std::pair<int32, int32> fieldIndex = _db2.GetLoadInfo()->GetFieldIndexByName(fieldName);
ASSERT(fieldIndex.first != -1, "Field with name %s does not exist!", fieldName);
return _db2.RecordGetString(_recordData, uint32(fieldIndex.first), uint32(fieldIndex.second));
}
void DB2Record::MakePersistent()
{
_fieldOffsets = _db2.RecordCreateDetachedFieldOffsets(_fieldOffsets);
}
DB2FileLoader::DB2FileLoader() : _impl(nullptr), _header()
{
}
DB2FileLoader::~DB2FileLoader()
{
delete _impl;
}
void DB2FileLoader::LoadHeaders(DB2FileSource* source, DB2FileLoadInfo const* loadInfo)
{
if (!source->IsOpen())
throw std::system_error(std::make_error_code(std::errc::no_such_file_or_directory));
if (!source->Read(&_header, sizeof(DB2Header)))
throw DB2FileLoadException("Failed to read header");
EndianConvert(_header.Signature);
EndianConvert(_header.RecordCount);
EndianConvert(_header.FieldCount);
EndianConvert(_header.RecordSize);
EndianConvert(_header.StringTableSize);
EndianConvert(_header.TableHash);
EndianConvert(_header.LayoutHash);
EndianConvert(_header.MinId);
EndianConvert(_header.MaxId);
EndianConvert(_header.Locale);
EndianConvert(_header.Flags);
EndianConvert(_header.IndexField);
EndianConvert(_header.TotalFieldCount);
EndianConvert(_header.PackedDataOffset);
EndianConvert(_header.ParentLookupCount);
EndianConvert(_header.ColumnMetaSize);
EndianConvert(_header.CommonDataSize);
EndianConvert(_header.PalletDataSize);
EndianConvert(_header.SectionCount);
if (_header.Signature != 0x33434457) //'WDC3'
throw DB2FileLoadException(Trinity::StringFormat("Incorrect file signature in {}, expected 'WDC3', got %c%c%c%c", source->GetFileName(),
char(_header.Signature & 0xFF), char((_header.Signature >> 8) & 0xFF), char((_header.Signature >> 16) & 0xFF), char((_header.Signature >> 24) & 0xFF)));
if (loadInfo && _header.LayoutHash != loadInfo->Meta->LayoutHash)
throw DB2FileLoadException(Trinity::StringFormat("Incorrect layout hash in {}, expected 0x{:08X}, got 0x{:08X} (possibly wrong client version)",
source->GetFileName(), loadInfo->Meta->LayoutHash, _header.LayoutHash));
if (_header.ParentLookupCount > 1)
throw DB2FileLoadException(Trinity::StringFormat("Too many parent lookups in {}, only one is allowed, got {}",
source->GetFileName(), _header.ParentLookupCount));
if (loadInfo && (_header.TotalFieldCount + (loadInfo->Meta->ParentIndexField >= int32(_header.TotalFieldCount) ? 1 : 0) != loadInfo->Meta->FieldCount))
throw DB2FileLoadException(Trinity::StringFormat("Incorrect number of fields in {}, expected {}, got {}",
source->GetFileName(), loadInfo->Meta->FieldCount, _header.TotalFieldCount + (loadInfo->Meta->ParentIndexField >= int32(_header.TotalFieldCount) ? 1 : 0)));
if (loadInfo && (_header.ParentLookupCount && loadInfo->Meta->ParentIndexField == -1))
throw DB2FileLoadException(Trinity::StringFormat("Unexpected parent lookup found in {}", source->GetFileName()));
std::unique_ptr<DB2SectionHeader[]> sections = std::make_unique<DB2SectionHeader[]>(_header.SectionCount);
if (_header.SectionCount && !source->Read(sections.get(), sizeof(DB2SectionHeader) * _header.SectionCount))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read section headers from {}", source->GetFileName()));
uint32 totalCopyTableSize = 0;
uint32 totalParentLookupDataSize = 0;
for (uint32 i = 0; i < _header.SectionCount; ++i)
{
totalCopyTableSize += sections[i].CopyTableCount * sizeof(DB2RecordCopy);
totalParentLookupDataSize += sections[i].ParentLookupDataSize;
}
if (loadInfo && !(_header.Flags & 0x1))
{
int64 expectedFileSize =
sizeof(DB2Header) +
sizeof(DB2SectionHeader) * _header.SectionCount +
sizeof(DB2FieldEntry) * _header.FieldCount +
int64(_header.RecordSize) * _header.RecordCount +
_header.StringTableSize +
(loadInfo->Meta->IndexField == -1 ? sizeof(uint32) * _header.RecordCount : 0) +
totalCopyTableSize +
_header.ColumnMetaSize +
_header.PalletDataSize +
_header.CommonDataSize +
totalParentLookupDataSize;
if (source->GetFileSize() != expectedFileSize)
throw DB2FileLoadException(Trinity::StringFormat("{} failed size consistency check, expected {}, got {}", source->GetFileName(), expectedFileSize, source->GetFileSize()));
}
std::unique_ptr<DB2FieldEntry[]> fieldData = std::make_unique<DB2FieldEntry[]>(_header.FieldCount);
if (!source->Read(fieldData.get(), sizeof(DB2FieldEntry) * _header.FieldCount))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read field information from {}", source->GetFileName()));
std::unique_ptr<DB2ColumnMeta[]> columnMeta;
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletValues;
std::unique_ptr<std::unique_ptr<DB2PalletValue[]>[]> palletArrayValues;
std::unique_ptr<std::unordered_map<uint32, uint32>[]> commonValues;
if (_header.ColumnMetaSize)
{
columnMeta = std::make_unique<DB2ColumnMeta[]>(_header.TotalFieldCount);
if (!source->Read(columnMeta.get(), _header.ColumnMetaSize))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read field metadata from {}", source->GetFileName()));
if (loadInfo && loadInfo->Meta->HasIndexFieldInData())
{
if (columnMeta[loadInfo->Meta->IndexField].CompressionType != DB2ColumnCompression::None
&& columnMeta[loadInfo->Meta->IndexField].CompressionType != DB2ColumnCompression::Immediate
&& columnMeta[loadInfo->Meta->IndexField].CompressionType != DB2ColumnCompression::SignedImmediate)
throw DB2FileLoadException(Trinity::StringFormat("Invalid compression type for index field in {}, expected one of None (0), Immediate (1), SignedImmediate (5), got {}",
source->GetFileName(), uint32(columnMeta[loadInfo->Meta->IndexField].CompressionType)));
}
palletValues = std::make_unique<std::unique_ptr<DB2PalletValue[]>[]>(_header.TotalFieldCount);
for (uint32 i = 0; i < _header.TotalFieldCount; ++i)
{
if (columnMeta[i].CompressionType != DB2ColumnCompression::Pallet)
continue;
palletValues[i] = std::make_unique<DB2PalletValue[]>(columnMeta[i].AdditionalDataSize / sizeof(DB2PalletValue));
if (!source->Read(palletValues[i].get(), columnMeta[i].AdditionalDataSize))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read field pallet values from {} for field {}", source->GetFileName(), i));
}
palletArrayValues = std::make_unique<std::unique_ptr<DB2PalletValue[]>[]>(_header.TotalFieldCount);
for (uint32 i = 0; i < _header.TotalFieldCount; ++i)
{
if (columnMeta[i].CompressionType != DB2ColumnCompression::PalletArray)
continue;
palletArrayValues[i] = std::make_unique<DB2PalletValue[]>(columnMeta[i].AdditionalDataSize / sizeof(DB2PalletValue));
if (!source->Read(palletArrayValues[i].get(), columnMeta[i].AdditionalDataSize))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read field pallet array values from {} for field {}", source->GetFileName(), i));
}
std::unique_ptr<std::unique_ptr<DB2CommonValue[]>[]> commonData = std::make_unique<std::unique_ptr<DB2CommonValue[]>[]>(_header.TotalFieldCount);
commonValues = std::make_unique<std::unordered_map<uint32, uint32>[]>(_header.TotalFieldCount);
for (uint32 i = 0; i < _header.TotalFieldCount; ++i)
{
if (columnMeta[i].CompressionType != DB2ColumnCompression::CommonData)
continue;
if (!columnMeta[i].AdditionalDataSize)
continue;
commonData[i] = std::make_unique<DB2CommonValue[]>(columnMeta[i].AdditionalDataSize / sizeof(DB2CommonValue));
if (!source->Read(commonData[i].get(), columnMeta[i].AdditionalDataSize))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read field common values from {} for field {}", source->GetFileName(), i));
uint32 numExtraValuesForField = columnMeta[i].AdditionalDataSize / sizeof(DB2CommonValue);
for (uint32 record = 0; record < numExtraValuesForField; ++record)
{
uint32 recordId = commonData[i][record].RecordId;
uint32 value = commonData[i][record].Value;
EndianConvert(value);
commonValues[i][recordId] = value;
}
}
}
if (!(_header.Flags & 0x1))
_impl = new DB2FileLoaderRegularImpl(source->GetFileName(), loadInfo, &_header);
else
_impl = new DB2FileLoaderSparseImpl(source->GetFileName(), loadInfo, &_header, source);
_impl->LoadColumnData(std::move(sections), std::move(fieldData), std::move(columnMeta), std::move(palletValues), std::move(palletArrayValues), std::move(commonValues));
}
void DB2FileLoader::Load(DB2FileSource* source, DB2FileLoadInfo const* loadInfo)
{
LoadHeaders(source, loadInfo);
std::vector<uint32> idTable;
std::vector<DB2RecordCopy> copyTable;
std::vector<std::vector<DB2IndexData>> parentIndexes;
if (loadInfo && !loadInfo->Meta->HasIndexFieldInData() && _header.RecordCount)
idTable.reserve(_header.RecordCount);
if (_header.ParentLookupCount)
{
parentIndexes.resize(_header.SectionCount);
for (std::vector<DB2IndexData>& parentIndexesForSection : parentIndexes)
parentIndexesForSection.resize(_header.ParentLookupCount);
}
for (uint32 i = 0; i < _header.SectionCount; ++i)
{
DB2SectionHeader& section = _impl->GetSection(i);
if (section.TactId)
{
switch (source->HandleEncryptedSection(section))
{
case DB2EncryptedSectionHandling::Skip:
_impl->SkipEncryptedSection(i);
idTable.resize(idTable.size() + section.IdTableSize / sizeof(uint32));
continue;
case DB2EncryptedSectionHandling::Process:
section.TactId = 0;
break;
default:
break;
}
}
if (!source->SetPosition(section.FileOffset))
throw DB2FileLoadException(Trinity::StringFormat("Unable to change {} read position for section {}", source->GetFileName(), i));
if (!_impl->LoadTableData(source, i))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read section table data from {} for section {}", source->GetFileName(), i));
if (!_impl->LoadCatalogData(source, i))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read section catalog data from {} for section {}", source->GetFileName(), i));
if (loadInfo)
{
if (loadInfo->Meta->HasIndexFieldInData())
{
if (section.IdTableSize != 0)
throw DB2FileLoadException(Trinity::StringFormat("Unexpected id table found in {} for section {}", source->GetFileName(), i));
}
else if (section.IdTableSize != 4 * section.RecordCount)
throw DB2FileLoadException(Trinity::StringFormat("Unexpected id table size in {} for section {}, expected {}, got {}",
source->GetFileName(), i, 4 * section.RecordCount, section.IdTableSize));
}
if (section.IdTableSize)
{
std::size_t idTableSize = idTable.size();
idTable.resize(idTableSize + section.IdTableSize / sizeof(uint32));
if (!source->Read(&idTable[idTableSize], section.IdTableSize))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read non-inline record ids from {} for section {}", source->GetFileName(), i));
// This is a hack fix for broken db2 files that have invalid id tables
for (std::size_t i = idTableSize; i < idTable.size(); ++i)
if (idTable[i] <= _header.MinId)
idTable[i] = _header.MinId + i;
}
if (!(_header.Flags & 0x1) && section.CopyTableCount)
{
std::size_t copyTableSize = copyTable.size();
copyTable.resize(copyTableSize + section.CopyTableCount);
if (!source->Read(©Table[copyTableSize], section.CopyTableCount * sizeof(DB2RecordCopy)))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read record copies from {} for section {}", source->GetFileName(), i));
}
if (_header.ParentLookupCount)
{
std::vector<DB2IndexData>& parentIndexesForSection = parentIndexes[i];
for (uint32 j = 0; j < _header.ParentLookupCount; ++j)
{
DB2IndexDataInfo indexInfo;
if (!source->Read(&indexInfo, sizeof(DB2IndexDataInfo)))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read parent lookup info from {} for section {}", source->GetFileName(), i));
if (!indexInfo.NumEntries)
continue;
parentIndexesForSection[j].Entries.resize(indexInfo.NumEntries);
if (!source->Read(parentIndexesForSection[j].Entries.data(), sizeof(DB2IndexEntry) * indexInfo.NumEntries))
throw DB2FileLoadException(Trinity::StringFormat("Unable to read parent lookup content from {} for section {}", source->GetFileName(), i));
}
}
}
_impl->SetAdditionalData(std::move(idTable), std::move(copyTable), std::move(parentIndexes));
if (loadInfo)
{
uint32 fieldIndex = 0;
if (!loadInfo->Meta->HasIndexFieldInData())
{
ASSERT(!loadInfo->Fields[0].IsSigned, "ID must be unsigned in %s", source->GetFileName());
++fieldIndex;
}
for (uint32 f = 0; f < loadInfo->Meta->FieldCount; ++f)
{
ASSERT(loadInfo->Fields[fieldIndex].IsSigned == _impl->IsSignedField(f),
"Field %s in %s must be %s%s", loadInfo->Fields[fieldIndex].Name, source->GetFileName(), _impl->IsSignedField(f) ? "signed" : "unsigned",
_impl->GetExpectedSignMismatchReason(f));
fieldIndex += loadInfo->Meta->Fields[f].ArraySize;
}
}
}
char* DB2FileLoader::AutoProduceData(uint32& indexTableSize, char**& indexTable)
{
return _impl->AutoProduceData(indexTableSize, indexTable);
}
char* DB2FileLoader::AutoProduceStrings(char** indexTable, uint32 indexTableSize, LocaleConstant locale)
{
return _impl->AutoProduceStrings(indexTable, indexTableSize, locale);
}
void DB2FileLoader::AutoProduceRecordCopies(uint32 records, char** indexTable, char* dataTable)
{
_impl->AutoProduceRecordCopies(records, indexTable, dataTable);
}
uint32 DB2FileLoader::GetRecordCount() const
{
return _impl->GetRecordCount();
}
uint32 DB2FileLoader::GetRecordCopyCount() const
{
return _impl->GetRecordCopyCount();
}
uint32 DB2FileLoader::GetMaxId() const
{
return _impl->GetMaxId();
}
DB2SectionHeader const& DB2FileLoader::GetSectionHeader(uint32 section) const
{
return _impl->GetSection(section);
}
DB2Record DB2FileLoader::GetRecord(uint32 recordNumber) const
{
return _impl->GetRecord(recordNumber);
}
DB2RecordCopy DB2FileLoader::GetRecordCopy(uint32 copyNumber) const
{
return _impl->GetRecordCopy(copyNumber);
}
|