/
DatabaseWriter.java
1092 lines (976 loc) · 45.7 KB
/
DatabaseWriter.java
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
/*
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU Lesser General Public License (the
* "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* 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 CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jumpmind.symmetric.io.data.writer;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.jumpmind.db.io.DatabaseXmlUtil;
import org.jumpmind.db.model.Column;
import org.jumpmind.db.model.Database;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.platform.IDatabasePlatform;
import org.jumpmind.db.sql.DmlStatement;
import org.jumpmind.db.sql.DmlStatement.DmlType;
import org.jumpmind.db.sql.ISqlTemplate;
import org.jumpmind.db.sql.ISqlTransaction;
import org.jumpmind.db.sql.SqlException;
import org.jumpmind.symmetric.io.data.Batch;
import org.jumpmind.symmetric.io.data.CsvData;
import org.jumpmind.symmetric.io.data.DataContext;
import org.jumpmind.symmetric.io.data.DataEventType;
import org.jumpmind.symmetric.io.data.IDataWriter;
import org.jumpmind.symmetric.io.data.writer.Conflict.DetectConflict;
import org.jumpmind.util.FormatUtils;
import org.jumpmind.util.Statistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bsh.EvalError;
import bsh.Interpreter;
public class DatabaseWriter implements IDataWriter {
protected final static Logger log = LoggerFactory.getLogger(DatabaseWriter.class);
public static enum LoadStatus {
SUCCESS, CONFLICT
};
protected IDatabasePlatform platform;
protected ISqlTransaction transaction;
protected DmlStatement currentDmlStatement;
protected boolean lastUseConflictDetection = true;
protected boolean lastApplyChangesOnly = false;
protected Table sourceTable;
protected Table targetTable;
protected Map<String, Table> targetTables = new HashMap<String, Table>();
protected CsvData lastData;
protected Batch batch;
protected DataContext context;
protected long uncommittedCount = 0;
protected DatabaseWriterSettings writerSettings;
protected Map<Batch, Statistics> statistics = new HashMap<Batch, Statistics>();
protected IDatabaseWriterConflictResolver conflictResolver;
protected Set<String> missingTables = new HashSet<String>();
public DatabaseWriter(IDatabasePlatform platform) {
this(platform, null, null);
}
public DatabaseWriter(IDatabasePlatform platform, DatabaseWriterSettings settings) {
this(platform, null, settings);
}
public DatabaseWriter(IDatabasePlatform platform,
IDatabaseWriterConflictResolver conflictResolver, DatabaseWriterSettings settings) {
this.platform = platform;
this.conflictResolver = conflictResolver == null ? new DefaultDatabaseWriterConflictResolver()
: conflictResolver;
this.writerSettings = settings == null ? new DatabaseWriterSettings() : settings;
}
public void open(DataContext context) {
this.context = context;
this.transaction = platform.getSqlTemplate().startSqlTransaction();
}
public void start(Batch batch) {
this.batch = batch;
this.statistics.put(batch, new Statistics());
}
public boolean start(Table table) {
this.lastData = null;
this.currentDmlStatement = null;
this.sourceTable = table;
this.targetTable = lookupTableAtTarget(table);
if (this.targetTable != null || hasFilterThatHandlesMissingTable(table)) {
String quote = getPlatform().getDatabaseInfo().getDelimiterToken();
this.transaction.allowInsertIntoAutoIncrementColumns(true, this.targetTable, quote);
return true;
} else if (writerSettings.isIgnoreMissingTables()) {
String qualifiedName = sourceTable.getFullyQualifiedTableName();
if (!missingTables.contains(qualifiedName)) {
log.warn("Did not find the {} table in the target database", qualifiedName);
missingTables.add(qualifiedName);
}
return false;
} else {
// The first data should fail because the table will not be found
return true;
}
}
public void write(CsvData data) {
if (targetTable != null ||
data.getDataEventType() == DataEventType.CREATE ||
data.getDataEventType() == DataEventType.SQL) {
try {
statistics.get(batch).increment(DataWriterStatisticConstants.STATEMENTCOUNT);
statistics.get(batch).increment(DataWriterStatisticConstants.LINENUMBER);
if (filterBefore(data)) {
LoadStatus loadStatus = LoadStatus.SUCCESS;
switch (data.getDataEventType()) {
case UPDATE:
loadStatus = update(data, true, true);
break;
case INSERT:
loadStatus = insert(data);
break;
case DELETE:
loadStatus = delete(data, true);
break;
case BSH:
script(data);
break;
case SQL:
sql(data);
break;
case CREATE:
create(data);
break;
default:
break;
}
if (loadStatus == LoadStatus.CONFLICT) {
if (conflictResolver != null) {
conflictResolver.needsResolved(this, data, loadStatus);
} else {
throw new ConflictException(data, targetTable, false);
}
} else {
uncommittedCount++;
}
lastData = data;
filterAfter(data);
checkForEarlyCommit();
}
} catch (IgnoreBatchException ex) {
rollback();
throw ex;
} catch (RuntimeException ex) {
if (filterError(data, ex)) {
throw ex;
} else {
uncommittedCount++;
statistics.get(batch).increment(DataWriterStatisticConstants.IGNORECOUNT);
checkForEarlyCommit();
}
}
} else {
if (sourceTable != null) {
throw new SqlException(String.format("Could not find the target table %s",
sourceTable.getFullyQualifiedTableName()));
} else {
throw new SqlException("The target table was not specified");
}
}
}
protected void checkForEarlyCommit() {
if (uncommittedCount >= writerSettings.getMaxRowsBeforeCommit()) {
notifyFiltersEarlyCommit();
commit();
/*
* Chances are if SymmetricDS is configured to commit early in a
* batch we want to give other threads a chance to do work and
* access the database. This was added to support H2 clients
* that are loading big batches while an application is doing work.
*/
try {
Thread.sleep(5);
} catch (InterruptedException e) {
log.warn("{}", e.getMessage());
}
}
}
protected void commit() {
if (transaction != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
this.transaction.commit();
notifyFiltersBatchCommitted();
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
}
}
uncommittedCount = 0;
}
protected void rollback() {
if (transaction != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
this.transaction.rollback();
notifyFiltersBatchRolledback();
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
}
}
uncommittedCount = 0;
}
protected boolean requireNewStatement(DmlType currentType, CsvData data,
boolean applyChangesOnly, boolean useConflictDetection,
Conflict.DetectConflict detectType) {
boolean requiresNew = currentDmlStatement == null || lastData == null
|| currentDmlStatement.getDmlType() != currentType
|| lastData.getDataEventType() != data.getDataEventType()
|| lastApplyChangesOnly != applyChangesOnly
|| lastUseConflictDetection != useConflictDetection;
if (!requiresNew && currentType == DmlType.UPDATE) {
String currentChanges = Arrays.toString(data.getChangedDataIndicators());
String lastChanges = Arrays.toString(lastData.getChangedDataIndicators());
requiresNew = !currentChanges.equals(lastChanges);
}
if (!requiresNew) {
requiresNew |= containsNullLookupKeyDataSinceLastStatement(currentType, data,
detectType);
}
return requiresNew;
}
protected boolean containsNullLookupKeyDataSinceLastStatement(DmlType currentType,
CsvData data, DetectConflict detectType) {
boolean foundNullValueChange = false;
if (currentType == DmlType.UPDATE || currentType == DmlType.DELETE) {
if (detectType != null
&& (detectType == DetectConflict.USE_CHANGED_DATA || detectType == DetectConflict.USE_OLD_DATA)) {
String[] lastOldData = lastData.getParsedData(CsvData.OLD_DATA);
String[] newOldData = data.getParsedData(CsvData.OLD_DATA);
if (lastOldData != null && newOldData != null) {
for (int i = 0; i < lastOldData.length && i < newOldData.length; i++) {
String lastValue = lastOldData[i];
String value = newOldData[i];
if ((lastValue != null && value == null)
|| (value != null && lastValue == null)) {
foundNullValueChange = true;
}
}
}
} else {
String[] lastpkData = lastData.getParsedData(CsvData.PK_DATA);
String[] newpkData = data.getParsedData(CsvData.PK_DATA);
if (lastpkData != null && newpkData != null) {
for (int i = 0; i < lastpkData.length && i < newpkData.length; i++) {
String lastValue = lastpkData[i];
String value = newpkData[i];
if ((lastValue != null && value == null)
|| (value != null && lastValue == null)) {
foundNullValueChange = true;
}
}
}
}
}
return foundNullValueChange;
}
protected boolean filterError(CsvData data, Exception ex) {
boolean process = true;
List<IDatabaseWriterErrorHandler> filters = this.writerSettings
.getDatabaseWriterErrorHandlers();
if (filters != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.FILTERMILLIS);
for (IDatabaseWriterErrorHandler filter : filters) {
process &= filter.handleError(context, targetTable, data, ex);
}
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.FILTERMILLIS);
}
}
return process;
}
protected boolean filterBefore(CsvData data) {
boolean process = true;
List<IDatabaseWriterFilter> filters = this.writerSettings.getDatabaseWriterFilters();
if (filters != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.FILTERMILLIS);
for (IDatabaseWriterFilter filter : filters) {
process &= filter.beforeWrite(this.context,
this.targetTable != null ? this.targetTable : this.sourceTable, data);
}
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.FILTERMILLIS);
}
}
return process;
}
protected void notifyFiltersEarlyCommit() {
List<IDatabaseWriterFilter> filters = this.writerSettings.getDatabaseWriterFilters();
if (filters != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.FILTERMILLIS);
for (IDatabaseWriterFilter filter : filters) {
filter.earlyCommit(context);
}
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.FILTERMILLIS);
}
}
}
protected void notifyFiltersBatchComplete() {
List<IDatabaseWriterFilter> filters = this.writerSettings.getDatabaseWriterFilters();
if (filters != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.FILTERMILLIS);
for (IDatabaseWriterFilter filter : filters) {
filter.batchComplete(context);
}
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.FILTERMILLIS);
}
}
}
protected void notifyFiltersBatchCommitted() {
List<IDatabaseWriterFilter> filters = this.writerSettings.getDatabaseWriterFilters();
if (filters != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.FILTERMILLIS);
for (IDatabaseWriterFilter filter : filters) {
filter.batchCommitted(context);
}
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.FILTERMILLIS);
}
}
}
protected void notifyFiltersBatchRolledback() {
List<IDatabaseWriterFilter> filters = this.writerSettings.getDatabaseWriterFilters();
if (filters != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.FILTERMILLIS);
for (IDatabaseWriterFilter filter : filters) {
filter.batchRolledback(context);
}
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.FILTERMILLIS);
}
}
}
protected void filterAfter(CsvData data) {
List<IDatabaseWriterFilter> filters = this.writerSettings.getDatabaseWriterFilters();
if (filters != null) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.FILTERMILLIS);
for (IDatabaseWriterFilter filter : filters) {
filter.afterWrite(this.context, this.targetTable != null ? this.targetTable
: this.sourceTable, data);
}
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.FILTERMILLIS);
}
}
}
protected LoadStatus insert(CsvData data) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
if (requireNewStatement(DmlType.INSERT, data, false, true, null)) {
this.lastUseConflictDetection = true;
this.currentDmlStatement = platform.createDmlStatement(DmlType.INSERT, targetTable);
if (log.isDebugEnabled()) {
log.debug("Preparing dml: " + this.currentDmlStatement.getSql());
}
transaction.prepare(this.currentDmlStatement.getSql());
}
try {
String[] values = (String[]) ArrayUtils.addAll(getRowData(data),
getLookupKeyData(getLookupDataMap(data), this.currentDmlStatement));
long count = execute(data, values);
statistics.get(batch).increment(DataWriterStatisticConstants.INSERTCOUNT, count);
return count > 0 ? LoadStatus.SUCCESS : LoadStatus.CONFLICT;
} catch (SqlException ex) {
if (platform.getSqlTemplate().isUniqueKeyViolation(ex)
&& !platform.getDatabaseInfo().isRequiresSavePointsInTransaction()) {
return LoadStatus.CONFLICT;
} else {
throw ex;
}
}
} catch (SqlException ex) {
logFailure(ex, data);
throw ex;
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
}
}
protected String[] getRowData(CsvData data) {
String[] targetValues = new String[targetTable.getColumnCount()];
String[] targetColumnNames = targetTable.getColumnNames();
String[] originalValues = data.getParsedData(CsvData.ROW_DATA);
String[] sourceColumnNames = sourceTable.getColumnNames();
for (int i = 0; i < sourceColumnNames.length && i < originalValues.length; i++) {
for(int t = 0; t < targetColumnNames.length; t++) {
if (sourceColumnNames[i].equalsIgnoreCase(targetColumnNames[t])) {
targetValues[t] = originalValues[i];
break;
}
}
}
return targetValues;
}
protected LoadStatus delete(CsvData data, boolean useConflictDetection) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
Conflict conflict = writerSettings.pickConflict(this.targetTable, batch);
Map<String, String> lookupDataMap = null;
if (requireNewStatement(DmlType.DELETE, data, useConflictDetection, useConflictDetection,
conflict.getDetectType())) {
this.lastUseConflictDetection = useConflictDetection;
List<Column> lookupKeys = null;
if (!useConflictDetection) {
lookupKeys = targetTable.getPrimaryKeyColumnsAsList();
} else {
switch (conflict.getDetectType()) {
case USE_OLD_DATA:
lookupKeys = targetTable.getColumnsAsList();
break;
case USE_VERSION:
case USE_TIMESTAMP:
List<Column> lookupColumns = new ArrayList<Column>();
Column versionColumn = targetTable.getColumnWithName(conflict
.getDetectExpression());
if (versionColumn != null) {
lookupColumns.add(versionColumn);
} else {
log.error(
"Could not find the timestamp/version column with the name {}. Defaulting to using primary keys for the lookup.",
conflict.getDetectExpression());
}
Column[] pks = targetTable.getPrimaryKeyColumns();
for (Column column : pks) {
// make sure all of the PK keys are in the list
// only once and are always at the end of the
// list
lookupColumns.remove(column);
lookupColumns.add(column);
}
lookupKeys = lookupColumns;
break;
case USE_PK_DATA:
default:
lookupKeys = targetTable.getPrimaryKeyColumnsAsList();
break;
}
}
if (lookupKeys == null || lookupKeys.size() == 0) {
lookupKeys = targetTable.getColumnsAsList();
}
if (!platform.getDatabaseInfo().isBlobsWorkInWhereClause()) {
Iterator<Column> it = lookupKeys.iterator();
while (it.hasNext()) {
Column col = it.next();
if (col.isOfBinaryType()) {
it.remove();
}
}
}
lookupDataMap = getLookupDataMap(data);
boolean[] nullKeyValues = new boolean[lookupKeys.size()];
for (int i = 0; i < lookupKeys.size(); i++) {
Column column = lookupKeys.get(i);
nullKeyValues[i] = !column.isRequired()
&& lookupDataMap.get(column.getName()) == null;
}
this.currentDmlStatement = platform.createDmlStatement(DmlType.DELETE,
targetTable.getCatalog(), targetTable.getSchema(), targetTable.getName(),
lookupKeys.toArray(new Column[lookupKeys.size()]), null, nullKeyValues);
if (log.isDebugEnabled()) {
log.debug("Preparing dml: " + this.currentDmlStatement.getSql());
}
transaction.prepare(this.currentDmlStatement.getSql());
}
try {
lookupDataMap = lookupDataMap == null ? getLookupDataMap(data) : lookupDataMap;
long count = execute(data, getLookupKeyData(lookupDataMap, currentDmlStatement));
statistics.get(batch).increment(DataWriterStatisticConstants.DELETECOUNT, count);
return count > 0 ? LoadStatus.SUCCESS : LoadStatus.CONFLICT;
} catch (SqlException ex) {
if (platform.getSqlTemplate().isUniqueKeyViolation(ex)
&& !platform.getDatabaseInfo().isRequiresSavePointsInTransaction()) {
return LoadStatus.CONFLICT;
} else {
throw ex;
}
}
} catch (SqlException ex) {
logFailure(ex, data);
throw ex;
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
}
}
protected LoadStatus update(CsvData data, boolean applyChangesOnly, boolean useConflictDetection) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
String[] columnValues = getRowData(data);
ArrayList<String> changedColumnNameList = new ArrayList<String>();
ArrayList<String> changedColumnValueList = new ArrayList<String>();
ArrayList<Column> changedColumnsList = new ArrayList<Column>();
for (int i = 0; i < targetTable.getColumnCount(); i++) {
Column column = targetTable.getColumn(i);
if (column != null) {
if (doesColumnNeedUpdated(i, column, data, applyChangesOnly)) {
changedColumnNameList.add(column.getName());
changedColumnsList.add(column);
changedColumnValueList.add(columnValues[i]);
}
}
}
if (changedColumnNameList.size() > 0) {
Map<String, String> lookupDataMap = null;
Conflict conflict = writerSettings.pickConflict(this.targetTable, batch);
if (requireNewStatement(DmlType.UPDATE, data, applyChangesOnly,
useConflictDetection, conflict.getDetectType())) {
lastApplyChangesOnly = applyChangesOnly;
lastUseConflictDetection = useConflictDetection;
List<Column> lookupKeys = null;
if (!useConflictDetection) {
lookupKeys = targetTable.getPrimaryKeyColumnsAsList();
} else {
switch (conflict.getDetectType()) {
case USE_CHANGED_DATA:
ArrayList<Column> lookupColumns = new ArrayList<Column>(
changedColumnsList);
Column[] pks = targetTable.getPrimaryKeyColumns();
for (Column column : pks) {
// make sure all of the PK keys are in the
// list only once and are always at the end
// of the list
lookupColumns.remove(column);
lookupColumns.add(column);
}
lookupKeys = lookupColumns;
break;
case USE_OLD_DATA:
lookupKeys = targetTable.getColumnsAsList();
break;
case USE_VERSION:
case USE_TIMESTAMP:
lookupColumns = new ArrayList<Column>();
Column versionColumn = targetTable.getColumnWithName(conflict
.getDetectExpression());
if (versionColumn != null) {
lookupColumns.add(versionColumn);
} else {
log.error(
"Could not find the timestamp/version column with the name {}. Defaulting to using primary keys for the lookup.",
conflict.getDetectExpression());
}
pks = targetTable.getPrimaryKeyColumns();
for (Column column : pks) {
// make sure all of the PK keys are in the
// list only once and are always at the end
// of the list
lookupColumns.remove(column);
lookupColumns.add(column);
}
lookupKeys = lookupColumns;
break;
case USE_PK_DATA:
default:
lookupKeys = targetTable.getPrimaryKeyColumnsAsList();
break;
}
}
if (lookupKeys == null || lookupKeys.size() == 0) {
lookupKeys = targetTable.getColumnsAsList();
}
if (!platform.getDatabaseInfo().isBlobsWorkInWhereClause()) {
Iterator<Column> it = lookupKeys.iterator();
while (it.hasNext()) {
Column col = it.next();
if (col.isOfBinaryType()) {
it.remove();
}
}
}
lookupDataMap = getLookupDataMap(data);
boolean[] nullKeyValues = new boolean[lookupKeys.size()];
for (int i = 0; i < lookupKeys.size(); i++) {
Column column = lookupKeys.get(i);
// the isRequired is a bit of a hack. This nullKeyValues
// should really be checking against the object values
// because some null values get translated into empty
// strings
nullKeyValues[i] = !column.isRequired()
&& lookupDataMap.get(column.getName()) == null;
}
this.currentDmlStatement = platform.createDmlStatement(DmlType.UPDATE,
targetTable.getCatalog(), targetTable.getSchema(),
targetTable.getName(),
lookupKeys.toArray(new Column[lookupKeys.size()]),
changedColumnsList.toArray(new Column[changedColumnsList.size()]),
nullKeyValues);
if (log.isDebugEnabled()) {
log.debug("Preparing dml: " + this.currentDmlStatement.getSql());
}
transaction.prepare(this.currentDmlStatement.getSql());
}
columnValues = (String[]) changedColumnValueList
.toArray(new String[changedColumnValueList.size()]);
lookupDataMap = lookupDataMap == null ? getLookupDataMap(data) : lookupDataMap;
String[] values = (String[]) ArrayUtils.addAll(columnValues,
getLookupKeyData(lookupDataMap, currentDmlStatement));
try {
long count = execute(data, values);
statistics.get(batch)
.increment(DataWriterStatisticConstants.UPDATECOUNT, count);
return count > 0 ? LoadStatus.SUCCESS : LoadStatus.CONFLICT;
} catch (SqlException ex) {
if (platform.getSqlTemplate().isUniqueKeyViolation(ex)
&& !platform.getDatabaseInfo().isRequiresSavePointsInTransaction()) {
return LoadStatus.CONFLICT;
} else {
throw ex;
}
}
} else {
// There was no change to apply
return LoadStatus.SUCCESS;
}
} catch (SqlException ex) {
logFailure(ex, data);
throw ex;
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
}
}
protected void logFailure(SqlException e, CsvData data) {
StringBuilder failureMessage = new StringBuilder();
failureMessage.append("Failed to process a ");
failureMessage.append(data.getDataEventType().toString().toLowerCase());
failureMessage.append(" event in batch ");
failureMessage.append(batch.getBatchId());
failureMessage.append(".\n");
if (this.currentDmlStatement != null) {
failureMessage.append("Failed sql was: ");
failureMessage.append(this.currentDmlStatement.getSql());
failureMessage.append("\n");
}
String rowData = data.getCsvData(CsvData.PK_DATA);
if (StringUtils.isNotBlank(rowData)) {
failureMessage.append("Failed pk data was: ");
failureMessage.append(rowData);
failureMessage.append("\n");
}
final long MAX_DATA_SIZE_TO_PRINT_TO_LOG = 1024 * 1000;
rowData = data.getCsvData(CsvData.ROW_DATA);
if (StringUtils.isNotBlank(rowData)) {
if (rowData.length() < MAX_DATA_SIZE_TO_PRINT_TO_LOG) {
failureMessage.append("Failed row data was: ");
failureMessage.append(rowData);
failureMessage.append("\n");
} else {
failureMessage.append("Row data was bigger than ");
failureMessage.append(MAX_DATA_SIZE_TO_PRINT_TO_LOG);
failureMessage.append(" bytes (it was ");
failureMessage.append(rowData.length());
failureMessage.append(" bytes). It will not be printed to the log file");
}
}
rowData = data.getCsvData(CsvData.OLD_DATA);
if (StringUtils.isNotBlank(rowData)) {
failureMessage.append("Failed old data was: ");
failureMessage.append(rowData);
failureMessage.append("\n");
}
log.error(failureMessage.toString());
}
protected boolean script(CsvData data) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
String script = data.getParsedData(CsvData.ROW_DATA)[0];
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("SOURCE_NODE_ID", batch.getSourceNodeId());
variables.put("TARGET_NODE_ID", batch.getTargetNodeId());
ISqlTemplate template = platform.getSqlTemplate();
Class<?> templateClass = template.getClass();
if (templateClass.getSimpleName().equals("JdbcSqlTemplate")) {
try {
Method method = templateClass.getMethod("getDataSource");
variables.put("DATASOURCE", method.invoke(template));
} catch (Exception e) {
log.warn("Had trouble looking up the datasource used by the sql template", e);
}
}
Interpreter interpreter = new Interpreter();
if (variables != null) {
for (String variableName : variables.keySet()) {
interpreter.set(variableName, variables.get(variableName));
}
}
if (log.isDebugEnabled()) {
log.debug("About to run: {}", script);
}
interpreter.eval(script);
statistics.get(batch).increment(DataWriterStatisticConstants.SCRIPTCOUNT);
} catch (EvalError e) {
throw new RuntimeException(e);
}
return true;
}
protected boolean create(CsvData data) {
String xml = null;
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
xml = data.getParsedData(CsvData.ROW_DATA)[0];
log.info("About to create table using the following definition: {}", xml);
StringReader reader = new StringReader(xml);
Database db = DatabaseXmlUtil.read(reader, false);
if (writerSettings.isCreateTableAlterCaseToMatchDatabaseDefault()) {
platform.alterCaseToMatchDatabaseDefaultCase(db);
}
if (writerSettings.isAlterTable()) {
platform.alterDatabase(db, !writerSettings.isCreateTableFailOnError());
} else {
platform.createDatabase(db, writerSettings.isCreateTableDropFirst(), !writerSettings.isCreateTableFailOnError());
}
platform.resetCachedTableModel();
statistics.get(batch).increment(DataWriterStatisticConstants.CREATECOUNT);
return true;
} catch (RuntimeException ex) {
log.error("Failed to alter table using the following xml: {}", xml);
throw ex;
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
}
}
protected boolean sql(CsvData data) {
try {
statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
String sql = preprocessSqlStatement(data);
transaction.prepare(sql);
if (log.isDebugEnabled()) {
log.debug("About to run: {}", sql);
}
long count = transaction.prepareAndExecute(sql);
if (log.isDebugEnabled()) {
log.debug("{} rows updated when running: {}", count, sql);
}
statistics.get(batch).increment(DataWriterStatisticConstants.SQLCOUNT);
statistics.get(batch).increment(DataWriterStatisticConstants.SQLROWSAFFECTEDCOUNT,
count);
return true;
} finally {
statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
}
}
protected String preprocessSqlStatement(CsvData data) {
String sql = data.getParsedData(CsvData.ROW_DATA)[0];
sql = FormatUtils.replace("nodeId", batch.getTargetNodeId(), sql);
sql = FormatUtils.replace("catalogName", targetTable.getCatalog(),sql);
sql = FormatUtils.replace("schemaName", targetTable.getSchema(), sql);
sql = FormatUtils.replace("tableName", formatTableName(targetTable.getName()), sql);
// sql = FormatUtils.replace("groupId", node.getNodeGroupId(), sql);
// sql = FormatUtils.replace("externalId", node.getExternalId(), sql);
return sql;
}
protected String formatTableName(String tableName) {
String quote = platform.getDdlBuilder().isDelimitedIdentifierModeOn() ? platform
.getDatabaseInfo().getDelimiterToken() : "";
return String.format("%s%s%s", quote, tableName, quote);
}
protected boolean doesColumnNeedUpdated(int columnIndex, Column column, CsvData data,
boolean applyChangesOnly) {
boolean needsUpdated = true;
String[] oldData = data.getParsedData(CsvData.OLD_DATA);
String[] rowData = data.getParsedData(CsvData.ROW_DATA);
if (!platform.getDatabaseInfo().isAutoIncrementUpdateAllowed() && column.isAutoIncrement()) {
needsUpdated = false;
} else if (oldData != null && applyChangesOnly) {
/*
* Old data isn't captured for some lob fields. When both values are
* null, then we always have to update because we don't know if the
* lob field was previously null.
*/
boolean containsEmptyLobColumn = platform.isLob(column.getMappedTypeCode())
&& StringUtils.isBlank(oldData[columnIndex]);
needsUpdated = !StringUtils.equals(rowData[columnIndex], oldData[columnIndex])
|| containsEmptyLobColumn;
if (containsEmptyLobColumn) {
// indicate that we are considering the column to be changed
data.getChangedDataIndicators()[columnIndex] = true;
}
} else {
/*
* This is in support of creating update statements that don't use
* the keys in the set portion of the update statement. </p> In
* oracle (and maybe not only in oracle) if there is no index on
* child table on FK column and update is performing on PK on master
* table, table lock is acquired on child table. Table lock is taken
* not in exclusive mode, but lock contentions is possible.
*/
needsUpdated = !column.isPrimaryKey()
|| !StringUtils.equals(rowData[columnIndex], getPkDataFor(data, column));
}
return needsUpdated;
}
protected Map<String, String> getLookupDataMap(CsvData data) {
Map<String, String> keyData = null;
if (data.getDataEventType() == DataEventType.INSERT) {
keyData = data.toColumnNameValuePairs(sourceTable.getColumnNames(), CsvData.ROW_DATA);
} else {
keyData = data.toColumnNameValuePairs(sourceTable.getColumnNames(),
CsvData.OLD_DATA);
if (keyData == null || keyData.size() == 0) {
keyData = data.toColumnNameValuePairs(sourceTable.getPrimaryKeyColumnNames(),
CsvData.PK_DATA);
}
if (keyData == null || keyData.size() == 0) {
keyData = data.toColumnNameValuePairs(sourceTable.getColumnNames(),
CsvData.ROW_DATA);
}
}
return keyData;
}
protected String[] getLookupKeyData(Map<String, String> lookupDataMap, DmlStatement dmlStatement) {
Column[] lookupColumns = dmlStatement.getKeys();
if (lookupColumns != null && lookupColumns.length > 0) {
if (lookupDataMap != null && lookupDataMap.size() > 0) {
String[] keyDataAsArray = new String[lookupColumns.length];
int index = 0;
for (Column keyColumn : lookupColumns) {
keyDataAsArray[index++] = lookupDataMap.get(keyColumn.getName());
}
return keyDataAsArray;
}
}
return null;
}
protected String getPkDataFor(CsvData data, Column column) {
String[] values = data.getParsedData(CsvData.PK_DATA);
if (values != null) {
Column[] columns = targetTable.getColumns();
int index = -1;
for (Column column2 : columns) {
if (column2.isPrimaryKey()) {
index++;
}
if (column2.equals(column)) {
return values[index];
}
}
} else {
return data.getParsedData(CsvData.ROW_DATA)[targetTable.getColumnIndex(column)];
}
return null;
}
protected int execute(CsvData data, String[] values) {
Object[] objectValues = platform.getObjectValues(batch.getBinaryEncoding(), values,
currentDmlStatement.getMetaData());
if (log.isDebugEnabled()) {
log.debug("Submitting data {} with types {}", Arrays.toString(objectValues),
Arrays.toString(this.currentDmlStatement.getTypes()));
}
return transaction.addRow(data, objectValues, this.currentDmlStatement.getTypes());
}
public void end(Table table) {
String quote = getPlatform().getDatabaseInfo().getDelimiterToken();
this.transaction.allowInsertIntoAutoIncrementColumns(false, this.targetTable, quote);
}
public void end(Batch batch, boolean inError) {
this.lastData = null;
this.currentDmlStatement = null;
if (batch.isIgnored()) {
getStatistics().get(batch).increment(DataWriterStatisticConstants.IGNORECOUNT);
}
if (!inError) {
notifyFiltersBatchComplete();
commit();
} else {
rollback();
}
}
public void close() {
if (transaction != null) {
this.transaction.close();
}