-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathUnconvertFromZDW.cpp
2149 lines (1893 loc) · 66.7 KB
/
UnconvertFromZDW.cpp
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 2019 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
#if not defined( __STDC_LIMIT_MACROS )
#error __STDC_LIMIT_MACROS must be defined
#endif
#include "zdw/UnconvertFromZDW.h"
#include <algorithm>
#include <math.h>
#include <ostream>
#include <set>
#include <cassert>
#include <sstream>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>
#include "zdw_column_type_constants.h"
using namespace adobe::zdw::internal;
using std::ostream;
using std::map;
using std::pair;
using std::set;
using std::string;
using std::vector;
//version 4 -- added support for multiple blocks in a single file
//version 4a -- streaming uncompression
//version 5 -- escaped single char fix, file naming fix
//version 5a -- added support for reading files with no visIDs (e.g. wbenchecom) or no unique data (i.e. empty file); added option to name output files with alternate extension instead of .sql
//version 6 -- now explicitly flag signed (negative) column values, added support for lines longer than 16K bytes (up to 4GB); added API interface
//version 6a -- now the .desc file can be dumped to stdout
//version 6b -- now the ZDW data may be read from stdin; now columns specified on the command line are output in the indicated order
//version 6c -- added -ci option
//version 6e -- added -cx and -s options
//version 7 -- added "tinytext" data type
//version 7a -- fixed regression in version 7 w.r.t. stderr chatter
//version 7b -- fixed incorrect output when char field is empty (bug #57203)
//version 7c -- now using -ci and -o and getting no columns back isn't considered an error by the class wrapper
//version 7d -- added -ce option
//version 7e -- add support for xz compression/decompression
//version 7f -- now use zlib instead of zcat for .gz files
//version 7g -- fixed crash when attempting to process a non-existent file
//version 8 -- removed visitors lookup table from internal data format
//version 9 -- replaced 8-char block dictionary tree with simplified sorted map strategy, which XZ compression can capitalize on
//version 9a -- added bit vector counting stats option
//version 9b -- made robust to very large dictionary segments
//version 9c -- pclose fix; case insensitive column selection fixes
//version 9d -- expose "virtual_export_basename" column.
//version 9e -- expose "virtual_export_row" column.
//version 10 -- support mediumtext and longtext column types
//version 10a -- support header line output with non-empty column names for each file block
//version 11 -- add metadata block to header
//version 11a -- fix virtual_export_row output
//version 11b -- add zstandard support
//version 11c -- fix invalid buffer reuse bug from ZSTD pr series.
namespace {
static const char newline[] = "\n";
static const char tab[] = "\t";
const int IGNORE = -1;
const int USE_VIRTUAL_COLUMN = -2;
char const* const VIRTUAL_EXPORT_BASENAME_COLUMN_NAME = "virtual_export_basename";
char const* const VIRTUAL_EXPORT_ROW_COLUMN_NAME = "virtual_export_row";
struct InsensitiveCompare
{
bool operator() (const string& lhs, const string& rhs) const
{
return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
}
};
string getInputFilename(string filename)
{
return !filename.empty() ? filename : string("stdin");
}
/*
* In: inFileName
* Out: sourceDir & basename (a pointer into the allocated sourceDir buffer)
* The caller needs to free the memory pointed to by sourceDir, after all references to basename.
*/
void InitDirAndBasenameFromFileName(string const& inFileNameStr, char * &sourceDir, const char* &basename)
{
char *filestub_local = NULL;
//Get basename w/o extension.
const char* inFileName = inFileNameStr.c_str();
if (strchr(inFileName, '/')) {
sourceDir = strdup(inFileName);
char* tmp = strrchr(sourceDir, '/');
*tmp = 0;
tmp++;
filestub_local = tmp;
} else {
const string buf = "./" + inFileNameStr;
sourceDir = strdup(buf.c_str());
sourceDir[1] = 0;
filestub_local = sourceDir + 2;
}
//Modify input filestub: cut off the final ".zdw*" for naming the output file(s).
char *pos = strstr(filestub_local, ".zdw");
while (pos) {
//Look for another ".zdw"
char *nextPos = strstr(pos + 4, ".zdw");
if (nextPos)
pos = nextPos;
else {
//This is the last one. Truncate it.
*pos = 0;
break;
}
}
basename = filestub_local;
}
}
namespace adobe {
namespace zdw {
const int UnconvertFromZDW_Base::UNCONVERT_ZDW_VERSION = 11;
const char UnconvertFromZDW_Base::UNCONVERT_ZDW_VERSION_TAIL[3] = "c";
const size_t UnconvertFromZDW_Base::DEFAULT_LINE_LENGTH = 16 * 1024; //16K default
const char UnconvertFromZDW_Base::ERR_CODE_TEXTS[ERR_CODE_COUNT + 1][30] = {
"OK",
"BAD_PARAMETER",
"GZREAD_FAILED",
"FILE_CREATION_ERR",
"FILE_OPEN_ERR",
"UNSUPPORTED_ZDW_VERSION_ERR",
"ZDW_LONGER_THAN_EXPECTED_ERR",
"UNEXPECTED_DESC_TYPE",
"ROW_COUNT_ERR",
"CORRUPTED_DATA_ERROR",
"HEADER_NOT_READ_YET",
"HEADER_ALREADY_READ_ERR",
"AT_END_OF_FILE",
"BAD_REQUESTED_COLUMN",
"NO_COLUMNS_TO_OUTPUT",
"PROCESSING_ERROR",
"UNSUPPORTED_OPERATION",
"METADATA_KEY_NOT_PRESENT",
"Unknown error"
};
//*****************************
ZDWException::ZDWException(const ERR_CODE errcode)
: runtime_error(UnconvertFromZDW_Base::ERR_CODE_TEXTS[errcode])
, code(errcode)
{ }
//*****************************
//API maintenance -- old breakdown currently uses this text to detect whether zdw unconvert failed or not
void UnconvertFromZDW_Base::printError(const string &exeName, const string &fileName)
{
statusOutput(ERROR, "%s: %s failed\n\n", !exeName.empty() ? exeName.c_str() : "UnconvertFromZDW", fileName.c_str());
}
//***********************************************
UnconvertFromZDW_Base::UnconvertFromZDW_Base(const string &fileName,
const bool bShowStatus, const bool bQuiet, //[default=true, true]
const bool bTestOnly, const bool bOutputDescFileOnly) //[default=false, false]
: exportFileLineLength(0)
, virtualLineLength(0)
, uniques(NULL)
, visitors(NULL)
, version(UNCONVERT_ZDW_VERSION)
, decimalFactor(DECIMAL_FACTOR)
, numLines(0)
, numColumnsInExportFile(0)
, numColumns(0)
, lastBlock(1)
, row(new char[DEFAULT_LINE_LENGTH])
, exeName()
, inFileName(fileName)
, inFileBaseName(GetBaseNameForInFile(inFileName))
, input(NULL)
, bOutputDescFileOnly(bOutputDescFileOnly)
, bShowStatus(bShowStatus && !bQuiet), bQuiet(bQuiet)
, bTestOnly(bTestOnly)
, bOutputNonEmptyColumnHeader(false)
, bShowBasicStatisticsOnly(false)
, bFailOnInvalidColumns(true)
, bExcludeSpecifiedColumns(false)
, bOutputEmptyMissingColumns(false)
, indexForVirtualBaseNameColumn(IGNORE)
, indexForVirtualRowColumn(IGNORE)
, columnType(NULL)
, columnCharSize(NULL)
, outputColumns(NULL)
, columnSize(NULL), setColumns(NULL)
, columnBase(NULL), columnVal(NULL)
, dictionarySize(0), numVisitors(0)
, rowsRead(0)
, numSetColumns(0)
, statusOutput(NULL)
, eState(ZDW_BEGIN)
, currentRowNumber(0)
{
temp_buf[TEMP_BUF_LAST_POS] = '\0';
if (!inFileName.empty())
{
//Check for file existence.
struct stat buf;
const int exists = stat(inFileName.c_str(), &buf);
if (exists >= 0)
{
string cmd;
const size_t len = inFileName.size();
if (len >= 4 && !strcmp(inFileName.c_str() + len - 3, ".gz")) {
cmd = "zcat ";
cmd += inFileName;
cmd.append(" 2>/dev/null"); //we don't need to see any chatter -- we output all relevant error codes ourselves
} else if (len >= 5 && !strcmp(inFileName.c_str() + len - 4, ".bz2")) {
//Streaming uncompression of .bz2 files.
cmd = "bzip2 -d --stdout ";
cmd += inFileName;
cmd.append(" 2>/dev/null"); //we don't need to see any chatter -- we output all relevant error codes ourselves
} else if (len >= 4 && !strcmp(inFileName.c_str() + len - 3, ".xz")) {
cmd = "xzcat ";
cmd += inFileName;
} else if (len >= 5 && !strcmp(inFileName.c_str() + len - 4, ".zst")) {
//Streaming uncompression of .zst files.
cmd = "zstd -d --stdout ";
cmd += inFileName;
cmd.append(" 2>/dev/null"); //we don't need to see any chatter -- we output all relevant error codes ourselves
} else {
//Streaming text.
cmd = "cat ";
cmd += inFileName;
}
input = new BufferedInput(cmd);
}
} else {
//No filename specified -- read ZDW data from stdin.
input = new BufferedInput();
}
}
//**************************************************
UnconvertFromZDW_Base::~UnconvertFromZDW_Base()
{
cleanupBlock();
delete[] this->columnType;
delete[] this->columnCharSize;
delete[] this->outputColumns;
delete[] this->row;
delete this->input;
}
string UnconvertFromZDW_Base::getVersion()
{
std::ostringstream str;
str << UNCONVERT_ZDW_VERSION << UNCONVERT_ZDW_VERSION_TAIL;
return str.str();
}
//**********************************************
size_t UnconvertFromZDW_Base::readBytes(
void* buf, //(out) buffer to write out
const size_t len, //(in) # of bytes to read in
const bool bHaltOnReadError) //[default=true]
{
//Read from input source.
const size_t result = this->input->read(buf, len);
if ((result != len) && bHaltOnReadError)
{
printError(this->exeName, getInputFilename(this->inFileName));
delete this->input;
this->input = NULL;
throw ZDWException(GZREAD_FAILED);
}
return result;
}
//**********************************************
size_t UnconvertFromZDW_Base::skipBytes(
const size_t len) //(in) # of bytes to skip
{
//Skip this amount of data from input source
return this->input->skip(len);
}
//**********************************************
//A fast itoa variant that doesn't require reversing the string text
//
//Returns: the size of the string outputted
//
//POST-COND: this->temp_buf has the converted numeric string at the end
size_t UnconvertFromZDW_Base::llutoa(ULONGLONG value)
{
size_t rem, pos = TEMP_BUF_LAST_POS;
do
{
rem = value % 10;
value /= 10;
this->temp_buf[--pos] = static_cast<char>(rem + 0x30); //+ '0'
} while (value != 0);
return TEMP_BUF_LAST_POS - pos;
}
//Signed variant of the above method.
size_t UnconvertFromZDW_Base::lltoa(SLONGLONG value)
{
size_t rem, pos = TEMP_BUF_LAST_POS;
//Minus sign.
bool bMinus = false;
if (value < 0)
{
bMinus = true;
value = -value;
}
do
{
rem = value % 10;
value /= 10;
this->temp_buf[--pos] = static_cast<char>(rem + 0x30); //+ '0'
} while (value != 0);
if (bMinus) //sign goes at beginning
this->temp_buf[--pos] = '-';
return TEMP_BUF_LAST_POS - pos;
}
//**********************************************
char* UnconvertFromZDW_Base::GetWord(ULONG index, char* row)
{
if (this->version >= 9) {
//Determine in-memory dictionary block and relative offset.
size_t dict_memblock = 0;
while (index >= this->dictionary_memblock_size[dict_memblock]) {
index -= this->dictionary_memblock_size[dict_memblock];
++dict_memblock;
assert(dict_memblock < this->dictionary_memblock_size.size());
}
return this->dictionary[dict_memblock] + index;
}
//Build string backwards -- start with the null terminator.
char *out = row + this->exportFileLineLength - 1;
*out = 0;
do
{
const char *textBlock = this->uniques[index].m_Char.c;
//Unrolled loop.
assert(BLOCKSIZE == 8); //how many elements in the block (i.e. steps in our unrolled loop)
*(--out) = *(textBlock++);
*(--out) = *(textBlock++);
*(--out) = *(textBlock++);
*(--out) = *(textBlock++);
*(--out) = *(textBlock++);
*(--out) = *(textBlock++);
*(--out) = *(textBlock++);
*(--out) = *(textBlock++);
//Continue to a previous block, if any.
index = this->uniques[index].m_PrevChar.n;
} while (index > 0);
return out;
}
//***************************************************************
// Tokenizes the inputted string into a vector of strings.
// These texts are the only columns that will be outputted.
//
// Returns: true if operation succeeded, or false on error (duplicate string definition)
bool UnconvertFromZDW_Base::setNamesOfColumnsToOutput(
const string& csv_str,
COLUMN_INCLUSION_RULE inclusionRule)
{
this->namesOfColumnsToOutput.clear(); //start empty
this->bFailOnInvalidColumns = this->bExcludeSpecifiedColumns = this->bOutputEmptyMissingColumns = false;
switch (inclusionRule) {
default:
case FAIL_ON_INVALID_COLUMN: this->bFailOnInvalidColumns = true; break;
case SKIP_INVALID_COLUMN: break;
case EXCLUDE_SPECIFIED_COLUMNS: this->bExcludeSpecifiedColumns = true; break;
case PROVIDE_EMPTY_MISSING_COLUMNS: this->bOutputEmptyMissingColumns = true; break;
}
const string delimiters = ", ";
// Skip delimiters at beginning.
string::size_type lastPos = csv_str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = csv_str.find_first_of(delimiters, lastPos);
//Design constraint: Forbid requesting multiple (case-insensitive) instances of a column name
set<string, InsensitiveCompare> lowercasedNames;
//Each iteration tokenizes a column name.
int unsigned index = 0;
while (string::npos != pos || string::npos != lastPos)
{
const string column_name = csv_str.substr(lastPos, pos - lastPos);
//skip duplicate column names
const bool bNewColumnName = (lowercasedNames.insert(column_name)).second;
if (bNewColumnName) {
// Add column name to the map.
const bool bAdded = this->namesOfColumnsToOutput.insert(
std::make_pair(column_name, index)).second; //output this column at this position in the row
assert(bAdded);
++index;
if (column_name == VIRTUAL_EXPORT_BASENAME_COLUMN_NAME && !this->bExcludeSpecifiedColumns) {
EnableVirtualExportBaseNameColumn();
} else if (column_name == VIRTUAL_EXPORT_ROW_COLUMN_NAME && !this->bExcludeSpecifiedColumns) {
EnableVirtualExportRowColumn();
}
} else {
if (this->bFailOnInvalidColumns)
return false;
if (this->bOutputEmptyMissingColumns) {
this->blankColumnNames[index++] = column_name;
}
}
// Skip delimiters. Note the "not_of"
lastPos = csv_str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = csv_str.find_first_of(delimiters, lastPos);
}
return true;
}
bool UnconvertFromZDW_Base::setNamesOfColumnsToOutput(
const vector<string> &csv_vector,
COLUMN_INCLUSION_RULE inclusionRule)
{
this->namesOfColumnsToOutput.clear(); //start empty
this->bFailOnInvalidColumns = this->bExcludeSpecifiedColumns = this->bOutputEmptyMissingColumns = false;
switch (inclusionRule) {
default:
case FAIL_ON_INVALID_COLUMN: this->bFailOnInvalidColumns = true; break;
case SKIP_INVALID_COLUMN: break;
case EXCLUDE_SPECIFIED_COLUMNS: this->bExcludeSpecifiedColumns = true; break;
case PROVIDE_EMPTY_MISSING_COLUMNS: this->bOutputEmptyMissingColumns = true; break;
}
int unsigned index = 0;
for (vector<string>::const_iterator itr = csv_vector.begin(); itr != csv_vector.end(); itr++)
{
// Add column name to the map.
const string& column_name = *itr;
const bool bAdded = this->namesOfColumnsToOutput.insert(
std::make_pair(column_name, index)).second; //output this column at this position in the row
if (column_name == VIRTUAL_EXPORT_BASENAME_COLUMN_NAME && !this->bExcludeSpecifiedColumns) {
EnableVirtualExportBaseNameColumn();
}
if (column_name == VIRTUAL_EXPORT_ROW_COLUMN_NAME && !this->bExcludeSpecifiedColumns) {
EnableVirtualExportRowColumn();
}
if (bAdded) {
++index;
} else {
if (this->bFailOnInvalidColumns)
return false; //skip duplicate column names
if (this->bOutputEmptyMissingColumns) {
this->blankColumnNames[index++] = column_name;
}
}
}
return true;
}
//****************************************************
ERR_CODE UnconvertFromZDW_Base::outputDescToFile(
const vector<string>& columnNames,
const string& outputDir, const char* filestub, //where to output the .desc.sql
const char* ext) //extension to give the outputted .desc file (NULL=none)
{
//Open .desc.sql file handle for output.
string outFileName = outputDir + "/" + filestub + ".desc";
if (ext)
outFileName += ext;
FILE *out = fopen(outFileName.c_str(), "w");
if (!out) {
statusOutput(ERROR, "%s: Could not open %s for writing\n", exeName.c_str(), outFileName.c_str());
return FILE_CREATION_ERR;
}
const ERR_CODE val = outputDesc(columnNames, out);
fclose(out);
return val;
}
ERR_CODE UnconvertFromZDW_Base::outputDescToStdOut(
const vector<string>& columnNames)
{
return outputDesc(columnNames, stdout);
}
//****************************************************
ERR_CODE UnconvertFromZDW_Base::outputDesc(
const vector<string>& columnNames,
FILE *out)
{
vector<string> outColumnTexts = getDesc(columnNames, "\t", "\n");
if (outColumnTexts.empty() && !columnNames.empty())
return UNEXPECTED_DESC_TYPE;
//Output column texts as ordered.
vector<string>::const_iterator strIt;
for (strIt = outColumnTexts.begin(); strIt != outColumnTexts.end(); ++strIt) {
fprintf(out, "%s", strIt->c_str());
}
return OK;
}
ERR_CODE UnconvertFromZDW_Base::GetSchema(
ostream& stream)
{
vector<string> outColumnTexts = getDesc(this->columnNames, " ", "");
if (outColumnTexts.empty() && !this->columnNames.empty())
return UNEXPECTED_DESC_TYPE;
//Output column texts as ordered.
vector<string>::const_iterator strIt;
vector<string>::const_iterator begin = outColumnTexts.begin();
for (strIt = begin; strIt != outColumnTexts.end(); ++strIt) {
if (strIt != begin) {
stream << ",\n";
}
stream << *strIt;
}
return OK;
}
string UnconvertFromZDW_Base::GetBaseNameForInFile(const string &inFileName)
{
if (inFileName.empty()) {
//return "No Input Filename Found";
return string();
}
char *sourceDir = NULL;
const char* outputBasename = NULL;
InitDirAndBasenameFromFileName(inFileName, sourceDir, outputBasename);
// Must get the value of outputBaseName *before* we deallocate sourceDir since the
// character buffer used for outputBasename will be freed when we free sourceDir.
const string inFileBaseName = outputBasename;
if (sourceDir)
free(sourceDir);
return inFileBaseName;
}
//****************************************************
vector<string> UnconvertFromZDW_Base::getDesc(const vector<string>& columnNames,
const string& name_type_separator, const string& delimiter) const
{
const ULONG numColumns = columnNames.size();
const ULONG numOutputColumns = numColumns + this->blankColumnNames.size();
vector<string> outColumnTexts(numOutputColumns);
for (size_t c = 0; c < numColumns; c++)
{
const int outColumnIndex = this->namesOfColumnsToOutput.empty() ? c : this->outputColumns[c];
if (outColumnIndex != IGNORE) //only list columns that are being outputted
{
//This column goes at this output position.
assert(outColumnIndex >= 0 && outColumnIndex < int(numOutputColumns)); //valid range
outColumnTexts[outColumnIndex] =
getColumnDesc(columnNames[c], this->columnType[c], c, name_type_separator, delimiter);
//Error condition
if (outColumnTexts[outColumnIndex].empty())
return vector<string>();
}
}
//When requesting absent columns for padding, give them a generic text type.
for (map<int, string>::const_iterator iter = this->blankColumnNames.begin(); iter != this->blankColumnNames.end(); ++iter)
{
outColumnTexts[iter->first] =
getColumnDesc(iter->second, TEXT, size_t(-1), name_type_separator, delimiter);
}
return outColumnTexts;
}
//****************************************************
string UnconvertFromZDW_Base::getColumnDesc(const string& name, UCHAR type, size_t index,
const string& name_type_separator, const string& delimiter) const
{
string text = name;
text += name_type_separator;
switch (type)
{
case VIRTUAL_EXPORT_FILE_BASENAME:
case VARCHAR:
{
const size_t TEMP_BUFFER_SIZE=32;
char temp[TEMP_BUFFER_SIZE];
const int char_size = (this->columnCharSize && this->columnCharSize[index]) ? this->columnCharSize[index] : 255; //before version 7, we don't have a size value
snprintf(temp, TEMP_BUFFER_SIZE, "varchar(%d)", char_size);
text += temp;
}
break;
case TEXT: text += "text"; break;
case TINYTEXT: text += "tinytext"; break;
case MEDIUMTEXT: text += "mediumtext"; break;
case LONGTEXT: text += "longtext"; break;
case DATETIME: text += "datetime"; break;
case CHAR_2: text += "char(2)"; break;
case VISID_LOW: text += "bigint(20) unsigned"; break;
case VISID_HIGH: text += "bigint(20) unsigned"; break;
case CHAR: text += "char(1)"; break;
case TINY: text += "tinyint(3) unsigned"; break;
case SHORT: text += "smallint(5) unsigned"; break;
case VIRTUAL_EXPORT_ROW:
case LONG: text += "int(11) unsigned"; break;
case LONGLONG: text += "bigint(20) unsigned"; break;
case TINY_SIGNED: text += "tinyint(3)"; break;
case SHORT_SIGNED: text += "smallint(5)"; break;
case LONG_SIGNED: text += "int(11)"; break;
case LONGLONG_SIGNED: text += "bigint(20)"; break;
case DECIMAL: text += "decimal(24,12)"; break;
default: return string(); //unexpected type
}
text += delimiter;
return text;
}
ERR_CODE UnconvertFromZDW_Base::outputMetadataToFile(
const string& outputDir, const char* filestub) const
{
const string outFileName = outputDir + "/" + filestub + ".metadata";
FILE *out = fopen(outFileName.c_str(), "w");
if (!out) {
statusOutput(ERROR, "%s: Could not open %s for writing\n", exeName.c_str(), outFileName.c_str());
return FILE_CREATION_ERR;
}
const ERR_CODE val = outputMetadata(out);
fclose(out);
return val;
}
ERR_CODE UnconvertFromZDW_Base::outputMetadataToStdOut() const
{
return outputMetadata(stdout);
}
//****************************************************
ERR_CODE UnconvertFromZDW_Base::outputMetadata(FILE *out) const
{
const set<string>& keys = this->metadataOptions.keys;
//Filter output set
set<string> outKeys;
set<string>::const_iterator it;
for (it = keys.begin(); it != keys.end(); ++it)
{
if (!this->metadataOptions.bAllowMissingKeys &&
this->metadata.find(*it) == this->metadata.end())
{
return METADATA_KEY_NOT_PRESENT;
}
outKeys.insert(*it);
}
//Output metadata keys
map<string, string>::const_iterator m_it;
if (outKeys.empty()) {
for (m_it = this->metadata.begin(); m_it != this->metadata.end(); ++m_it) {
if (this->metadataOptions.bOnlyMetadataKeys) {
fprintf(out, "%s\n", m_it->first.c_str());
} else {
fprintf(out, "%s=%s\n", m_it->first.c_str(), m_it->second.c_str());
}
}
} else {
for (it = outKeys.begin(); it != outKeys.end(); ++it) {
if (this->metadataOptions.bOnlyMetadataKeys) {
fprintf(out, "%s\n", it->c_str());
} else {
m_it = this->metadata.find(*it);
fprintf(out, "%s=%s\n", it->c_str(), (m_it != this->metadata.end()) ? m_it->second.c_str() : "");
}
}
}
return OK;
}
//****************************************
void UnconvertFromZDW_Base::cleanupBlock()
{
//Deinit for this block.
for (size_t i = 0; i < this->dictionary.size(); ++i)
delete[] this->dictionary[i];
delete[] this->uniques;
delete[] this->visitors;
delete[] this->columnSize;
delete[] this->setColumns;
delete[] this->columnBase;
delete[] this->columnVal;
this->dictionary.clear();
this->dictionary_memblock_size.clear();
this->uniques = NULL;
this->visitors = NULL;
this->columnSize = NULL;
this->setColumns = NULL;
this->columnBase = NULL;
this->columnVal = NULL;
}
//****************************************************
ERR_CODE UnconvertFromZDW_Base::parseBlockHeader()
{
assert(this->dictionary.empty());
assert(this->dictionary_memblock_size.empty());
assert(!this->uniques);
assert(!this->visitors);
assert(!this->columnSize);
assert(!this->setColumns);
assert(!this->columnBase);
assert(!this->columnVal);
assert(sizeof(UCHAR) == 1);
assert(sizeof(USHORT) == 2);
readLineLength();
readDictionary();
readColumnFieldStats();
this->rowsRead = 0;
return OK;
}
void UnconvertFromZDW_Base::readLineLength()
{
if (this->version >= 3)
{
//Each block stores this header info.
readBytes(&this->numLines, 4);
if (this->version >= 6) {
assert(sizeof(this->exportFileLineLength) == 4);
readBytes(&this->exportFileLineLength, 4);
} else {
// Before version 6, the format only allowed a 2-byte length field.
// So, we're reading the 2-byte field
// and storing it in the properly sized variable.
USHORT t_version;
readBytes(&t_version, 2);
this->exportFileLineLength = t_version;
}
readBytes(&this->lastBlock, 1);
if (this->exportFileLineLength > DEFAULT_LINE_LENGTH)
{
delete[] this->row;
this->row = new char[this->exportFileLineLength];
}
}
if (this->bShowBasicStatisticsOnly) {
this->statusOutput(INFO, "Max line length = %lu\n", static_cast<long unsigned>(this->exportFileLineLength));
}
}
void UnconvertFromZDW_Base::readDictionary()
{
UCHAR indexSize;
//Read byte size of the index values.
this->dictionarySize = 0;
readBytes(&indexSize, 1);
if (indexSize != 0) //0 size indicates no values to read in
{
indexBytes sb;
sb.n = 0;
readBytes(sb.c, indexSize);
this->dictionarySize = sb.n;
}
//Read dictionary.
if (this->version >= 9) {
if (!this->bQuiet)
this->statusOutput(INFO, "Reading %" PF_LLU " byte dictionary\n", this->dictionarySize);
if (this->bShowBasicStatisticsOnly) {
skipBytes(this->dictionarySize);
} else {
//Create large dictionary as smaller memory chunks to work around memory fragmentation.
const size_t MAX_DICTIONARY_CHUNK = 500000000; //500M -- should be much larger than any single possible entry
const size_t numChunks = size_t(ceil(this->dictionarySize / float(MAX_DICTIONARY_CHUNK)));
this->dictionary.reserve(numChunks);
this->dictionary_memblock_size.reserve(numChunks);
ULONGLONG sizeLeft = this->dictionarySize;
while (sizeLeft > MAX_DICTIONARY_CHUNK) {
readDictionaryChunk(MAX_DICTIONARY_CHUNK);
sizeLeft -= MAX_DICTIONARY_CHUNK;
}
readDictionaryChunk(sizeLeft);
}
} else {
if (!this->bShowBasicStatisticsOnly) {
this->uniques = new UniquesPart[this->dictionarySize + 1];
memset(this->uniques, 0, (this->dictionarySize + 1) * sizeof(UniquesPart));
}
if (!this->bQuiet)
this->statusOutput(INFO, "Reading %" PF_LLU " uniques\n", this->dictionarySize);
if (this->bShowBasicStatisticsOnly) {
//Just skip through this data.
skipBytes(this->dictionarySize * (BLOCKSIZE + indexSize));
} else {
const ULONG OUTPUT_MOD = 1000000;
this->uniques[0].m_Char.n = 0;
this->uniques[0].m_PrevChar.n = 0;
unsigned int c;
for (c = 1; c <= this->dictionarySize; c++)
{
readBytes(this->uniques[c].m_Char.c, BLOCKSIZE);
readBytes(this->uniques[c].m_PrevChar.c, indexSize);
if (this->bShowStatus && !(c % OUTPUT_MOD))
{
this->statusOutput(INFO, "\r%u", c - 1);
}
}
if (this->bShowStatus && indexSize != 0)
this->statusOutput(INFO, "\r%u\n", c - 1);
}
}
readVisitorDictionary();
}
void UnconvertFromZDW_Base::readDictionaryChunk(const size_t size)
{
if (!size)
return;
//With multiple memory chunks,
//stitch any final partial entry in the previous chunk onto the front of this chunk
//to create an unbroken string.
const char *textToStitch = NULL;
size_t bytesToStitch = 0;
const size_t numChunks = this->dictionary.size();
if (numChunks) {
const size_t prevChunk = numChunks - 1;
const char *endOfBlock = this->dictionary[prevChunk] + this->dictionary_memblock_size[prevChunk] - 1;
textToStitch = endOfBlock;
while (*textToStitch)
--textToStitch;
bytesToStitch = endOfBlock - textToStitch;
++textToStitch; //stitch after null terminator, i.e., residual after last complete entry
}
char *chunk = new char[size + bytesToStitch];
if (bytesToStitch) {
//Move partial entry from end of previous block to new block.
strcpy(chunk, textToStitch);
this->dictionary_memblock_size[numChunks - 1] -= bytesToStitch;
}
try {
readBytes(chunk + bytesToStitch, size);
} catch (ZDWException &ex) {
delete[] chunk;
throw;
}
this->dictionary.push_back(chunk);
this->dictionary_memblock_size.push_back(size + bytesToStitch);
}
void UnconvertFromZDW_Base::readVisitorDictionary()
{
if (this->version < 8)
{
UCHAR vIndexSize;
//Read byte size of visitor IDs.
this->numVisitors = 0;
readBytes(&vIndexSize, 1);
if (vIndexSize != 0) //0 size indicates no values to read in
{
indexBytes sb;
sb.n = 0;
readBytes(sb.c, vIndexSize);
this->numVisitors = sb.n;
}
this->visitors = new VisitorPart[this->numVisitors + 1];
memset(this->visitors, 0, (this->numVisitors + 1) * sizeof(VisitorPart));
if (!this->bQuiet)
this->statusOutput(INFO, "Reading %" PF_LLU " visitor indices\n", this->numVisitors);
//Read visitor IDs
if (this->bShowBasicStatisticsOnly) {
//Just skip through this data.
skipBytes(this->numVisitors * (8 + vIndexSize));
} else {
const ULONG OUTPUT_MOD = 1000000;
this->visitors[0].m_VID = 0;
this->visitors[0].m_PrevID.n = 0;
unsigned int c;
for (c = 1; c <= this->numVisitors; c++)
{
readBytes(&(this->visitors[c].m_VID), 8);
readBytes(this->visitors[c].m_PrevID.c, vIndexSize);
if (this->bShowStatus && !(c % OUTPUT_MOD))
{
this->statusOutput(INFO, "\r%u", c - 1);
}
}
if (this->bShowStatus && vIndexSize != 0)
this->statusOutput(INFO, "\r%u\n", c - 1);
}
}
}
void UnconvertFromZDW_Base::readColumnFieldStats()
{
this->columnSize = new UCHAR[this->numColumns];
readBytes(this->columnSize, this->numColumnsInExportFile);
this->columnBase = new ULONGLONG[this->numColumns];
ULONG numColumnsUsedFromExportFile = 0;
for (unsigned int c = 0; c < this->numColumnsInExportFile; ++c)
{
if (this->columnSize[c])
{
readBytes(this->columnBase + c, 8);
++numColumnsUsedFromExportFile;
} else {
this->columnBase[c] = 0;
}
}
assert(numColumnsUsedFromExportFile <= this->numColumnsInExportFile);
this->numSetColumns = static_cast<long>(ceil(numColumnsUsedFromExportFile / 8.0));
this->setColumns = new unsigned char[this->numSetColumns];
this->columnVal = new storageBytes[this->numColumns];
memset(this->columnVal, 0, this->numColumns * sizeof(storageBytes));
if (UseVirtualExportBaseNameColumn()) {
// This causes the VIRTUAL_EXPORT_FILE_BASENAME column to fall through to the default value
// code path. That is where we actually update the column value. See outputDefault(...)
this->columnSize[this->indexForVirtualBaseNameColumn] = 0;
this->columnBase[this->indexForVirtualBaseNameColumn] = 0;
}
if (UseVirtualExportRowColumn()) {
// This causes the VIRTUAL_EXPORT_ROW column to fall through to the default value
// code path. That is where we actually update the column value. See outputDefault(...)
this->columnSize[this->indexForVirtualRowColumn] = 0;
this->columnBase[this->indexForVirtualRowColumn] = 0;