-
Notifications
You must be signed in to change notification settings - Fork 104
/
SQLBackendImpl.java
1193 lines (1057 loc) · 55.1 KB
/
SQLBackendImpl.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
/**
* Copyright 2014-2017 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-cygnus (FIWARE project).
*
* fiware-cygnus is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
* fiware-cygnus is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License along with fiware-cygnus. If not, see
* http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License please contact with iot_support at tid dot es
*/
package com.telefonica.iot.cygnus.backends.sql;
import com.google.gson.JsonElement;
import com.sun.rowset.CachedRowSetImpl;
import com.telefonica.iot.cygnus.errors.CygnusBadContextData;
import com.telefonica.iot.cygnus.errors.CygnusPersistenceError;
import com.telefonica.iot.cygnus.errors.CygnusRuntimeError;
import com.telefonica.iot.cygnus.log.CygnusLogger;
import com.telefonica.iot.cygnus.utils.CommonUtils;
import com.telefonica.iot.cygnus.backends.sql.Enum.SQLInstance;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
import javax.sql.DataSource;
import javax.sql.rowset.CachedRowSet;
import java.sql.*;
import java.text.ParseException;
import java.time.Instant;
import java.util.*;
import java.util.Date;
/**
* The type Sql backend.
*/
public class SQLBackendImpl implements SQLBackend{
private static final CygnusLogger LOGGER = new CygnusLogger(SQLBackendImpl.class);
private SQLBackendImpl.SQLDriver driver;
private final SQLCache cache;
protected SQLInstance sqlInstance;
private final boolean persistErrors;
private final int maxLatestErrors;
private static final String DEFAULT_ERROR_TABLE_SUFFIX = "_error_log";
private static final int DEFAULT_MAX_LATEST_ERRORS = 100;
private static final String DEFAULT_LIMIT_SELECT_EXP_RECORDS = "4096";
private String nlsTimestampFormat;
private String nlsTimestampTzFormat;
/**
* Constructor.
*
* @param sqlHost
* @param sqlPort
* @param sqlUsername
* @param sqlPassword
* @param maxPoolSize
* @param maxPoolIdle
* @param minPoolIdle
* @param minPoolIdleTimeMillis
* @param sqlInstance
* @param sqlDriverName
* @param persistErrors
* @param maxLatestErrors
*/
public SQLBackendImpl(String sqlHost, String sqlPort, String sqlUsername, String sqlPassword, int maxPoolSize, int maxPoolIdle, int minPoolIdle, int minPoolIdleTimeMillis, SQLInstance sqlInstance, String sqlDriverName, boolean persistErrors, int maxLatestErrors) {
this(sqlHost, sqlPort, sqlUsername, sqlPassword, maxPoolSize, maxPoolIdle, minPoolIdle, minPoolIdleTimeMillis, sqlInstance, sqlDriverName, null, persistErrors, maxLatestErrors);
} // SQLBackendImpl
/**
* Constructor. (invoked by ngsild sinks)
*
* @param sqlHost
* @param sqlPort
* @param sqlUsername
* @param sqlPassword
* @param maxPoolSize
* @param maxPoolIdle
* @param minPoolIdle
* @param minPoolIdleTimeMillis
* @param sqlInstance
* @param sqlDriverName
* @param sqlOptions
*/
public SQLBackendImpl(String sqlHost, String sqlPort, String sqlUsername, String sqlPassword, int maxPoolSize, int maxPoolIdle, int minPoolIdle, int minPoolIdleTimeMillis, SQLInstance sqlInstance, String sqlDriverName, String sqlOptions) {
this(sqlHost, sqlPort, sqlUsername, sqlPassword, maxPoolSize, maxPoolIdle, minPoolIdle, minPoolIdleTimeMillis, sqlInstance, sqlDriverName, sqlOptions, true, DEFAULT_MAX_LATEST_ERRORS);
} // SQLBackendImpl
/**
* Constructor.
*
* @param sqlHost
* @param sqlPort
* @param sqlUsername
* @param sqlPassword
* @param maxPoolSize
* @param maxPoolIdle
* @param minPoolIdle
* @param minPoolIdleTimeMillis
* @param sqlInstance
* @param sqlDriverName
* @param sqlOptions
* @param persistErrors
* @param maxLatestErrors
*/
public SQLBackendImpl(String sqlHost, String sqlPort, String sqlUsername, String sqlPassword, int maxPoolSize, int maxPoolIdle, int minPoolIdle, int minPoolIdleTimeMillis, SQLInstance sqlInstance, String sqlDriverName, String sqlOptions, boolean persistErrors, int maxLatestErrors) {
driver = new SQLBackendImpl.SQLDriver(sqlHost, sqlPort, sqlUsername, sqlPassword, maxPoolSize, maxPoolIdle, minPoolIdle, minPoolIdleTimeMillis, sqlInstance, sqlDriverName, sqlOptions);
cache = new SQLCache();
this.sqlInstance = sqlInstance;
this.persistErrors = persistErrors;
this.maxLatestErrors = maxLatestErrors;
} // SQLBackendImpl
/**
* Releases resources
*/
public void close(){
if (driver != null) driver.close();
} // close
/**
* Sets the SQL driver. It is protected since it is only used by the
* tests.
*
* @param driver The SQL driver to be set.
*/
public void setDriver(SQLBackendImpl.SQLDriver driver) {
this.driver = driver;
} // setDriver
public SQLBackendImpl.SQLDriver getDriver() {
return driver;
} // getDriver
/**
* Set NLS_TIMESTAMP_FORMAT and NLS_TIMESTAMP_TZ_FORMAT
*
* @param format
**/
public void setNlsTimestampFormat(String format) {
this.nlsTimestampFormat = format;
} // setNlsTimestampFormat
public String getNlsTimestampFormat() {
return nlsTimestampFormat;
} // getNlsTImestampFormat
public void setNlsTimestampTzFormat(String format) {
this.nlsTimestampTzFormat = format;
} // setNlsTimestampTzFormat
public String getNlsTimestampTzFormat() {
return nlsTimestampTzFormat;
} // getNlsTImestampTzFormat
@Override
public void createDestination(String destination) throws CygnusRuntimeError, CygnusPersistenceError {
if (cache.isCachedDataBase(destination)) {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " '" + destination + "' is cached, thus it is not created");
return;
} // if
Statement stmt = null;
// get a connection to an empty destination
Connection con = driver.getConnection("");
String query = "";
if (sqlInstance == SQLInstance.MYSQL) {
query = "create database if not exists `" + destination + "`";
} else if (sqlInstance == SQLInstance.POSTGRESQL) {
query = "CREATE SCHEMA IF NOT EXISTS " + destination;
}
try {
stmt = con.createStatement();
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Database/scheme creation error", "SQLException", e.getMessage());
} // try catch
try {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Executing SQL query '" + query + "'");
stmt.executeUpdate(query);
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Database/scheme creation error", "SQLException", e.getMessage());
} // try catch
closeSQLObjects(con, stmt);
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Trying to add '" + destination + "' to the cache after database/scheme creation");
cache.addDataBase(destination);
} // createDestination
// This method is an implementation for the method createDestination in order to make it easier to understand
public void createDataBase (String dataBase) throws CygnusPersistenceError, CygnusRuntimeError {
createDestination(dataBase);
}
// This method is an implementation for the method createDestination in order to make it easier to understand
public void createSchema (String schema) throws CygnusPersistenceError, CygnusRuntimeError {
createDestination(schema);
}
@Override
public void createTable(String dataBase, String schema, String table, String typedFieldNames)
throws CygnusRuntimeError, CygnusPersistenceError {
String tableName = table;
if (sqlInstance == SQLInstance.POSTGRESQL) {
tableName = schema + "." + table;
}
if (cache.isCachedTable(dataBase, tableName)) {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " '" + tableName + "' is cached, thus it is not created");
return;
} // if
Statement stmt = null;
// get a connection to the given destination
Connection con = driver.getConnection(dataBase);
String query = "";
if (sqlInstance == SQLInstance.MYSQL) {
query = "create table if not exists `" + tableName + "`" + typedFieldNames;
} else if (sqlInstance == SQLInstance.POSTGRESQL) {
query = "CREATE TABLE IF NOT EXISTS " + tableName + " " + typedFieldNames;
} else if (sqlInstance == SQLInstance.ORACLE) {
// FIXME: Add an oracle workaround for "if not exists"
query = "CREATE TABLE " + tableName + " " + typedFieldNames;
}
try {
stmt = con.createStatement();
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Table creation error", "SQLException", e.getMessage());
} // try catch
try {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Executing SQL query '" + query + "'");
stmt.executeUpdate(query);
} catch (SQLTimeoutException e) {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Table creation error. Query " + query, "SQLTimeoutException", e.getMessage());
} catch (SQLException e) {
closeSQLObjects(con, stmt);
persistError(dataBase, schema, query, e);
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Table creation error", "SQLException", e.getMessage());
} // try catch
closeSQLObjects(con, stmt);
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Trying to add '" + tableName + "' to the cache after table creation");
cache.addTable(dataBase, tableName);
} // createTable
// FXIME insertContextData Never used ?
@Override
public void insertContextData(String dataBase, String schema, String table, String fieldNames, String fieldValues)
throws CygnusBadContextData, CygnusRuntimeError, CygnusPersistenceError {
Statement stmt = null;
String tableName = table;
// get a connection to the given destination
Connection con = driver.getConnection(dataBase);
String query = "";
if (sqlInstance == SQLInstance.MYSQL) {
query = "insert into `" + tableName + "` " + fieldNames + " values " + fieldValues;
} else if (sqlInstance == SQLInstance.POSTGRESQL) {
tableName = schema + "." + table;
query = "INSERT INTO " + tableName + " " + fieldNames + " VALUES " + fieldValues;
} else if (sqlInstance == SQLInstance.ORACLE) {
query = "INSERT INTO " + tableName + " " + fieldNames + " VALUES " + fieldValues;
}
try {
stmt = con.createStatement();
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Data insertion error", "SQLException", e.getMessage());
} // try catch
try {
LOGGER.debug(sqlInstance.toString().toUpperCase() + "Database: " + dataBase + " Executing SQL query '" + query + "'");
stmt.executeUpdate(query);
LOGGER.info(sqlInstance.toString().toUpperCase() + "Database: " + dataBase + " Executed SQL query '" + query + "'");
} catch (SQLTimeoutException e) {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + "Database: " + dataBase + " Data insertion error. Query insert into `" + tableName + "` " + fieldNames + " values " + fieldValues, "SQLTimeoutException", e.getMessage());
} catch (SQLException e) {
persistError(dataBase, schema, query, e);
throw new CygnusBadContextData(sqlInstance.toString().toUpperCase() + "Database: " + dataBase + " Data insertion error. Query: insert into `" + tableName + "` " + fieldNames + " values " + fieldValues, "SQLException", e.getMessage());
} finally {
closeSQLObjects(con, stmt);
} // try catch
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Trying to add '" + dataBase + "' and '" + tableName + "' to the cache after insertion");
cache.addDataBase(dataBase);
cache.addTable(dataBase, tableName);
} // insertContextData
private CachedRowSet select(String dataBase, String schema, String tableName, String selection)
throws CygnusRuntimeError, CygnusPersistenceError {
Statement stmt = null;
// get a connection to the given destination
Connection con = driver.getConnection(dataBase);
String query = "";
if (sqlInstance == SQLInstance.MYSQL) {
query = "select " + selection + " from `" + tableName + "` order by recvTime desc limit " + DEFAULT_LIMIT_SELECT_EXP_RECORDS;
} else if (sqlInstance == SQLInstance.POSTGRESQL) {
if (schema != null && (!tableName.startsWith(schema))) {
tableName = schema + '.' + tableName;
}
query = "select " + selection + " from " + tableName + " order by recvTime desc limit " + DEFAULT_LIMIT_SELECT_EXP_RECORDS;
} else {
query = "select " + selection + " from " + tableName + " order by recvTime desc limit " + DEFAULT_LIMIT_SELECT_EXP_RECORDS;
}
try {
stmt = con.createStatement();
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Querying error", "SQLException", e.getMessage());
} // try catch
try {
// to-do: refactor after implementing
// https://github.com/telefonicaid/fiware-cygnus/issues/1371
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Executing SQL query '" + query + "'");
ResultSet rs = stmt.executeQuery(query);
// A CachedRowSet is "disconnected" from the source, thus can be
// used once the statement is closed
@SuppressWarnings("restriction")
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(rs); // FIXME: close Resultset Objects??
closeSQLObjects(con, stmt);
rs.close();
return crs;
} catch (SQLTimeoutException e) {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Data select error. Query " + query, "SQLTimeoutException", e.getMessage());
} catch (SQLException e) {
closeSQLObjects(con, stmt);
persistError(dataBase, schema, query, e);
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Querying error", "SQLException", e.getMessage());
} // try catch
} // select
private void delete(String dataBase, String schema, String tableName, String filters)
throws CygnusRuntimeError, CygnusPersistenceError {
Statement stmt = null;
// get a connection to the given destination
Connection con = driver.getConnection(dataBase);
String query = "";
if (sqlInstance == SQLInstance.MYSQL) {
query = "delete from `" + tableName + "` where " + filters;
} else if (sqlInstance == SQLInstance.POSTGRESQL) {
if (schema != null && (!tableName.startsWith(schema))) {
tableName = schema + '.' + tableName;
}
query = "delete from " + tableName + " where " + filters;
} else {
query = "delete from " + tableName + " where " + filters;
}
try {
stmt = con.createStatement();
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Deleting error", "SQLException", e.getMessage());
} // try catch
try {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Executing SQL query '" + query + "'");
stmt.executeUpdate(query);
} catch (SQLTimeoutException e) {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Data delete error. Query " + query, "SQLTimeoutException", e.getMessage());
} catch (SQLException e) {
closeSQLObjects(con, stmt);
persistError(dataBase, schema, query, e);
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Deleting error", "SQLException", e.getMessage());
} // try catch
closeSQLObjects(con, stmt);
} // delete
@Override
public void capRecords(String dataBase, String schemaName, String tableName, long maxRecords)
throws CygnusRuntimeError, CygnusPersistenceError {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " capRecords for database: " +
dataBase + " schema: " + schemaName + " tableName: " + tableName);
// Get the records within the table
CachedRowSet records = select(dataBase, schemaName, tableName, "*");
// Get the number of records
int numRecords = 0;
try {
if (records.last()) {
numRecords = records.getRow();
records.beforeFirst();
} // if
} catch (SQLException e) {
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Data capping error", "SQLException", e.getMessage());
} // try catch
// Get the reception times (they work as IDs) for future deletion
// to-do: refactor after implementing
// https://github.com/telefonicaid/fiware-cygnus/issues/1371
String filters = "";
try {
if (numRecords > maxRecords) {
for (int i = 0; i < (numRecords - maxRecords); i++) {
records.next();
String recvTime = records.getString("recvTime");
if (filters.isEmpty()) {
filters += "recvTime='" + recvTime + "'";
} else {
filters += " or recvTime='" + recvTime + "'";
} // if else
} // for
} // if
records.close();
} catch (SQLException e) {
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Data capping error", "SQLException", e.getMessage());
} // try catch
if (filters.isEmpty()) {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " No records to be deleted");
} else {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Records must be deleted (destination=" + dataBase + ",schemaName=" + schemaName + ",tableName=" + tableName + ", filters="
+ filters + ")");
delete(dataBase, schemaName, tableName, filters);
} // if else
} // capRecords
@Override
public void expirateRecordsCache(long expirationTime) throws CygnusRuntimeError, CygnusPersistenceError {
// Iterate on the cached resource IDs
cache.startDataBaseIterator();
while (cache.hasNextDataBase()) {
String dataBase = cache.nextDataBase();
cache.startTableIterator(dataBase);
while (cache.hasNextTable(dataBase)) {
String tableName = cache.nextTable(dataBase);
// Get schema from tableName if PSQL, just for persistError after
String schema = null;
if (sqlInstance == SQLInstance.POSTGRESQL) {
String[] parts = tableName.split("\\.");
if (parts.length > 0) {
schema = parts[0];
}
}
LOGGER.debug(sqlInstance.toString().toUpperCase() + " expirateRecordsCache for database: " +
dataBase + " schema: " + schema + " tableName: " + tableName);
// Get the records within the table
CachedRowSet records = select(dataBase, schema, tableName, "*");
// Get the number of records
int numRecords = 0;
try {
if (records.last()) {
numRecords = records.getRow();
records.beforeFirst();
} // if
} catch (SQLException e) {
try {
records.close();
} catch (SQLException e1) {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Can't close CachedRowSet.");
}
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Data expiration error", "SQLException", e.getMessage());
} // try catch
// Get the reception times (they work as IDs) for future
// deletion
// to-do: refactor after implementing
// https://github.com/telefonicaid/fiware-cygnus/issues/1371
String filters = "";
try {
for (int i = 0; i < numRecords; i++) {
records.next();
String recvTime = records.getString("recvTime");
long recordTime = CommonUtils.getMilliseconds(recvTime);
long currentTime = new java.util.Date().getTime();
if (recordTime < (currentTime - (expirationTime * 1000))) {
if (filters.isEmpty()) {
filters += "recvTime='" + recvTime + "'";
} else {
filters += " or recvTime='" + recvTime + "'";
} // if else
} else {
break;
} // if else
} // for
} catch (SQLException e) {
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Data expiration error", "SQLException", e.getMessage());
} catch (ParseException e) {
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Data expiration error", "ParseException", e.getMessage());
} catch (Exception e) {
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Data expiration error", "Exception", e.getMessage());
} // try catch
if (filters.isEmpty()) {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " No records to be deleted");
} else {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Records must be deleted (destination=" + dataBase + ",schemaName=" + schema + ",tableName=" + tableName + ", filters="
+ filters + ")");
delete(dataBase, schema, tableName, filters);
} // if else
} // while
} // while
} // expirateRecordsCache
/**
* Close all the SQL objects previously opened by doCreateTable and
* doQuery.
*
* @param con
* @param stmt
* @return True if the SQL objects have been closed, false otherwise.
*/
private void closeSQLObjects(Connection con, Statement stmt) throws CygnusRuntimeError {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Closing SQL connection objects.");
closeStatement(stmt);
closeConnection(con);
} // closeSQLObjects
/**
* Close SQL objects previously opened by doCreateTable and
* doQuery.
*
* @param statement
* @return True if the SQL objects have been closed, false otherwise.
*/
private void closeStatement (Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
LOGGER.warn(sqlInstance.toString().toUpperCase() + " error closing invalid statement: " + e.getMessage());
} // try catch
} // if
}
/**
* Close SQL objects previously opened by doCreateTable and
* doQuery.
*
* @param connection
* @return True if the SQL objects have been closed, false otherwise.
*/
private void closeConnection (Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LOGGER.warn(sqlInstance.toString().toUpperCase() + " error closing invalid connection: " + e.getMessage());
} // try catch
} // if
}
public void createErrorTable(String dataBase, String schema)
throws CygnusRuntimeError, CygnusPersistenceError {
// the default table for error log will be called the same as the destination name
String errorTableName = dataBase + DEFAULT_ERROR_TABLE_SUFFIX;
if (sqlInstance == SQLInstance.POSTGRESQL) {
errorTableName = schema + "." + dataBase + DEFAULT_ERROR_TABLE_SUFFIX;
}
String typedFieldNames = "(" +
"timestamp TIMESTAMP NOT NULL" +
", error text" +
", query text" +
", CONSTRAINT PK_ErrorLog PRIMARY KEY (timestamp) )";
String typedFieldNamesOracle = "(" +
"timestamp TIMESTAMP NOT NULL" +
", error clob" +
", query clob" +
", CONSTRAINT PK_ErrorLog PRIMARY KEY (timestamp) )";
Statement stmt = null;
// get a connection to the given destination
Connection con = driver.getConnection(dataBase);
String query = "";
if (sqlInstance == SQLInstance.MYSQL) {
query = "create table if not exists `" + errorTableName + "`" + typedFieldNames;
} else if (sqlInstance == SQLInstance.POSTGRESQL) {
query = "CREATE TABLE IF NOT EXISTS " + errorTableName + " " + typedFieldNames;
} else if (sqlInstance == SQLInstance.ORACLE) {
// FIXME: Add an oracle workaround for "if not exists"
query = "CREATE TABLE " + errorTableName + " " + typedFieldNamesOracle;
}
try {
stmt = con.createStatement();
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Table creation error", "SQLException", e.getMessage());
} // try catch
try {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Executing SQL query '" + query + "'");
stmt.executeUpdate(query);
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Table creation error", "SQLException", e.getMessage());
} // try catch
closeSQLObjects(con, stmt);
} // createErrorTable
/**
* Upsert transaction.
*
* @param aggregation the aggregation
* @param lastData the last data
* @param lastDataDelete the last data delete
* @param dataBase the dataBase
* @param tableName the table name
* @param tableSuffix the table suffix
* @param uniqueKey the unique key
* @param timestampKey the timestamp key
* @param timestampFormat the timestamp format
* @param attrNativeTypes the attr native types
* @throws CygnusPersistenceError the cygnus persistence error
* @throws CygnusBadContextData the cygnus bad context data
* @throws CygnusRuntimeError the cygnus runtime error
* @throws CygnusPersistenceError the cygnus persistence error
*/
public void upsertTransaction (LinkedHashMap<String, ArrayList<JsonElement>> aggregation,
LinkedHashMap<String, ArrayList<JsonElement>> lastData,
LinkedHashMap<String, ArrayList<JsonElement>> lastDataDelete,
String dataBase,
String schema,
String tableName,
String tableSuffix,
String uniqueKey,
String timestampKey,
String timestampFormat,
boolean attrNativeTypes)
throws CygnusPersistenceError, CygnusBadContextData, CygnusRuntimeError {
Connection connection = null;
String upsertQuerys = new String();
String currentUpsertQuery = new String();
int insertedRows[];
try {
connection = driver.getConnection(dataBase);
connection.setAutoCommit(false);
ArrayList<StringBuffer> upsertQuerysList = SQLQueryUtils.sqlUpsertQuery(aggregation,
lastData,
lastDataDelete,
tableName,
tableSuffix,
uniqueKey,
timestampKey,
timestampFormat,
sqlInstance,
dataBase,
schema,
attrNativeTypes);
// Ordering queries to avoid deadlocks. See issue #2197 for more detail
upsertQuerysList.sort(Comparator.comparing(buff -> buff.toString()));
for (StringBuffer query : upsertQuerysList) {
PreparedStatement upsertStatement;
currentUpsertQuery = query.toString();
upsertStatement = connection.prepareStatement(currentUpsertQuery);
// FIXME https://github.com/telefonicaid/fiware-cygnus/issues/1959
upsertStatement.executeUpdate();
upsertQuerys = upsertQuerys + " " + query;
}
connection.commit();
LOGGER.info(sqlInstance.toString().toUpperCase() + " Finished transactions into database: " +
dataBase + " \n upsertQuerys: " + upsertQuerys);
} catch (SQLTimeoutException e) {
cygnusSQLRollback(connection);
if (upsertQuerys.isEmpty() && currentUpsertQuery.isEmpty()) {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " " + e.getNextException() +
" Data insertion error. database: " + dataBase +
" connection: " + connection,
" SQLTimeoutException", e.getMessage());
} else {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " " + e.getNextException() +
" Data insertion error. database: " + dataBase +
" upsertQuerys: " + upsertQuerys +
" currentUpsertQuery: " + currentUpsertQuery,
" SQLTimeoutException", e.getMessage());
}
} catch (SQLException e) {
cygnusSQLRollback(connection);
if (upsertQuerys.isEmpty() && currentUpsertQuery.isEmpty()) {
persistError(dataBase, schema, null, e);
throw new CygnusBadContextData(sqlInstance.toString().toUpperCase() + " " + e.getNextException() +
" Data insertion error. database: " + dataBase +
" connection: " + connection,
" SQLException", e.getMessage());
} else {
String allQueries = " upsertQuerys: " + upsertQuerys +
" currentUpsertQuery: " + currentUpsertQuery;
persistError(dataBase, schema, allQueries, e);
throw new CygnusBadContextData(sqlInstance.toString().toUpperCase() + " " + e.getNextException() +
" Data insertion error. database: " + dataBase + allQueries,
" SQLException", e.getMessage());
}
} finally {
closeConnection(connection);
} // try catch
if (sqlInstance == SQLInstance.POSTGRESQL) {
tableName = schema + "." + tableName;
}
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Trying to add '" + dataBase + "' and '" + tableName + "' to the cache after upsertion");
cache.addDataBase(dataBase);
cache.addTable(dataBase, tableName);
}
public void insertTransaction (LinkedHashMap<String, ArrayList<JsonElement>> aggregation,
String dataBase,
String schema,
String tableName,
boolean attrNativeTypes)
throws CygnusPersistenceError, CygnusBadContextData, CygnusRuntimeError {
Connection connection = null;
String insertQuery = new String();
try {
connection = driver.getConnection(dataBase);
connection.setAutoCommit(false);
insertQuery = SQLQueryUtils.sqlInsertQuery(aggregation,
tableName,
sqlInstance,
dataBase,
schema,
attrNativeTypes).toString();
PreparedStatement insertStatement;
insertStatement = connection.prepareStatement(insertQuery);
/*
FIXME https://github.com/telefonicaid/fiware-cygnus/issues/1959
Add SQLSafe values with native PreparedStatement methods
insertPreparedStatement = SQLQueryUtils.addJsonValues(insertStatement, aggregation, attrNativeTypes);
*/
insertStatement.executeUpdate();
connection.commit();
LOGGER.info(sqlInstance.toString().toUpperCase() + " Finished transactions into database: " +
dataBase + " \n insertQuery: " + insertQuery);
} catch (SQLTimeoutException e) {
cygnusSQLRollback(connection);
if (insertQuery.isEmpty()) {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " " + e.getNextException() +
" Data insertion error. database: " + dataBase +
" connection: " + connection,
" SQLTimeoutException", e.getMessage());
} else {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " " + e.getNextException() +
" Data insertion error. database: " + dataBase +
" insertQuery: " + insertQuery,
" SQLTimeoutException", e.getMessage());
}
} catch (SQLException e) {
cygnusSQLRollback(connection);
if (insertQuery.isEmpty()) {
persistError(dataBase, schema, null, e);
throw new CygnusBadContextData(sqlInstance.toString().toUpperCase() + " " + e.getNextException() +
" Data insertion error. database: " + dataBase +
" connection: `" + connection,
" SQLException", e.getMessage());
} else {
String allQueries = " insertQuery: " + insertQuery;
persistError(dataBase, schema, allQueries, e);
throw new CygnusBadContextData(sqlInstance.toString().toUpperCase() + " " + e.getNextException() +
" Data insertion error. database: " + dataBase + allQueries,
" SQLException", e.getMessage());
}
} finally {
closeConnection(connection);
} // try catch
if (sqlInstance == SQLInstance.POSTGRESQL) {
tableName = schema + "." + tableName;
}
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Trying to add '" + dataBase + "' and '" + tableName + "' to the cache after insertion");
cache.addDataBase(dataBase);
cache.addTable(dataBase, tableName);
}
private void cygnusSQLRollback (Connection connection) {
try {
connection.rollback();
} catch (SQLException e) {
LOGGER.error("Error when rollingback transaction " + e.getMessage());
}
}
public void purgeErrorTable(String dataBase, String schema)
throws CygnusRuntimeError, CygnusPersistenceError {
// the default table for error log will be called the same as the destination name
String errorTableName = dataBase + DEFAULT_ERROR_TABLE_SUFFIX;
if (sqlInstance == SQLInstance.POSTGRESQL) {
errorTableName = schema + "." + dataBase + DEFAULT_ERROR_TABLE_SUFFIX;
}
String limit = String.valueOf(maxLatestErrors);
Statement stmt = null;
// get a connection to the given destination
Connection con = driver.getConnection(dataBase);
String query = "";
if (sqlInstance == SQLInstance.MYSQL) {
query = "delete from `" + errorTableName + "` " + "where timestamp not in (select timestamp from (select timestamp from `" + errorTableName + "` " + "order by timestamp desc limit " + limit + " ) tmppurge )";
} else if (sqlInstance == SQLInstance.POSTGRESQL) {
query = "DELETE FROM " + errorTableName + " " + "WHERE timestamp NOT IN (SELECT timestamp FROM (SELECT timestamp FROM " + errorTableName + " " + "ORDER BY timestamp DESC LIMIT " + limit + " ) tmppurge )";
} else if (sqlInstance == SQLInstance.ORACLE) {
// FXIME: add limit
query = "DELETE FROM " + errorTableName + " " + "WHERE timestamp NOT IN (SELECT timestamp FROM (SELECT timestamp FROM " + errorTableName + " " + "ORDER BY timestamp DESC ) tmppurge )";
}
try {
stmt = con.createStatement();
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusRuntimeError(sqlInstance.toString().toUpperCase() + " Purge error table error", "SQLException", e.getMessage());
} // try catch
try {
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Executing SQL query '" + query + "'");
stmt.executeUpdate(query);
} catch (SQLException e) {
closeSQLObjects(con, stmt);
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Purge error table error", "SQLException", e.getMessage());
} // try catch
closeSQLObjects(con, stmt);
}
private void insertErrorLog(String dataBase, String schema, String errorQuery, Exception exception)
throws CygnusBadContextData, CygnusRuntimeError, CygnusPersistenceError, SQLException {
java.util.Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
String errorTableName = dataBase + DEFAULT_ERROR_TABLE_SUFFIX;
if (sqlInstance == SQLInstance.POSTGRESQL) {
errorTableName = schema + "." + dataBase + DEFAULT_ERROR_TABLE_SUFFIX;
}
String fieldNames = "(" +
"timestamp" +
", error" +
", query)";
// get a connection to the given destination
Connection con = driver.getConnection(dataBase);
String query = "";
if (sqlInstance == SQLInstance.MYSQL) {
query = "insert into `" + errorTableName + "` " + fieldNames + " values (?, ?, ?)";
} else if (sqlInstance == SQLInstance.POSTGRESQL ||
sqlInstance == SQLInstance.ORACLE){
query = "INSERT INTO " + errorTableName + " " + fieldNames + " VALUES (?, ?, ?)";
}
PreparedStatement preparedStatement = con.prepareStatement(query);
try {
preparedStatement.setObject(1, java.sql.Timestamp.from(Instant.now()));
preparedStatement.setString(2, exception.getMessage());
preparedStatement.setString(3, errorQuery);
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Executing SQL query '" + preparedStatement.toString() + "'");
preparedStatement.executeUpdate();
} catch (SQLTimeoutException e) {
throw new CygnusPersistenceError(sqlInstance.toString().toUpperCase() + " Data insertion error. Query: `" + preparedStatement, "SQLTimeoutException", e.getMessage());
} catch (SQLException e) {
throw new CygnusBadContextData(sqlInstance.toString().toUpperCase() + " Data insertion error. Query: `" + preparedStatement, "SQLException", e.getMessage());
} finally {
closeSQLObjects(con, preparedStatement);
} // try catch
} // insertErrorLog
private void persistError(String destination, String schema, String query, Exception exception) throws CygnusPersistenceError, CygnusRuntimeError {
try {
if (persistErrors) {
try {
// try insert without create error table before
insertErrorLog(destination, schema, query, exception);
} catch (CygnusBadContextData ex) {
createErrorTable(destination, schema);
insertErrorLog(destination, schema, query, exception);
}
purgeErrorTable(destination, schema);
}
return;
} catch (CygnusBadContextData cygnusBadContextData) {
LOGGER.warn(sqlInstance.toString().toUpperCase() + " failed to persist error on database/scheme " + destination + DEFAULT_ERROR_TABLE_SUFFIX + " " + cygnusBadContextData);
} catch (Exception e) {
LOGGER.warn(sqlInstance.toString().toUpperCase() + " failed to persist error on database/scheme " + destination + DEFAULT_ERROR_TABLE_SUFFIX + " " + e);
}
}
public class SQLDriver {
private final HashMap<String, DataSource> datasources;
private final HashMap<String, GenericObjectPool> pools;
private final String sqlHost;
private final String sqlPort;
private final String sqlUsername;
private final String sqlPassword;
private final SQLInstance sqlInstance;
private final String sqlDriverName;
private final int maxPoolSize;
private final int maxPoolIdle;
private final int minPoolIdle;
private final int minPoolIdleTimeMillis;
private final String sqlOptions;
/**
* Constructor.
*
* @param sqlHost
* @param sqlPort
* @param sqlUsername
* @param sqlPassword
* @param maxPoolSize
* @param maxPoolIdle
* @param minPoolIdle
* @param minPoolIdleTimeMillis
* @param sqlInstance
* @param sqlDriverName
* @param sqlOptions
*/
public SQLDriver(String sqlHost, String sqlPort, String sqlUsername, String sqlPassword, int maxPoolSize, int maxPoolIdle, int minPoolIdle, int minPoolIdleTimeMillis, SQLInstance sqlInstance, String sqlDriverName, String sqlOptions) {
datasources = new HashMap<>();
pools = new HashMap<>();
this.sqlHost = sqlHost;
this.sqlPort = sqlPort;
this.sqlUsername = sqlUsername;
this.sqlPassword = sqlPassword;
this.maxPoolSize = maxPoolSize;
this.maxPoolIdle = maxPoolIdle;
this.minPoolIdle = minPoolIdle;
this.minPoolIdleTimeMillis = minPoolIdleTimeMillis;
this.sqlInstance = sqlInstance;
this.sqlDriverName = sqlDriverName;
this.sqlOptions = sqlOptions;
} // SQLDriver
/**
* Gets a connection to the SQL server.
*
* @param destination
* @return
* @throws CygnusRuntimeError
* @throws CygnusPersistenceError
*/
public Connection getConnection(String destination) throws CygnusRuntimeError, CygnusPersistenceError {
try {
// FIXME: the number of cached connections should be limited to
// a certain number; with such a limit
// number, if a new connection is needed, the oldest one is closed
Connection connection = null;
if (datasources.containsKey(destination)) {
connection = datasources.get(destination).getConnection();
LOGGER.debug(sqlInstance.toString().toUpperCase() + " Recovered destination connection from cache (" + destination + ")");