Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 86045d162fd6053dda237b03eb2e296ecda75257 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
/**
 * Copyright (c) 2004 - 2009 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Eike Stepper - initial API and implementation
 *    Stefan Winkler - https://bugs.eclipse.org/bugs/show_bug.cgi?id=259402    
 */
package org.eclipse.emf.cdo.server.internal.db.jdbc;

import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.id.CDOIDUtil;
import org.eclipse.emf.cdo.common.revision.CDORevision;
import org.eclipse.emf.cdo.server.db.mapping.IAttributeMapping;
import org.eclipse.emf.cdo.server.internal.db.CDODBSchema;
import org.eclipse.emf.cdo.server.internal.db.bundle.OM;
import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;

import org.eclipse.net4j.db.DBException;
import org.eclipse.net4j.db.DBUtil;
import org.eclipse.net4j.util.collection.Pair;
import org.eclipse.net4j.util.om.monitor.OMMonitor;
import org.eclipse.net4j.util.om.monitor.OMMonitor.Async;
import org.eclipse.net4j.util.om.trace.ContextTracer;
import org.eclipse.net4j.util.ref.ReferenceValueMap;

import org.eclipse.emf.ecore.EEnumLiteral;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author Stefan Winkler
 * @since 2.0
 */
public class PreparedStatementJDBCDelegate extends AbstractJDBCDelegate
{
  /**
   * Value for {@link #cachingFlag}: Guess if caching is needed
   */
  public static final String CACHE_STMTS_GUESS = "guess";

  /**
   * Value for {@link #cachingFlag}: Turn caching on
   */
  public static final String CACHE_STMTS_TRUE = "true";

  /**
   * Value for {@link #cachingFlag}: Turn caching off
   */
  public static final String CACHE_STMTS_FALSE = "false";

  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, PreparedStatementJDBCDelegate.class);

  private static final String SQL_UPDATE_REVISE_VERSION = " SET " + CDODBSchema.ATTRIBUTES_REVISED + " = ? WHERE "
      + CDODBSchema.ATTRIBUTES_ID + " = ? AND " + CDODBSchema.ATTRIBUTES_VERSION + " = ?";

  private static final String SQL_UPDATE_REVISE_UNREVISED = " SET " + CDODBSchema.ATTRIBUTES_REVISED + " = ? WHERE "
      + CDODBSchema.ATTRIBUTES_ID + " = ? AND " + CDODBSchema.ATTRIBUTES_REVISED + " = 0";

  private static final String SQL_INSERT_REFERENCE_WITH_DBID = " VALUES (?, ?, ?, ?, ?)";

  private static final String SQL_INSERT_REFERENCE = " VALUES (?, ?, ?, ?)";

  /**
   * Cache for preparedStatements used in diverse methods
   */
  private Map<CacheKey, WrappedPreparedStatement> statementCache = null;

  /**
   * Container for dirty statements. A statement is considered 'dirty', if addBatch was called, but not executeBatch.
   */
  private Map<CacheKey, PreparedStatement> dirtyStatements = null;

  /**
   * This flag determines, if prepared statements should be cached within this delegate. Its value is guessed in
   * {@link #postInitConnection()} based on the fact if the JDBC driver supports pooled statements. If it does, caching
   * in the delegate is unnecessary.
   */
  private boolean cacheStatements;

  private CachingEnablement cachingEnablement;

  /**
   * This statement is used for unprepared batched statements like in
   * {@link #doUpdateAttributes(String, long, int, long, List, boolean)}
   */
  private Statement miscStatement = null;

  public PreparedStatementJDBCDelegate()
  {
  }

  @Override
  protected void doActivate() throws Exception
  {
    super.doActivate();
    dirtyStatements = new ReferenceValueMap.Strong<CacheKey, PreparedStatement>();

    switch (cachingEnablement)
    {
    case ENABLED:
      cacheStatements = true;
      break;

    case DISABLED:
      cacheStatements = false;
      break;

    case GUESS:
      try
      {
        cacheStatements = !getConnection().getMetaData().supportsStatementPooling();
      }
      catch (SQLException ex)
      {
        OM.LOG.warn("Failed to guess JDBC statement pooling. Activating cache, just to be sure ...", ex);
        cacheStatements = true;
      }
    }

    if (TRACER.isEnabled())
    {
      TRACER.trace("JDBC PreparedStatement caching is " + (cacheStatements ? "enabled." : "NOT enabled."));
    }

    if (cacheStatements)
    {
      // initialize cache ...
      statementCache = new ReferenceValueMap.Soft<CacheKey, WrappedPreparedStatement>();
    }
  }

  @Override
  protected void doBeforeDeactivate() throws Exception
  {
    for (PreparedStatement ps : dirtyStatements.values())
    {
      DBUtil.close(ps);
    }

    dirtyStatements.clear();
    if (cacheStatements)
    {
      for (WrappedPreparedStatement ps : statementCache.values())
      {
        DBUtil.close(ps.getWrappedStatement());
      }

      statementCache.clear();
    }

    super.doBeforeDeactivate();
  }

  public CachingEnablement getCachingEnablement()
  {
    return cachingEnablement;
  }

  public void setCachingEnablement(CachingEnablement cachingEnablement)
  {
    checkInactive();
    this.cachingEnablement = cachingEnablement;
  }

  public void flush(OMMonitor monitor)
  {
    try
    {
      monitor.begin(dirtyStatements.size() + 1);

      if (miscStatement != null)
      {
        Async async = monitor.forkAsync();
        try
        {
          int[] results = miscStatement.executeBatch();
          for (int result : results)
          {
            checkState(result == 1, "Batch of misc statements did not return '1'");
          }
        }
        catch (SQLException ex)
        {
          throw new DBException("Batch execution failed for misc statement.", ex);
        }
        finally
        {
          try
          {
            miscStatement.close();
          }
          catch (SQLException ex)
          {
            // eat up ...
          }
          miscStatement = null;
          async.stop();
        }
      }

      for (Entry<CacheKey, PreparedStatement> entry : dirtyStatements.entrySet())
      {
        try
        {
          int[] results;
          Async async = monitor.forkAsync();

          try
          {
            results = entry.getValue().executeBatch();
          }
          finally
          {
            async.stop();
          }

          if (TRACER.isEnabled())
          {
            TRACER.format("Executing batch for {0} [{1}]", entry.getKey().toString(), entry.getValue());
          }

          for (int result : results)
          {
            checkState(result != Statement.EXECUTE_FAILED, "Batch execution returned EXECUTE_FAILED!");
          }
        }
        catch (SQLException ex)
        {
          throw new DBException("Batch execution failed for " + entry.getKey().toString() + " [" + entry.getValue()
              + "]", ex);
        }
      }
    }
    finally
    {
      if (!cacheStatements)
      {
        if (TRACER.isEnabled())
        {
          TRACER.format("Closing prepared statements.");
        }

        for (PreparedStatement ps : dirtyStatements.values())
        {
          DBUtil.close(ps);
        }
      }
      else
      {
        if (TRACER.isEnabled())
        {
          TRACER.format("Re-caching prepared statements.");
        }

        for (Entry<CacheKey, PreparedStatement> entry : dirtyStatements.entrySet())
        {
          cacheStatement(entry.getKey(), entry.getValue());
        }
      }

      dirtyStatements.clear();

      monitor.done();
    }
  }

  @Override
  protected void doInsertAttributes(String tableName, CDORevision rev, List<IAttributeMapping> attributeMappings,
      boolean withFullRevisionInfo)
  {
    boolean firstBatch = false;
    InternalCDORevision revision = (InternalCDORevision)rev;

    if (attributeMappings == null)
    {
      attributeMappings = Collections.emptyList();
    }

    PreparedStatement stmt = getDirtyStatement(StmtType.INSERT_ATTRIBUTES, tableName);
    if (stmt == null && cacheStatements)
    {
      firstBatch = true;
      stmt = getAndRemoveCachedStatement(StmtType.INSERT_ATTRIBUTES, tableName);
    }

    try
    {
      firstBatch = true;
      if (stmt == null)
      {
        StringBuilder sql = new StringBuilder();

        sql.append("INSERT INTO ");
        sql.append(tableName);
        sql.append(" VALUES (?, ?, ");
        if (withFullRevisionInfo)
        {
          sql.append("?, ?, ?, ?, ?, ?");
        }

        for (int i = 0; i < attributeMappings.size(); i++)
        {
          sql.append(", ?");
        }

        sql.append(")");
        stmt = getConnection().prepareStatement(sql.toString());
      }

      int col = 1;
      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.setLong(col++, CDOIDUtil.getLong(revision.getID()));
      stmt.setInt(col++, revision.getVersion());
      if (withFullRevisionInfo)
      {
        stmt.setLong(col++, getStoreAccessor().getStore().getMetaID(revision.getEClass()));
        stmt.setLong(col++, revision.getCreated());
        stmt.setLong(col++, revision.getRevised());
        stmt.setLong(col++, CDOIDUtil.getLong(revision.getResourceID()));
        stmt.setLong(col++, CDOIDUtil.getLong((CDOID)revision.getContainerID()));
        stmt.setInt(col++, revision.getContainingFeatureID());
      }

      for (IAttributeMapping attributeMapping : attributeMappings)
      {
        Object value = attributeMapping.getRevisionValue(revision);

        if (value == null)
        {
          stmt.setNull(col++, attributeMapping.getField().getType().getCode());
        }
        else if (value instanceof java.util.Date)
        {
          // BUG 217255
          stmt.setTimestamp(col++, new Timestamp(((Date)value).getTime()));
        }
        else if (value instanceof EEnumLiteral)
        {
          stmt.setInt(col++, ((EEnumLiteral)value).getValue());
        }
        else
        {
          stmt.setObject(col++, value);
        }
      }

      if (firstBatch)
      {
        addDirtyStatement(StmtType.INSERT_ATTRIBUTES, tableName, stmt);
      }

      stmt.addBatch();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
  }

  @Override
  protected void doUpdateAttributes(String tableName, long cdoid, int newVersion, long created,
      List<Pair<IAttributeMapping, Object>> attributeChanges, boolean hasFullRevisionInfo)
  {
    StringBuilder builder = new StringBuilder();
    builder.append("UPDATE ");
    builder.append(tableName);
    builder.append(" SET ");
    builder.append(CDODBSchema.ATTRIBUTES_VERSION);
    builder.append(" = ");
    builder.append(newVersion);
    builder.append(", ");
    builder.append(CDODBSchema.ATTRIBUTES_CREATED);
    builder.append(" = ");
    builder.append(created);

    for (Pair<IAttributeMapping, Object> attributeChange : attributeChanges)
    {
      IAttributeMapping attributeMapping = attributeChange.getElement1();
      builder.append(", ");
      builder.append(attributeMapping.getField());
      builder.append(" = ");
      attributeMapping.appendValue(builder, attributeChange.getElement2());
    }

    builder.append(" WHERE ");
    builder.append(CDODBSchema.ATTRIBUTES_ID);
    builder.append(" = ");
    builder.append(cdoid);

    String sql = builder.toString();

    if (TRACER.isEnabled())
    {
      TRACER.trace("Batching misc statement:" + sql);
    }

    try
    {
      if (miscStatement == null)
      {
        miscStatement = getConnection().createStatement();
      }
      miscStatement.addBatch(sql);
    }
    catch (SQLException ex)
    {
      throw new DBException(ex);
    }
  }

  @Override
  protected void doUpdateAttributes(String tableName, long cdoid, int newVersion, long created, long newContainerId,
      int newContainingFeatureId, long newResourceId, List<Pair<IAttributeMapping, Object>> attributeChanges,
      boolean hasFullRevisionInfo)
  {
    StringBuilder builder = new StringBuilder();
    builder.append("UPDATE ");
    builder.append(tableName);
    builder.append(" SET ");
    builder.append(CDODBSchema.ATTRIBUTES_VERSION);
    builder.append(" = ");
    builder.append(newVersion);
    builder.append(", ");
    builder.append(CDODBSchema.ATTRIBUTES_CREATED);
    builder.append(" = ");
    builder.append(created);
    builder.append(", ");
    builder.append(CDODBSchema.ATTRIBUTES_CONTAINER);
    builder.append(" = ");
    builder.append(newContainerId);

    builder.append(", ");
    builder.append(CDODBSchema.ATTRIBUTES_FEATURE);
    builder.append(" = ");
    builder.append(newContainingFeatureId);

    builder.append(", ");
    builder.append(CDODBSchema.ATTRIBUTES_RESOURCE);
    builder.append(" = ");
    builder.append(newResourceId);

    for (Pair<IAttributeMapping, Object> attributeChange : attributeChanges)
    {
      IAttributeMapping attributeMapping = attributeChange.getElement1();
      builder.append(", ");
      builder.append(attributeMapping.getField());
      builder.append(" = ");
      attributeMapping.appendValue(builder, attributeChange.getElement2());
    }

    builder.append(" WHERE ");
    builder.append(CDODBSchema.ATTRIBUTES_ID);
    builder.append(" = ");
    builder.append(cdoid);

    String sql = builder.toString();

    if (TRACER.isEnabled())
    {
      TRACER.trace(sql);
    }

    try
    {
      if (miscStatement == null)
      {
        miscStatement = getConnection().createStatement();
      }
      miscStatement.addBatch(sql);
    }
    catch (SQLException ex)
    {
      throw new DBException(ex);
    }
  }

  @Override
  protected void doUpdateRevisedForReplace(String tableName, long revisedStamp, long cdoid, int version)
  {
    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.REVISE_VERSION, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder sql = new StringBuilder("UPDATE ");
        sql.append(tableName);
        sql.append(SQL_UPDATE_REVISE_VERSION);
        stmt = getConnection().prepareStatement(sql.toString());

        if (cacheStatements)
        {
          cacheStatement(StmtType.REVISE_VERSION, tableName, stmt);
        }
      }

      stmt.setLong(1, revisedStamp);
      stmt.setLong(2, cdoid);
      stmt.setInt(3, version);
      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  @Override
  protected void doUpdateRevisedForDetach(String tableName, long revisedStamp, long cdoid)
  {
    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.REVISE_UNREVISED, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder sql = new StringBuilder("UPDATE ");
        sql.append(tableName);
        sql.append(SQL_UPDATE_REVISE_UNREVISED);
        stmt = getConnection().prepareStatement(sql.toString());

        if (cacheStatements)
        {
          cacheStatement(StmtType.REVISE_UNREVISED, tableName, stmt);
        }
      }

      stmt.setLong(1, revisedStamp);
      stmt.setLong(2, cdoid);
      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  /*
   * This has been the preparedStatement version of updateAttributes. Does not make sense now, as amount of attributes
   * is variable. Preparing for any number of attributes is not very intelligent ...
   * @Override protected void doUpdateAllAttributes(String tableName, long cdoid, int version, long created,
   * List<Pair<IAttributeMapping, Object>> attributeChanges, boolean withFullRevisionInfo) { boolean firstBatch = false;
   * PreparedStatement stmt = getDirtyStatement(StmtType.UPDATE_ATTRIBUTES, tableName); if (stmt == null &&
   * cacheStatements) { firstBatch = true; stmt = getAndRemoveCachedStatement(StmtType.UPDATE_ATTRIBUTES, tableName); }
   * try { firstBatch = true; if (stmt == null) { StringBuilder sql = new StringBuilder(); sql.append("UPDATE ");
   * sql.append(tableName); sql.append(" SET "); sql.append(CDODBSchema.ATTRIBUTES_VERSION); sql.append(" = ? "); if
   * (withFullRevisionInfo) { sql.append(", "); sql.append(CDODBSchema.ATTRIBUTES_RESOURCE); sql.append(" = ?,");
   * sql.append(CDODBSchema.ATTRIBUTES_CONTAINER); sql.append(" = ?,"); sql.append(CDODBSchema.ATTRIBUTES_FEATURE);
   * sql.append(" = ?"); } for (IAttributeMapping attributeMapping : attributeMappings) { sql.append(", ");
   * sql.append(attributeMapping.getField()); sql.append(" = ?"); } sql.append(" WHERE ");
   * sql.append(CDODBSchema.ATTRIBUTES_ID); sql.append(" = ? "); stmt =
   * getConnection().prepareStatement(sql.toString()); } int col = 1; if (TRACER.isEnabled()) {
   * TRACER.trace(stmt.toString()); } stmt.setInt(col++, revision.getVersion()); if (withFullRevisionInfo) {
   * stmt.setLong(col++, CDOIDUtil.getLong(revision.getResourceID())); stmt.setLong(col++,
   * CDOIDUtil.getLong((CDOID)revision.getContainerID())); stmt.setInt(col++, revision.getContainingFeatureID()); } for
   * (IAttributeMapping attributeMapping : attributeMappings) { Object value =
   * attributeMapping.getRevisionValue(revision); if (value == null) { stmt.setNull(col++,
   * attributeMapping.getField().getType().getCode()); } else { stmt.setObject(col++, value); } } stmt.setLong(col++,
   * CDOIDUtil.getLong(revision.getID())); if (firstBatch) { addDirtyStatement(StmtType.UPDATE_ATTRIBUTES, tableName,
   * stmt); } stmt.addBatch(); } catch (SQLException e) { throw new DBException(e); } }
   */

  @Override
  protected void doDeleteAttributes(String tableName, long cdoid)
  {
    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.DELETE_ATTRIBUTES, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder sql = new StringBuilder("DELETE FROM ");
        sql.append(tableName);
        sql.append(" WHERE ");
        sql.append(CDODBSchema.ATTRIBUTES_ID);
        sql.append(" = ? ");

        stmt = getConnection().prepareStatement(sql.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.DELETE_ATTRIBUTES, tableName, stmt);
        }
      }

      stmt.setLong(1, cdoid);
      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  @Override
  protected void doInsertReference(String tableName, long dbID, long source, int version, int index, long target)
  {
    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.INSERT_REFERENCES, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder sql = new StringBuilder("INSERT INTO ");
        sql.append(tableName);
        sql.append(dbID != 0 ? SQL_INSERT_REFERENCE_WITH_DBID : SQL_INSERT_REFERENCE);
        stmt = getConnection().prepareStatement(sql.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.INSERT_REFERENCES, tableName, stmt);
        }
      }

      int idx = 1;
      if (dbID != 0)
      {
        stmt.setLong(idx++, dbID);
      }

      stmt.setLong(idx++, source);
      stmt.setInt(idx++, version);
      stmt.setInt(idx++, index);
      stmt.setLong(idx++, target);
      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  @Override
  protected void doInsertReferenceRow(String tableName, long metaID, long cdoid, int newVersion, long target, int index)
  {
    move1up(tableName, metaID, cdoid, newVersion, index);
    doInsertReference(tableName, metaID, cdoid, newVersion, index, target);
  }

  @Override
  protected void doMoveReferenceRow(String tableName, long metaID, long cdoid, int newVersion, int oldPosition,
      int newPosition)
  {
    if (oldPosition == newPosition)
    {
      return;
    }

    // move element away temporarily
    updateOneIndex(tableName, metaID, cdoid, newVersion, oldPosition, -1);

    // move elements in between
    if (oldPosition < newPosition)
    {
      move1down(tableName, metaID, cdoid, newVersion, oldPosition, newPosition);
    }
    else
    {
      // oldPosition > newPosition -- equal case is handled above
      move1up(tableName, metaID, cdoid, newVersion, newPosition, oldPosition);
    }

    // move temporary element to new position
    updateOneIndex(tableName, metaID, cdoid, newVersion, -1, newPosition);

  }

  @Override
  protected void doRemoveReferenceRow(String tableName, long metaID, long cdoid, int index, int newVersion)
  {
    deleteReferenceRow(tableName, metaID, cdoid, index);
    move1down(tableName, metaID, cdoid, newVersion, index);
  }

  @Override
  protected void doUpdateReference(String tableName, long metaID, long sourceId, int newVersion, int index,
      long targetId)
  {
    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.UPDATE_REFERENCE, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder builder = new StringBuilder("UPDATE ");
        builder.append(tableName);
        builder.append(" SET ");
        builder.append(CDODBSchema.REFERENCES_TARGET);
        builder.append(" = ?, ");
        builder.append(CDODBSchema.REFERENCES_VERSION);
        builder.append(" = ? WHERE ");
        if (metaID != 0)
        {
          builder.append(CDODBSchema.REFERENCES_FEATURE);
          builder.append("= ? AND ");
        }

        builder.append(CDODBSchema.REFERENCES_SOURCE);
        builder.append("= ? AND ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" = ?");

        stmt = getConnection().prepareStatement(builder.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.UPDATE_REFERENCE, tableName, stmt);
        }
      }

      int idx = 1;
      stmt.setLong(idx++, targetId);
      stmt.setInt(idx++, newVersion);

      if (metaID != 0)
      {
        stmt.setLong(idx++, metaID);
      }

      stmt.setLong(idx++, sourceId);
      stmt.setLong(idx++, index);

      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  @Override
  protected void doUpdateReferenceVersion(String tableName, long cdoid, int newVersion)
  {
    boolean firstBatch = false;

    PreparedStatement stmt = getDirtyStatement(StmtType.UPDATE_REFERENCE_VERSION, tableName);
    if (stmt == null && cacheStatements)
    {
      firstBatch = true;
      stmt = getAndRemoveCachedStatement(StmtType.UPDATE_REFERENCE_VERSION, tableName);
    }

    try
    {
      if (stmt == null)
      {
        firstBatch = true;

        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ");
        sql.append(tableName);
        sql.append(" SET ");
        sql.append(CDODBSchema.REFERENCES_VERSION);
        sql.append(" = ? ");
        sql.append(" WHERE ");
        sql.append(CDODBSchema.REFERENCES_SOURCE);
        sql.append(" = ?");

        stmt = getConnection().prepareStatement(sql.toString());
      }

      stmt.setInt(1, newVersion);
      stmt.setLong(2, cdoid);

      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      if (firstBatch)
      {
        addDirtyStatement(StmtType.UPDATE_REFERENCE_VERSION, tableName, stmt);
      }

      stmt.addBatch();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
  }

  @Override
  protected void doDeleteReferences(String tableName, long metaID, long cdoid)
  {
    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.DELETE_REFERENCES, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder sql = new StringBuilder("DELETE FROM ");
        sql.append(tableName);
        sql.append(" WHERE ");
        sql.append(CDODBSchema.REFERENCES_SOURCE);
        sql.append(" = ? ");

        if (metaID != 0)
        {
          sql.append("AND");
          sql.append(CDODBSchema.REFERENCES_FEATURE);
          sql.append(" = ? ");
        }

        stmt = getConnection().prepareStatement(sql.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.DELETE_REFERENCES, tableName, stmt);
        }
      }

      stmt.setLong(1, cdoid);
      if (metaID != 0)
      {
        stmt.setLong(2, metaID);
      }

      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  @Override
  protected ResultSet doSelectRevisionAttributes(String tableName, long revisionId,
      List<IAttributeMapping> attributeMappings, boolean hasFullRevisionInfo, String where) throws SQLException
  {
    // Because of the variable where clause, statement caching can not be
    // based on table names. Instead, we build the sql in any case and
    // use this as key (similar to what JDBC3 does ...).

    StringBuilder builder = new StringBuilder();
    builder.append("SELECT ");
    builder.append(CDODBSchema.ATTRIBUTES_VERSION);
    builder.append(", ");
    builder.append(CDODBSchema.ATTRIBUTES_CREATED);

    if (hasFullRevisionInfo)
    {
      builder.append(", ");
      builder.append(CDODBSchema.ATTRIBUTES_REVISED);
      builder.append(", ");
      builder.append(CDODBSchema.ATTRIBUTES_RESOURCE);
      builder.append(", ");
      builder.append(CDODBSchema.ATTRIBUTES_CONTAINER);
      builder.append(", ");
      builder.append(CDODBSchema.ATTRIBUTES_FEATURE);
    }

    for (IAttributeMapping attributeMapping : attributeMappings)
    {
      builder.append(", ");
      builder.append(attributeMapping.getField());
    }

    builder.append(" FROM ");
    builder.append(tableName);
    builder.append(" WHERE ");
    builder.append(CDODBSchema.ATTRIBUTES_ID);
    builder.append("= ? AND (");
    builder.append(where);
    builder.append(")");
    String sql = builder.toString();
    if (TRACER.isEnabled())
    {
      TRACER.format("{0} ({1})", sql, revisionId);
    }

    PreparedStatement pstmt = null;
    if (cacheStatements)
    {
      pstmt = getCachedStatement(StmtType.GENERAL, sql);
      if (pstmt == null)
      {
        pstmt = getConnection().prepareStatement(sql);
        cacheStatement(StmtType.GENERAL, sql, pstmt);
      }
    }
    else
    {
      /* no caching */
      pstmt = getConnection().prepareStatement(sql);
    }

    pstmt.setLong(1, revisionId);
    return pstmt.executeQuery();
  }

  @Override
  protected ResultSet doSelectRevisionReferences(String tableName, long sourceId, int version, long metaID, String where)
      throws SQLException
  {
    StringBuilder builder = new StringBuilder();
    builder.append("SELECT ");
    builder.append(CDODBSchema.REFERENCES_TARGET);
    builder.append(" FROM ");
    builder.append(tableName);
    builder.append(" WHERE ");
    if (metaID != 0)
    {
      builder.append(CDODBSchema.REFERENCES_FEATURE);
      builder.append("= ? AND ");
    }

    builder.append(CDODBSchema.REFERENCES_SOURCE);
    builder.append("= ? AND ");
    builder.append(CDODBSchema.REFERENCES_VERSION);
    builder.append("= ? ");
    if (where != null)
    {
      builder.append(where);
    }

    builder.append(" ORDER BY ");
    builder.append(CDODBSchema.REFERENCES_IDX);

    String sql = builder.toString();
    if (TRACER.isEnabled())
    {
      TRACER.trace(sql);
    }

    PreparedStatement pstmt = null;
    if (cacheStatements)
    {
      pstmt = getCachedStatement(StmtType.GENERAL, sql);
      if (pstmt == null)
      {
        pstmt = getConnection().prepareStatement(sql);
        cacheStatement(StmtType.GENERAL, sql, pstmt);
      }
    }
    else
    {
      /* no caching */
      pstmt = getConnection().prepareStatement(sql);
    }

    int idx = 1;
    if (metaID != 0)
    {
      pstmt.setLong(idx++, metaID);
    }

    pstmt.setLong(idx++, sourceId);
    pstmt.setInt(idx++, version);
    return pstmt.executeQuery();
  }

  /**
   * Implementation of the hook which is called after selects.
   */
  @Override
  protected void releaseStatement(Statement stmt)
  {
    // leave open cached statements
    if (!cacheStatements || !(stmt instanceof PreparedStatement))
    {
      super.releaseStatement(stmt);
    }

    // /* This code would guarantee that releaseStatement is only called
    // for cached statements. However this looks through the whole hashmap
    // and is thus too expensive to do in non-debugging mode. */
    //
    // else {
    // if(!selectStatementsCache.containsValue(stmt)) {
    // super.releaseStatement(stmt);
    // }
    // }
  }

  // ----------------------------------------------------------
  // List management helpers
  // ----------------------------------------------------------

  private void updateOneIndex(String tableName, long metaID, long cdoid, int newVersion, int oldIndex, int newIndex)
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("updateOneIndex ({0},{1},{2},{3},{4})", tableName, cdoid, newVersion, oldIndex, newIndex);
    }

    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.MOVE_ONE_INDEX, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder builder = new StringBuilder("UPDATE ");
        builder.append(tableName);
        builder.append(" SET ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" = ?, ");
        builder.append(CDODBSchema.REFERENCES_VERSION);
        builder.append(" = ? WHERE ");
        if (metaID != 0)
        {
          builder.append(CDODBSchema.REFERENCES_FEATURE);
          builder.append("= ? AND ");
        }

        builder.append(CDODBSchema.REFERENCES_SOURCE);
        builder.append("= ? AND ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" = ?");

        stmt = getConnection().prepareStatement(builder.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.MOVE_ONE_INDEX, tableName, stmt);
        }
      }

      int idx = 1;
      stmt.setInt(idx++, newIndex);
      stmt.setInt(idx++, newVersion);

      if (metaID != 0)
      {
        stmt.setLong(idx++, metaID);
      }

      stmt.setLong(idx++, cdoid);
      stmt.setLong(idx++, oldIndex);

      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  /**
   * Move references downwards to close a gap at position <code>index</code>. Only indexes starting with
   * <code>index + 1</code> and ending with <code>upperIndex</code> are moved down.
   */
  private void move1down(String tableName, long metaID, long cdoid, int newVersion, int index, int upperIndex)
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("move1down({0},{1},{2},{3},{4})", tableName, cdoid, newVersion, index, upperIndex);
    }

    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.MOVE_RANGE_1_DOWN, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder builder = new StringBuilder();
        builder.append("UPDATE ");
        builder.append(tableName);
        builder.append(" SET ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" = ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append("-1 ,");
        builder.append(CDODBSchema.REFERENCES_VERSION);
        builder.append(" = ? WHERE ");
        if (metaID != 0)
        {
          builder.append(CDODBSchema.REFERENCES_FEATURE);
          builder.append("= ? AND ");
        }

        builder.append(CDODBSchema.REFERENCES_SOURCE);
        builder.append("= ? AND ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" > ? AND ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" <= ?");

        stmt = getConnection().prepareStatement(builder.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.MOVE_RANGE_1_DOWN, tableName, stmt);
        }
      }

      int idx = 1;
      stmt.setInt(idx++, newVersion);

      if (metaID != 0)
      {
        stmt.setLong(idx++, metaID);
      }

      stmt.setLong(idx++, cdoid);
      stmt.setInt(idx++, index);
      stmt.setInt(idx++, upperIndex);

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  /**
   * Move references downwards to close a gap at position <code>index</code>. All indexes starting with
   * <code>index + 1</code> are moved down.
   */
  private void move1down(String tableName, long metaID, long cdoid, int newVersion, int index)
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("move1down({0},{1},{2},{3})", tableName, cdoid, newVersion, index);
    }

    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.MOVE_1_DOWN, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder builder = new StringBuilder();
        builder.append("UPDATE ");
        builder.append(tableName);
        builder.append(" SET ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" = ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append("-1 ,");
        builder.append(CDODBSchema.REFERENCES_VERSION);
        builder.append(" = ? WHERE ");
        if (metaID != 0)
        {
          builder.append(CDODBSchema.REFERENCES_FEATURE);
          builder.append("= ? AND ");
        }

        builder.append(CDODBSchema.REFERENCES_SOURCE);
        builder.append("= ? AND ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" > ?");

        stmt = getConnection().prepareStatement(builder.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.MOVE_1_DOWN, tableName, stmt);
        }
      }

      int idx = 1;
      stmt.setInt(idx++, newVersion);

      if (metaID != 0)
      {
        stmt.setLong(idx++, metaID);
      }

      stmt.setLong(idx++, cdoid);
      stmt.setInt(idx++, index);

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }

    }
  }

  /**
   * Move references upwards to make room at position <code>index</code>. Only indexes starting with <code>index</code>
   * and ending with <code>upperIndex - 1</code> are moved up.
   */
  private void move1up(String tableName, long metaID, long cdoid, int newVersion, int index, int upperIndex)
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("move1up({0},{1},{2},{3},{4})", tableName, cdoid, newVersion, index, upperIndex);
    }

    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.MOVE_RANGE_1_UP, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder builder = new StringBuilder();
        builder.append("UPDATE ");
        builder.append(tableName);
        builder.append(" SET ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" = ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append("+1 ,");
        builder.append(CDODBSchema.REFERENCES_VERSION);
        builder.append(" = ? WHERE ");
        if (metaID != 0)
        {
          builder.append(CDODBSchema.REFERENCES_FEATURE);
          builder.append("= ? AND ");
        }

        builder.append(CDODBSchema.REFERENCES_SOURCE);
        builder.append("= ? AND ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" => ? AND ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" < ?");

        stmt = getConnection().prepareStatement(builder.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.MOVE_RANGE_1_UP, tableName, stmt);
        }
      }

      int idx = 1;
      stmt.setInt(idx++, newVersion);

      if (metaID != 0)
      {
        stmt.setLong(idx++, metaID);
      }

      stmt.setLong(idx++, cdoid);
      stmt.setInt(idx++, index);
      stmt.setInt(idx++, upperIndex);

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }

    }
  }

  /**
   * Move references upwards to make room at position <code>index</code>. Only indexes starting with <code>index</code>.
   */
  private void move1up(String tableName, long metaID, long cdoid, int newVersion, int index)
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("move1up({0},{1},{2},{3})", tableName, cdoid, newVersion, index);
    }

    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.MOVE_1_UP, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder builder = new StringBuilder();
        builder.append("UPDATE ");
        builder.append(tableName);
        builder.append(" SET ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" = ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append("+1 ,");
        builder.append(CDODBSchema.REFERENCES_VERSION);
        builder.append(" = ? WHERE ");
        if (metaID != 0)
        {
          builder.append(CDODBSchema.REFERENCES_FEATURE);
          builder.append("= ? AND ");
        }

        builder.append(CDODBSchema.REFERENCES_SOURCE);
        builder.append("= ? AND ");
        builder.append(CDODBSchema.REFERENCES_IDX);
        builder.append(" >= ?");

        stmt = getConnection().prepareStatement(builder.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.MOVE_1_UP, tableName, stmt);
        }
      }

      int idx = 1;
      stmt.setInt(idx++, newVersion);

      if (metaID != 0)
      {
        stmt.setLong(idx++, metaID);
      }

      stmt.setLong(idx++, cdoid);
      stmt.setInt(idx++, index);

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }

    }
  }

  private void deleteReferenceRow(String tableName, long metaID, long cdoid, int index)
  {
    PreparedStatement stmt = null;
    if (cacheStatements)
    {
      stmt = getCachedStatement(StmtType.DELETE_ONE_REFERENCE, tableName);
    }

    try
    {
      if (stmt == null)
      {
        StringBuilder sql = new StringBuilder("DELETE FROM ");
        sql.append(tableName);
        sql.append(" WHERE ");
        sql.append(CDODBSchema.REFERENCES_SOURCE);
        sql.append(" = ? AND ");
        sql.append(CDODBSchema.REFERENCES_IDX);
        sql.append(" = ? ");

        if (metaID != 0)
        {
          sql.append("AND");
          sql.append(CDODBSchema.REFERENCES_FEATURE);
          sql.append(" = ? ");
        }

        stmt = getConnection().prepareStatement(sql.toString());
        if (cacheStatements)
        {
          cacheStatement(StmtType.DELETE_ONE_REFERENCE, tableName, stmt);
        }
      }

      stmt.setLong(1, cdoid);
      stmt.setInt(2, index);
      if (metaID != 0)
      {
        stmt.setLong(3, metaID);
      }

      if (TRACER.isEnabled())
      {
        TRACER.trace(stmt.toString());
      }

      stmt.execute();
    }
    catch (SQLException e)
    {
      throw new DBException(e);
    }
    finally
    {
      if (!cacheStatements)
      {
        DBUtil.close(stmt);
      }
    }
  }

  // ----------------------------------------------------------
  // Statement caching
  // ----------------------------------------------------------

  /**
   * Add a dirty statement to the dirty statements container.
   */
  private void addDirtyStatement(StmtType type, String subKey, PreparedStatement stmt)
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("Adding dirty statement: ({0},{1}) -> {2}", type, subKey, stmt);
    }

    dirtyStatements.put(new CacheKey(type, subKey), stmt);
  }

  /**
   * Query the dirty statements container.
   * 
   * @return
   */
  private PreparedStatement getDirtyStatement(StmtType type, String subKey)
  {
    return dirtyStatements.get(CacheKey.useOnce(type, subKey));
  }

  /**
   * Cache a prepared statement.
   */
  private void cacheStatement(StmtType type, String subKey, PreparedStatement stmt)
  {
    cacheStatement(new CacheKey(type, subKey), stmt);
  }

  /**
   * Cache a prepared statement with given key.
   */
  private void cacheStatement(CacheKey key, PreparedStatement stmt)
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("Adding cached statement: {0} -> {1}", key, stmt);
    }

    statementCache.put(key, new WrappedPreparedStatement(stmt));
  }

  /**
   * Query the cache of prepared statements.
   */
  private PreparedStatement getCachedStatement(StmtType type, String subKey)
  {
    WrappedPreparedStatement wrapped = statementCache.get(CacheKey.useOnce(type, subKey));
    if (wrapped == null)
    {
      return null;
    }

    PreparedStatement stmt = wrapped.getWrappedStatement();
    if (TRACER.isEnabled())
    {
      TRACER.format("Using cached statement: ({0},{1}) -> {2}", type, subKey, stmt);
    }

    return stmt;
  }

  private PreparedStatement getAndRemoveCachedStatement(StmtType type, String subKey)
  {
    WrappedPreparedStatement wrapped = statementCache.remove(CacheKey.useOnce(type, subKey));
    if (wrapped == null)
    {
      return null;
    }

    PreparedStatement stmt = wrapped.unwrapStatement();
    if (TRACER.isEnabled())
    {
      TRACER.format("Removing cached statement: ({0},{1}) -> {2}", type, subKey, stmt);
    }

    return stmt;
  }

  /**
   * @author Stefan Winkler
   */
  public static enum CachingEnablement
  {
    ENABLED, DISABLED, GUESS
  }

  /**
   * Statement type as first part of the statement cache key.
   * 
   * @author Stefan Winkler
   */
  private static enum StmtType
  {
    INSERT_ATTRIBUTES, DELETE_ATTRIBUTES, INSERT_REFERENCES, DELETE_REFERENCES, DELETE_ONE_REFERENCE, REVISE_VERSION, REVISE_UNREVISED, GENERAL, UPDATE_REFERENCE_VERSION, MOVE_1_UP, MOVE_RANGE_1_UP, MOVE_1_DOWN, MOVE_RANGE_1_DOWN, MOVE_ONE_INDEX, UPDATE_REFERENCE
  }

  /**
   * Convenience definition for Pair<StmtType, String>
   * 
   * @author Stefan Winkler
   */
  private static class CacheKey extends Pair<StmtType, String>
  {
    public CacheKey(StmtType type, String subKey)
    {
      super(type, subKey);
    }

    private static CacheKey useOnceKey = new CacheKey(StmtType.GENERAL, "");

    /**
     * Memory-resource-friendly method which uses a single static field, modifies it and returns it to be used at once,
     * e.g., to use it in a cache lookup. Do not store a reference to the result!!!
     */
    public static CacheKey useOnce(StmtType type, String subKey)
    {
      useOnceKey.setElement1(type);
      useOnceKey.setElement2(subKey);
      return useOnceKey;
    }
  }
}

Back to the top