/
SuperFlexDbArchiver.scala
1212 lines (984 loc) · 49.8 KB
/
SuperFlexDbArchiver.scala
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
/*
* Distributed as part of superflex v0.2.0
*
* Copyright (C) 2013 Machinery For Change, Inc.
*
* Author: Steve Waldman <swaldman@mchange.com>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of EITHER:
*
* 1) The GNU Lesser General Public License (LGPL), version 2.1, as
* published by the Free Software Foundation
*
* OR
*
* 2) The Eclipse Public License (EPL), version 1.0
*
* You may choose which license to accept if you wish to redistribute
* or modify this work. You may offer derivatives of this work
* under the license you have chosen, or you may provide the same
* choice of license which you have been offered here.
*
* This software 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.
*
* You should have received copies of both LGPL v2.1 and EPL v1.0
* along with this software; see the files LICENSE-EPL and LICENSE-LGPL.
* If not, the text of these licenses are currently available at
*
* LGPL v2.1: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* EPL v1.0: http://www.eclipse.org/org/documents/epl-v10.php
*
*/
package com.mchange.sc.v1.superflex;
import java.io.{File, FileInputStream, InputStreamReader, BufferedReader, IOException};
import java.sql.{Connection,DriverManager,PreparedStatement,SQLException,Statement,Types};
import java.text.{ParseException,SimpleDateFormat};
import com.mchange.v2.csv.CsvBufferedReader;
import scala.collection._;
import scala.collection.mutable.ArrayBuffer;
import com.mchange.sc.v1.util.ClosableUtils._;
import com.mchange.sc.v1.sql.ResourceUtils._;
import scala.language.reflectiveCalls;
object SuperFlexDbArchiver {
val dfltDateFormatPatterns = Array("yyyy-MM-dd", "yyyyMMdd", "MMddyyyy", "dd-MMM-yyyy", "dd-MMM-yy", "MM/dd/yy", "MM/dd/yyyy", "ddMMMyyyy");
val dfltDateTimeFormatPatternAddenda = Array("'T'HH:mm:ss");
val dfltDateTimeFormatPatterns = for (p <- dfltDateFormatPatterns; sfx <- dfltDateTimeFormatPatternAddenda) yield (p + sfx);
// to distinguish dates from datetimes, since datetime patterns are
// succeeding when only the prefix date matches, leading to timestamp
// cols where we want dates
val extraDateValidator = new Function2[String,String,Boolean] {
def apply(maybeDate : String, patternStr : String) : Boolean = {
def countColons(s : String) : Int = s.filter( _ == ':').length
return ( countColons( maybeDate ) == countColons( patternStr ) );
}
}
// lowercase only! -- we lowercase values before trying to match with these strings.
val trueStrings = "true"::"t"::"yes"::"y"::"1"::Nil;
val falseStrings = "false"::"f"::"no"::"n"::"0"::Nil;
val leadingZerosRegex = "0\\d".r;
type MetaData = Map[String,List[String]];
trait NamedDataFileSource {
def createBufferedReader( bufferSize : Int, fileEncoding : String ) : BufferedReader;
def sourceName : String;
override def equals( other : Any ) : Boolean;
override def hashCode() : Int;
}
object FileDataFileSource {
def apply( fileName : String ) : FileDataFileSource = new FileDataFileSource( new File( fileName ) );
def apply( file : File ) : FileDataFileSource = new FileDataFileSource( file );
abstract class Base( val f : File, fullpath : Boolean = true ) extends NamedDataFileSource {
def createBufferedReader( bufferSize : Int, fileEncoding : String ) : BufferedReader = { new BufferedReader( new InputStreamReader( new FileInputStream( f ), fileEncoding ), bufferSize ) };
def sourceName : String = { if (fullpath) f.getCanonicalPath(); else f.getName(); }
override def equals( other : Any ) : Boolean = {
other match {
case (o : FileDataFileSource) if this.getClass == other.getClass => this.f == o.f;
case _ => false;
}
}
override def hashCode() : Int = f.hashCode() + 3;
}
}
final class FileDataFileSource( f : File, fullpath : Boolean = true ) extends FileDataFileSource.Base( f, fullpath );
/**
* Necessary to support CSV files tha contain quoted multiline entries
*/
object CsvFileDataFileSource {
def apply( fileName : String ) : CsvFileDataFileSource = new CsvFileDataFileSource( new File( fileName ) );
def apply( file : File ) : CsvFileDataFileSource = new CsvFileDataFileSource( file );
}
final class CsvFileDataFileSource( f : File, fullpath : Boolean = true ) extends FileDataFileSource.Base( f, fullpath ) {
override def createBufferedReader( bufferSize : Int, fileEncoding : String ) : BufferedReader = new CsvBufferedReader( super.createBufferedReader( bufferSize, fileEncoding ) )
}
def dfltColSort( pkNames : List[String] ) : Ordering[String] = new Ordering[String] {
def compare( t : String, o : String ) = oldDfltColSort( pkNames )( t ).compare( o )
}
def oldDfltColSort( pkNames : List[String] )( cn : String) : Ordered[String] = {
new Ordered[String] {
def compare( other : String ) : Int = {
val tpki = pkNames.indexOf( cn );
val opki = pkNames.indexOf( other );
if ( tpki >= 0 && opki >= 0) {
if (tpki > opki) 1;
else if (tpki < opki) -1;
else 0;
} else if (tpki >= 0) -1;
else if (opki >=0) 1;
else cn.compareTo( other );
}
}
}
def asBoolean( maybeBoolean : String) : Option[Boolean] = {
val chk = maybeBoolean.toLowerCase;
if ( trueStrings.contains( chk ) ) Some(true);
else if ( falseStrings.contains( chk ) ) Some(false);
else None;
}
//should only be called on valid, non-null booleans, so use of Option.get should effectively be guarded
val booleanSetter = ( (ps : PreparedStatement, i : Int, s: String) => ps.setBoolean(i, asBoolean(s).get ) );
val charTypeSetter = ( (ps : PreparedStatement, i : Int, s: String) => ps.setString(i, s ) );
val integerSetter = ( (ps : PreparedStatement, i : Int, s: String) => ps.setInt(i, Integer.parseInt(s)) );
val bigintSetter = ( (ps : PreparedStatement, i : Int, s: String) => ps.setLong(i, java.lang.Long.parseLong(s)) );
val doublePrecisionSetter = ( (ps : PreparedStatement, i : Int, s: String) => ps.setDouble(i, java.lang.Double.parseDouble( s ) ) );
def dateSetter( pattern : String ) = new DateTimeSetter( pattern )
def timestampSetter( pattern : String ) = new DateTimeSetter( pattern )
// each thread should make a copy, as not all setters can be called concurrently
// setters that can be called concurrently will be passed back as "copies".
def copySetter( setter : Function3[PreparedStatement, Int, String, Unit] ) : Function3[PreparedStatement, Int, String, Unit] = {
if ( setter.isInstanceOf[DateTimeSetter] ) setter.asInstanceOf[DateTimeSetter].copy else setter;
}
def copyMaybeSetter( maybeSetter : Option[Function3[PreparedStatement, Int, String, Unit]] ) : Option[Function3[PreparedStatement, Int, String, Unit]] = {
if ( maybeSetter != None )
Some( copySetter( maybeSetter.get ) );
else
None;
}
// ensures that multiple instances are equal while allowing for distinct instances (required
// to avoid synchronization during multithreaded use, as SimpleDateFormat is not thread
// safe). (I'm afraid to use a case class here, 'cuz what if they're intern()ed somehow?
final class DateTimeSetter( val pattern : String ) extends Function3[PreparedStatement,Int,String,Unit] {
val df = new SimpleDateFormat( pattern );
override def apply( ps : PreparedStatement, i : Int, s : String) : Unit = {
try { ps.setDate(i, new java.sql.Date(df.parse( s ).getTime() ) ) }
catch{ case t : Throwable => printf("Pattern %s, Bad datum %s\n", pattern, s); throw t; }
}
override def equals( other : Any ): Boolean = {
other match {
case o : DateTimeSetter => ((this eq o) || (this.pattern == o.pattern));
case _ : Any => false;
}
}
override def hashCode : Int = pattern.hashCode;
def copy = new DateTimeSetter( pattern );
}
case class FkdLine( rawLine : String, transformedLine : String, splitLine : Seq[String], probDesc : String ) {
def xmlSnippet =
<line>
<raw>{ this.rawLine }</raw>
<transformed>{ this.transformedLine }</transformed>
<split>{ this.splitLine.map('"' + _ + '"').mkString(",") }</split>
</line>
};
case class FkdLineKeeper( source : NamedDataFileSource, colNames : List[String], fkdLines : List[FkdLine] ) {
def xmlSnippet =
<datasource>
<sourcename>{ this.source.sourceName }</sourcename>
<colnames>{ this.colNames.map('"' + _ + '"').mkString(",") }</colnames>
<lines>
{ fkdLines.map( _.xmlSnippet ) }
</lines>
</datasource>
}
def unreadableLinesXml( keepers : Iterable[FkdLineKeeper] ) = {
<unreadable-lines>
{ keepers.filter( _.fkdLines.length > 0).map( _.xmlSnippet ) }
</unreadable-lines>
}
object Key {
val COL_NAMES = "colNames";
val LABELS = "labels";
val PROLOGUE = "prologue";
}
val emptyColumnInfoArray = new Array[ColumnInfo](0);
val emptyStringArray = new Array[String](0);
}
// TODO: Add a parameter to limit the number of rows per batch in inserts.
// Currently we treat full files as one batch, which is fast but
// overindulgent of memory.
abstract class SuperFlexDbArchiver extends Splitter {
import SuperFlexDbArchiver._; //bring in unqualified reference to companion objects members
protected val priorTableInfo : TableInfo;
protected val files : Seq[NamedDataFileSource];
protected val debugColumnInspection = false;
protected val concurrentInserts : Boolean = true;
/**
* -1 means unlimited. Only matters if concurrentInserts is true
*/
protected val maxConcurrency : Int = -1;
protected val quoteColNames : Boolean = false;
protected val shouldDrop = false;
//println ("priorTableInfo " + priorTableInfo);
protected val colSort = dfltColSort( if (priorTableInfo.pkNames == None) Nil; else priorTableInfo.pkNames.get );
protected val dateFormatPatterns : Iterable[String] = dfltDateFormatPatterns;
protected val dateTimeFormatPatterns : Iterable[String] = dfltDateTimeFormatPatterns;
protected val defaultTypeDeclaration = ( "INTEGER", Types.INTEGER );
protected val bufferSize = 512 * 1024 * 1024; //500M
protected val fileEncoding = "ISO-8859-1";
protected val tmpTablePfx = "tmp_";
protected val leadingZerosNonNumeric = true;
// use -1 to treat full files as batches, irrespective of size
protected val maxBatchSize = 50000;
// if true, read will die with an exception if there are unreadable lines
// if false, bad lines will be retained for logging / correcting, and then skipped
protected val strict = true;
protected val mustInfer : Boolean = true;
protected def transformColName( colName : String ) : String = colName;
protected def readMetaData( br: BufferedReader ) : MetaData;
protected def isNull( datum : String, colName : String ) : Boolean = (datum == null || datum.length == 0);
protected def readDataLine( br : BufferedReader ) : String = br.readLine();
/**
* Note -- this method will only be called if quoteColNames is
* overridden to true.
*/
protected def quoteColName( colName : String ) = '"' + colName + '"';
// we need users to set transformation and quoting conventions distinctly,
// because we do not want to quote when we index columns. So the
// combined method is final.
private final def transformQuoteColName( colName : String ) : String = {
var out = transformColName( colName );
if ( quoteColNames )
out = quoteColName( out );
out;
}
/**
* if table structure inference is disabled, then the synthetic columns must be fully specified. Otherwise, you can use nameOnlyColumnInfos(...) below.
*/
protected def syntheticColumns( f : NamedDataFileSource, colNames : Seq[String] ) : Array[ColumnInfo] = emptyColumnInfoArray;
protected def syntheticColumnValues( data : Array[String], f : NamedDataFileSource, colNames : Seq[String] ) : Array[String] = emptyStringArray;
/**
* Just a utility for specifying synthetic columns whose type should be inferred like "natural" columns
*/
protected final def nameOnlyColumnInfos( names : String* ) : Array[ColumnInfo] = names.map( ColumnInfo( _, None, None, None, None ) ).toArray;
/**
* when overriding, place the super.prepareTransformDataLines() in out._1, and your own info in out._2.
*
* super.prepareTransformDataLines() must always be called, as SuperFlexDbArchiver uses prepare / transform methods. They are not just hooks.
*
* Note -- any class that overrides prepare/prepareTransform method must override ALL THREE to pass
* the left side of the prepObj pair to and or call the superclass method.
*/
protected def prepareTransformFileData( f : NamedDataFileSource, colNames : Array[String] ) : Tuple2[Any,Any] = Tuple2( f, colNames );
/**
* when overriding, get the parent class' line using super.prepareTransformUnsplitDataLine( prepObj._1 ), and retrieve
* your own info from prepObj._2
*
* super.transformUnsplitDataLines() must always be called, as SuperFlexDbArchiver uses prepare / transform methods. They are not just hooks.
*
* Note -- any class that overrides prepare/prepareTransform method must override ALL THREE to pass
* the left side of the prepObj pair to and or call the superclass method.
*/
protected def transformUnsplitDataLine( line : String, prepInfo : Tuple2[Any,Any] ) : String = line;
/**
* when overriding, get the parent class' line using super.transformUnsplitDataLine( prepObj._1 ), and retrieve
* your own info from prepObj._2
*
* super.transformSplitData() must always be called, as SuperFlexDbArchiver uses prepare / transform methods. They are not just hooks.
*
* Note -- any class that overrides prepare/prepareTransform method must override ALL THREE to pass
* the left side of the prepObj pair to and or call the superclass method.
*/
protected def transformSplitData( data : Array[String], prepInfo : Tuple2[Any,Any] ) : Array[String] = {
val ( f, colNames ) = prepInfo.asInstanceOf[Tuple2[NamedDataFileSource,Array[String]]];
val synthCols = syntheticColumns( f, colNames );
val sz = synthCols.size;
if (sz == 0) data;
else {
val synthData = syntheticColumnValues( data, f, colNames );
val out = new Array[String]( data.length + sz );
// printf("colNames: %s\n", colNames.mkString("[ ", ", "," ]"));
// printf("synthCols.size: %s, synthData.size %s\n", synthCols.size.toString, synthData.size.toString);
System.arraycopy(data, 0, out, 0, data.length );
System.arraycopy(synthData, 0, out, data.length, sz);
out;
}
}
protected def afterTableCreate( con : Connection ) : Unit = {};
protected def afterRowInsert( con : Connection, data : Array[String], f : NamedDataFileSource, colNames : Seq[String] ) : Unit = {};
protected def afterAllInserts( csrc : ConnectionSource ) : Unit = {};
/**
* Can be set to override the usual inference process for a
* given column. The return value is the SQL type that should be
* declared and the java.sql.Types code it should be associated
* with. Returning None means to use the usual inference
* process.
*/
protected def forceInferredType( colName : String, maxLength : Int ) : Option[Tuple2[String,Int]] = None;
// we let this be a def, because we'll find it convenient to let this depend
// on the column count sometimes in order to work around a postgres bug.
//
// search the pg-sql mailing list for threads
// "Deadlock detection"
// "Connection hanging on INSERT apparently due to large batch size and 4 CPU cores"
// "deadlocks on JDBC batch inserts into tables with many columns"
//
// note that table insepction has completed by the time this "parameter" is accessed,
// so we can check, e.g. _unifiedNamesToColInfos
//
protected def batchFileInserts : Boolean = true;
/** throw an Exception if not valid */
protected def validateMetaData( mds : MetaData) : Unit = {}
protected def padFieldLength( observedMaxLength : Int) : Int = observedMaxLength;
// Note: this object imposes the sort that will determine the ordering of columns
protected object FilesInfo {
// note that synth columns are always appended to "natural" file columns in the
// order they are presented by syntheticColNames. parse and insepction should
// supply synthetic values appropriately
def apply( metaDatas : Array[MetaData] ) : FilesInfo = {
val allColNames = mutable.Set.empty[String];
val colNamesByFile = mutable.HashMap.empty[NamedDataFileSource, Array[String]];
for (i <- 0 until files.length) {
val fileColNames = metaDatas(i)( Key.COL_NAMES ).toArray;
val synthCols = syntheticColumns( files(i), fileColNames );
val synthColNames = synthCols.map( _.name );
val fileSynthColNames = fileColNames ++ synthColNames;
//printf( "fileSynthColNames %s", fileSynthColNames.mkString("[ ", ", ", " ]") );
allColNames ++= fileSynthColNames;
colNamesByFile += ( files(i) -> fileSynthColNames.toArray );
}
val fcbcn = mutable.Map.empty[String, Iterable[(NamedDataFileSource, Int)]] ++
( for ( cn <- allColNames ) yield ( Tuple2(cn, for (f <- files; fcn = colNamesByFile(f).indexOf( cn ); if fcn >= 0) yield ( f, fcn ) ) ) );
new FilesInfo( allColNames, colNamesByFile, fcbcn, colSort );
}
}
protected class FilesInfo( cnames : Iterable[String],
cnbf : Map[NamedDataFileSource,Array[String]],
fcbcn : Map[String, Iterable[(NamedDataFileSource, Int)]],
sort : Ordering[String] ) {
val allColumnNames : SortedSet[String] = immutable.TreeSet.empty(sort) ++ cnames;
val colNamesByFile : Map[NamedDataFileSource, Array[String]] = immutable.HashMap.empty ++ cnbf;
val fileColsByColumnName : SortedMap[String, Iterable[ (NamedDataFileSource, Int) ] ] = immutable.TreeMap.empty(sort) ++ fcbcn;
}
/**
* An empty String, rather than a None value, signifies no prologues
*/
private def mergePrologues(metaDatas : Array[MetaData]) : String = {
// XXX hardcoded 8k buffer
val sb : StringBuilder = new StringBuilder(8192);
for (i <- 0 until metaDatas.length; prologue = metaDatas(i).getOrElse(Key.PROLOGUE, null); if (prologue != null)) {
assert( prologue.length == 1, "Prologues should be parsed to a single string (the first value of the metadata List." );
sb.append( "Source file: ");
sb.append( files(i).sourceName );
sb.append(':');
sb.append("\n");
sb.append( prologue(0).trim() );
sb.append( "\n" );
}
sb.toString();
}
// if label vals would be interpreted as nulls in data, they
// are interpreted as nulls here
protected def createLabelMap(md : MetaData, file : NamedDataFileSource) : Option[Map[String,String]] = {
val colNames : Option[List[String]] = md.get( Key.COL_NAMES );
val labels : Option[List[String]] = md.get( Key.LABELS );
if (colNames == None || labels == None) {
None;
} else if (colNames.get.length == labels.get.length) {
val cng = colNames.get;
val lg = labels.get;
val pairs : Seq[ (String, String) ] = for (i <- 0 until cng.length; if (! isNull(lg(i), cng(i)))) yield Tuple2( cng(i), lg(i) );
val synthPairs = {
val synthCols = syntheticColumns( file, cng );
for ( ci <- synthCols; label = ci.label.getOrElse( null ); if (! isNull( label, ci.name ) ) ) yield ( ci.name, label );
};
Some( immutable.Map( (pairs ++ synthPairs) : _* ) );
} else {
printf("Uh oh... length of colNames and labels lists don't match. Reporting no labels.\n");
None;
}
}
/**
* An empty map, rather than a None value, signifies no labels
*/
protected def findLabels(metaDatas : Array[MetaData], files : Seq[NamedDataFileSource]) : Map[String,String] = {
val labelMaps = for (i <- 0 until metaDatas.length) yield ( createLabelMap( metaDatas(i), files(i) ) );
val goodLabelMaps = labelMaps.filter( _ != None ).map( _.get );
val bindingsUnion : Set[Tuple2[String,String]] = goodLabelMaps.foldLeft( immutable.Set.empty[Tuple2[String,String]] )( _ ++ _ );
// merge duplicate values
val keySet : Set[String] = immutable.Set( bindingsUnion.map( _._1 ).toSeq : _* );
val outBuilder = mutable.Map.empty[String,String];
for ( k <- keySet ) {
outBuilder += Tuple2( k , bindingsUnion.filter( _._1 == k ).map( _._2 ). mkString(" || ") );
}
return immutable.Map.empty ++ outBuilder;
}
// these options all get filled in sequence
// it is safe to assume they have values if the function
// that fills in the data has been called
//
// however some vals (empty strings, empty maps) may signify
// unknown or null
protected var _metaDatas : Option[Array[MetaData]] = None;
protected var _labels : Option[Map[String,String]] = None; //empty if unknown
protected var _mergedPrologues : Option[String] = None; //"" if no prologues provided
protected var _filesInfo : Option[FilesInfo] = None;
protected var _unifiedTableInfo : Option[TableInfo] = None;
protected var _unifiedNamesToColInfos : Option[Map[String,ColumnInfo]] = None;
protected var _maybeQualifiedTableName : Option[String] = None;
protected var _createDdl : Option[String] = None;
protected var _fkdLineKeepers : Option[Map[NamedDataFileSource,FkdLineKeeper]] = None;
// pkConstraint need NOT be filled in, if the table being
// generated has specified no primary key fields. calls
// to get should always be guarded.
protected var _pkConstraint : Option[String] = None;
def archiveFiles( csrc : ConnectionSource ) : Unit = {
inferTableInfo();
generateCreateDdl();
if (shouldDrop) dropDeindexTable( csrc );
executeCreateDdl( csrc );
insertFiles( csrc );
}
def archiveFilesNoDups( csrc : ConnectionSource ) : Unit = archiveFilesNoDups( csrc, true );
def archiveFilesNoDups( csrc : ConnectionSource, imposePkConstraint : Boolean ) : Unit = {
inferTableInfo();
// asserts that _values are set during inference
val maybeQualifiedTableName = _maybeQualifiedTableName.get;
val unifiedTableInfo = _unifiedTableInfo.get;
val tmpTableName = {
if (unifiedTableInfo.tschema == None ) {
tmpTablePfx + maybeQualifiedTableName; //schema-less case
} else {
unifiedTableInfo.tschema.get + '.' + tmpTablePfx + unifiedTableInfo.tname.get;
}
}
printf("tmpTableName: %s\n", tmpTableName);
// if for some reason there is an old shadow of the tempory table,
// drop it
dropTable( csrc, tmpTableName );
generateCreateDdl( false, tmpTableName );
executeCreateDdl( csrc, tmpTableName );
insertFiles( csrc, this.files, _filesInfo.get, concurrentInserts, tmpTableName );
if ( shouldDrop ) dropDeindexTable(csrc);
var con : Connection = null;
var stmt : Statement = null;
try {
con = csrc.getConnection();
stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE %s AS ( SELECT DISTINCT * FROM %s )".format(maybeQualifiedTableName, tmpTableName));
stmt.executeUpdate("DROP TABLE %s".format(tmpTableName));
if ( imposePkConstraint ) {
if ( _pkConstraint != None) stmt.executeUpdate("ALTER TABLE %s ADD %s".format( maybeQualifiedTableName, _pkConstraint.get ));
else println("Could not impose PRIMARY KEY constraint on generated table. No PRIMARY KEY columns specified.");
}
} finally {
attemptClose( stmt, con );
}
}
def dropDeindexTable( csrc : ConnectionSource ) : Unit = dropTable( csrc );
protected def prologuesDefined() : Boolean = {
// should only be called after inference is complete. effectively asserts...
_mergedPrologues.get.length > 0;
}
final def dropTable( csrc : ConnectionSource ) : Unit = {
withConnection( csrc ) { con =>
withStatement( con ) { stmt =>
dropTable( stmt );
}
}
}
final def dropTable( csrc : ConnectionSource, mqtn : String ) : Unit = {
withConnection( csrc ) { con =>
withStatement( con ) { stmt =>
dropTable( stmt, mqtn );
}
}
}
final def dropTable( stmt : Statement ) : Unit = {
// effectively asserts that _maybeQualifiedTableName has been set
val maybeQualifiedTableName = _maybeQualifiedTableName.get;
dropTable( stmt, maybeQualifiedTableName );
}
final def dropTable(stmt : Statement, mqtn : String) : Unit = {
try { stmt.executeUpdate("DROP TABLE %s".format(mqtn)); }
catch { case (exc : SQLException) => ; } //ignore, assume table wasn't there
}
private def learnFromMetaDatas() : Unit = {
if ( _metaDatas == None ) readAllMetaDatas();
val metaDatas = _metaDatas.get;
if ( _filesInfo == None ) _filesInfo = Some( FilesInfo( metaDatas ) );
val filesInfo = _filesInfo.get;
val labels : Map[String,String] = findLabels( metaDatas, files );
this._labels = Some( labels );
this._mergedPrologues = Some( mergePrologues( metaDatas ) );
}
private def learnFromUnifiedTableInfo() : Unit = {
//println( "getting unified table info");
// effectively asserts that _unifiedTableInfo has been set
val unifiedTableInfo = _unifiedTableInfo.get;
val unifiedNamesToColInfos = immutable.TreeMap[String,ColumnInfo]()(colSort) ++ unifiedTableInfo.cols.get.map( ci => (ci.name -> ci) ); //sorted
this._unifiedNamesToColInfos = Some( unifiedNamesToColInfos );
if (unifiedTableInfo.pkNames != None) {
val pkeyExtras = unifiedTableInfo.pkNames.get.filterNot( unifiedNamesToColInfos.keySet.contains(_) );
if (! pkeyExtras.isEmpty )
throw new DbArchiverException("Column names specified as primary keys don't exist in the inferred or specified table. Unknown primary keys: " + pkeyExtras.mkString(", ") );
}
this._maybeQualifiedTableName = {
if (unifiedTableInfo.tschema == None) unifiedTableInfo.tname else Some( unifiedTableInfo.tschema.get + '.' + unifiedTableInfo.tname.get )
}
}
private def inferTableInfo(): Unit = {
if (priorTableInfo.tname == None)
throw new DbArchiverException("A table name must be specified in priorTableInfo. Currently: " + priorTableInfo);
if (mustInfer) {
learnFromMetaDatas();
val metaDatas = _metaDatas.get;
val filesInfo = _filesInfo.get;
val labels = _labels.get;
// this has the side effect of setting up _fkdLineKeepers
val inferredColMap : Map[ NamedDataFileSource, Seq[ExaminedColumn] ] = inferFileCols( filesInfo );
val inferredCols : SortedMap[String, ExaminedColumn] = {
immutable.TreeMap.empty[String, ExaminedColumn]( colSort ) ++
( for ( cn <- filesInfo.allColumnNames ) yield cn -> (filesInfo.fileColsByColumnName( cn ).map( fc => inferredColMap( fc._1 ).apply(fc._2) ) ).reduceLeft( _ && _ ) );
}
val inferredColInfos = inferredCols.map( tup => new ColumnInfo(tup._1,
if (labels == None || ! labels.contains(tup._1)) None; else Some( labels(tup._1) ),
Some(tup._2.bestTypeDeclaration._1),
Some(tup._2.bestTypeDeclaration._2),
Some(tup._2.setter) ) ).toSeq;
val inferredTableInfo = new TableInfo( None, None, Some(inferredColInfos), None ); // name and any schema or pkeys should be set on priorTableInfo
// unified table info will contain information about synthetic colums by inference (they were included in filesInfo)
val unifiedTableInfo = priorTableInfo.reconcileOver( inferredTableInfo );
//val unifiedTableInfo = TableInfo( priorTableInfo.tschema, priorTableInfo.tname, Some( allColSeq ), priorTableInfo.pkNames );
this._unifiedTableInfo = Some( unifiedTableInfo );
//printf("unifiedTableInfo: %s\n", unifiedTableInfo);
learnFromUnifiedTableInfo();
val unifiedNamesToColInfos = _unifiedNamesToColInfos.get;
val extraCols = immutable.Set(unifiedNamesToColInfos.keySet.toSeq : _*) -- filesInfo.allColumnNames;
if (! extraCols.isEmpty )
throw new DbArchiverException("Information is specified (via priorTableInfo) about columns not in the data. Extras: " + extraCols.mkString(", "));
} else {
// we still have to make sure all the member variables that
// would normally have been filled by inspection get filled.
learnFromMetaDatas();
// we still need to infer what synth columns will be required
// metaDatas was set above
val metaDatas = _metaDatas.get;
val synthCols = {
val fileSynthCols = for (i <- 0 until metaDatas.length) yield syntheticColumns( files(i), metaDatas(i).apply( Key.COL_NAMES ) );
val tmp = mutable.Map.empty[String, ColumnInfo];
for ( fileseq <- fileSynthCols; ci <- fileseq ) {
val check = tmp.get( ci.name );
if (check != None) {
tmp += ( ci.name -> check.get.reconcile( ci ));
} else {
tmp += ( ci.name -> ci );
}
}
tmp.map( _._2 );
};
if (synthCols.isEmpty) {
this._unifiedTableInfo = Some( priorTableInfo );
} else {
this._unifiedTableInfo = Some( priorTableInfo.reconcileOver( TableInfo( None, None, Some(synthCols), None ) ) );
}
printf("priorTableInfo: %s\n", priorTableInfo);
printf("set table info: %s\n", this._unifiedTableInfo);
learnFromUnifiedTableInfo();
this._fkdLineKeepers = Some( createEmptyFkdLineKeepers() );
}
}
// for when we are skipping inference and fully specifying the expected table structure
// in this case, we don't have the opportunity to pre-inspect files for bad records
private def createEmptyFkdLineKeepers() : Map[NamedDataFileSource,FkdLineKeeper] =
{ immutable.Map( files.map( f => ( f, FkdLineKeeper(f, _filesInfo.get.colNamesByFile(f).toList, Nil) ) ) : _* ); }
private def generateCreateDdl() : Unit = generateCreateDdl( true, _maybeQualifiedTableName.get /* asserts _maybeQualifiedTableName set */ );
private def generateCreateDdl( includePkConstraint : Boolean, maybeQualifiedTableName : String ) : Unit = {
val unifiedTableInfo = _unifiedTableInfo.get;
val unifiedNamesToColInfos = _unifiedNamesToColInfos.get;
//printf("In generateCreateDdl( ... ) -- unifiedTableInfo %s\n", unifiedTableInfo);
// XXX: 4096 is hardcoded here...
val sb : StringBuilder = new StringBuilder(4096);
sb.append("CREATE TABLE ");
sb.append( maybeQualifiedTableName );
val decls : List[String] = {
val rawPkColNames = unifiedTableInfo.pkNames;
val noPkDecls = unifiedNamesToColInfos.toList.map( tup => ( transformQuoteColName( tup._2.name ) + " " + tup._2.sqlTypeDecl.get ) );
if (rawPkColNames != None && rawPkColNames.get != Nil) {
val pkConstraint = "PRIMARY KEY( " + rawPkColNames.get.map( transformQuoteColName _ ).mkString(", ") + " )";
this._pkConstraint = Some( pkConstraint );
if (includePkConstraint) {
noPkDecls:::pkConstraint::Nil;
} else {
noPkDecls;
}
} else {
noPkDecls;
}
};
sb.append( decls.mkString(" ( ", ", ", " )") );
_createDdl = Some( sb.toString() );
}
private def executeCreateDdl( csrc : ConnectionSource ) : Unit = {
val maybeQualifiedTableName = _maybeQualifiedTableName.get; // effectively asserts that _maybeQualifiedTableName has been set
executeCreateDdl( csrc, maybeQualifiedTableName );
}
private def executeCreateDdl( csrc : ConnectionSource, maybeQualifiedTableName : String ) : Unit = {
val createDdl = _createDdl.get; // effectively asserts that _createDdl has been set
var con : Connection = null;
var stmt : Statement = null;
try {
con = csrc.getConnection();
stmt = con.createStatement();
// if ( drop )
// {
// printf("Attempting to drop table '%s', if present.\n", maybeQualifiedTableName);
// drop( stmt );
// }
printf("Creating table '%s'.\n", maybeQualifiedTableName);
println( createDdl );
stmt.executeUpdate( createDdl );
afterTableCreate( con );
println("CREATE was executed without exceptions.");
} finally {
attemptClose( stmt, con );
}
}
private def insertFile( csrc : ConnectionSource, f : NamedDataFileSource, filesInfo : FilesInfo ) : Unit = withConnection( csrc ) { insertFile( _, f, filesInfo) }
private def insertFile( csrc : ConnectionSource, f : NamedDataFileSource, filesInfo : FilesInfo, maybeQualifiedTableName : String ) : Unit =
withConnection( csrc ) { insertFile( _, f, filesInfo, maybeQualifiedTableName) }
private def insertFile( con : Connection, f : NamedDataFileSource, filesInfo : FilesInfo ) : Unit = {
// effectively assets that member variables have been set...
var maybeQualifiedTableName = _maybeQualifiedTableName.get;
insertFile( con, f, filesInfo, maybeQualifiedTableName );
}
private def insertFile( con : Connection, f : NamedDataFileSource, filesInfo : FilesInfo, maybeQualifiedTableName : String ) : Unit = {
//printf( "insertFile -- %s\n", f.sourceName );
// effectively assets that member variables have been set...
val unifiedTableInfo = _unifiedTableInfo.get;
val unifiedNamesToColInfos = _unifiedNamesToColInfos.get;
val fkdLineKeepers = _fkdLineKeepers.get;
val myFkdLineKeeper = fkdLineKeepers(f); // there should be one for every file
val myFkdRawLines = immutable.HashSet( myFkdLineKeeper.fkdLines.map( _.rawLine ) : _* );
//printf("%s -- myFkdRawLines\n%s\n", f.sourceName, myFkdRawLines.mkString("\n"));
var skipped : Int = 0;
var br : BufferedReader = null;
var ps : PreparedStatement = null;
try {
val fileColNames = Array[String]( filesInfo.colNamesByFile( f ) : _* );
val psColList = fileColNames.map( transformQuoteColName( _ ) ).mkString("( ", ", ", " )"); // in File order, not table order
val psInsertionPoints = ( (for (fcn <- fileColNames) yield '?').mkString("( ", ", ", " )") );
// generate appropriate data setting functions, mixing inferred with preset columns
val setters = for ( cn <- fileColNames) yield copyMaybeSetter( unifiedNamesToColInfos( cn ).setter ); //not all setters are thread safe... we must copy
val typeCode = for ( cn <- fileColNames) yield unifiedNamesToColInfos( cn ).typeCode;
val insertStmt = String.format("INSERT INTO %s %s VALUES %s", maybeQualifiedTableName, psColList, psInsertionPoints );
//printf("insertStmt: %s\n", insertStmt);
ps = con.prepareStatement( insertStmt );
br = f.createBufferedReader( bufferSize, fileEncoding );
readMetaData( br ); // skip preliminaries...
val prepObj = prepareTransformFileData( f, fileColNames );
var batchCount = 0;
var line = readDataLine( br );
//println("line: " + line);
while ( goodLine( line ) ) {
if (! myFkdRawLines( line ) ) { // if the line is known to be fkd, we don't try to parse, read, and insert it
line = transformUnsplitDataLine( line, prepObj );
val data = transformSplitData( split( line ), prepObj );
/*
printf( "data %s\n", data.mkString("[ ", ", " , " ]") );
printf( "psColList %s\n", psColList );
printf( "psInsertionPoints %s\n", psInsertionPoints );
*/
for (i <- 0 until data.length) {
if ( isNull( data(i), fileColNames(i) ) ) {
ps.setNull( i + 1, typeCode(i).get); // XXX: should guard this get
} else {
try {
setters(i).get.apply(ps, i + 1, data(i)); // XXX: should guard this get, ps slots are indexed by 1, arrays are indexed by zero
} catch {
case e : Exception => {
printf("BAD VALUE: COLUMN %d of\n%s\n",i+1,line);
throw e;
}
}
}
}
// println(ps);
if ( batchFileInserts ) {
ps.addBatch();
batchCount += 1;
if (batchCount == maxBatchSize) {
printf("%s: batch size limit %d reached. executing, then resetting.\n", f.sourceName, batchCount);
ps.executeBatch();
batchCount = 0;
printf("%s: executed batch and reset batch size count.\n", f.sourceName);
}
} else {
ps.executeUpdate();
afterRowInsert( con, data, f, fileColNames );
}
} else {
skipped += 1;
printf("%s: Skipped bad line: %s\n", f.sourceName, line );
}
line = readDataLine( br );
}
if (batchFileInserts) ps.executeBatch();
printf("%s: Skipped %d lines. Expected to skip %d lines.\n", f.sourceName, skipped, myFkdLineKeeper.fkdLines.length);
} catch {
case e : SQLException => { printThrowable(e); throw e; }
} finally {
attemptClose( ps, br );
}
}
def insertFiles(csrc : ConnectionSource) : Unit = {
// effectively asserts that _filesInfo and _maybeQualifiedTableName have been set
insertFiles(csrc, this.files, _filesInfo.get, concurrentInserts, _maybeQualifiedTableName.get );
}
def insertFiles(csrc : ConnectionSource, files : Iterable[NamedDataFileSource], filesInfo : FilesInfo, concurrent : Boolean, maybeQualifiedTableName : String) : Unit = {
if (concurrent) {
val fcn : (NamedDataFileSource) => Option[Throwable] = {
(f : NamedDataFileSource) => {
try { insertFile( csrc, f, filesInfo, maybeQualifiedTableName ); None; }
catch { case (t : Throwable) => { printThrowable(t); Some(t); } };
}
}
files.par.map( fcn );
} else {
withConnection( csrc )( con => files.foreach( insertFile( con, _, filesInfo, maybeQualifiedTableName ) ) )
}
afterAllInserts( csrc );
}
private def printThrowable( t : Throwable ) : Unit = {
if ( t != null ) {
t.printStackTrace();
if ( t.isInstanceOf[SQLException] ) printThrowable( t.asInstanceOf[SQLException].getNextException )
}
}
// XXX: hardcoded 8K starting buffer for headers
private def buildStreams() : Seq[BufferedReader] = {
var buildStreams = new ArrayBuffer[BufferedReader];
try {
for (f <- files) buildStreams += f.createBufferedReader(8192, fileEncoding);
buildStreams.toVector;
} catch {
case ex : Exception => { buildStreams.foreach( attemptClose _ ); throw ex; }
}
}
private def readAllMetaDatas() : Unit = {
val streams = buildStreams();
try {
_metaDatas = Some( for( br <- streams.toArray[BufferedReader] ) yield ( readValidateMetaData( br ) ) );
} finally{
streams.foreach( attemptClose _ );
}
}
private def readValidateMetaData( br : BufferedReader ) : MetaData = {
val out = readMetaData( br );
validateMetaData( out );
out;
}
// as a side effect, sets up _fkdLineKeepers
private def inferFileCols( fi : FilesInfo ) : Map[ NamedDataFileSource, Seq[ExaminedColumn] ] = {
// since synthetic file cols are set up in filesInfo, they will be passed to doInferFile
def doInferFile( f : NamedDataFileSource, colNames : Array[String] ) : (NamedDataFileSource, Seq[ExaminedColumn], FkdLineKeeper) = {
var numCols : Int = colNames.length;
printf("Examining %s, which has %d columns.\n", f.sourceName, numCols);
val br = f.createBufferedReader( bufferSize, fileEncoding );
readMetaData( br ); //skip preliminaries
try {
val (recSeq, flk) = examineColumns( br, colNames, f );
( f, recSeq.map( _.toExaminedColumn), flk )
} finally {
br.close();
}
}
val xformFcn = (pair : Tuple2[NamedDataFileSource,Array[String]]) => { doInferFile( pair._1, pair._2 ) };
//val processor = CollectionProcessor( xformFcn, maxConcurrency );
//val triples = processor.process( files.map( f => (f, fi.colNamesByFile(f)) ) );
val triples = files.par.map( f => (f, fi.colNamesByFile(f)) ).map( xformFcn ).toVector;
val keepers : Map[NamedDataFileSource,FkdLineKeeper] = immutable.Map.empty ++ triples.map( trip => (trip._3.source -> trip._3 ) );
this._fkdLineKeepers = Some( keepers );
val pairs = triples.map( tup => Tuple2(tup._1, tup._2) )
immutable.HashMap( pairs.toSeq : _*);
}
private[SuperFlexDbArchiver] case class ExaminedColumn(val colName : String,
val booleanOnly : Boolean,
val numericOnly : Boolean,
val integerOnly : Boolean,
val fixedLength : Option[Int],
val maxLength : Int, // if maxLength < 0, all known entries of this colum are null
val dateFormatStr : Option[String],
val dateTimeFormatStr : Option[String]) {
def &&( other : ExaminedColumn ) = {
require( this.colName == other.colName );
ExaminedColumn(colName,
this.booleanOnly && other.booleanOnly,
this.numericOnly && other.numericOnly,
this.integerOnly && other.integerOnly,
if (this.fixedLength == other.fixedLength) { fixedLength } else { None },
this.maxLength max other.maxLength,
if (this.dateFormatStr == other.dateFormatStr) { dateFormatStr } else { None },
if (this.dateTimeFormatStr == other.dateTimeFormatStr) { dateTimeFormatStr } else { None } );
}
// XXX: Put all this type crap into some formal enumeration
// TODO: Make this customizable to different databases
val bestTypeDeclaration : Tuple2[String, Int] = {
val forced = forceInferredType( colName, maxLength );
if (forced != None ) {
val out = ( forced.get._1.toUpperCase, forced.get._2 );
assert( ("TIMESTAMP"::"DATE"::"INTEGER"::"BIGINT"::"DOUBLE PRECISION"::"BOOLEAN"::Nil).contains( out._1 ) || out._1.indexOf("CHAR") >= 0,
"Forced column types must be one of 'TIMESTAMP', 'DATE', 'INTEGER', 'BIGINT', 'DOUBLE PRECISION', 'BOOLEAN', or something containg 'CHAR'" );
if (debugColumnInspection) printf("[%s] Column type '%s' was forced by a subclass override.", colName, out._1 );