-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecordset.java
More file actions
1780 lines (1468 loc) · 60.3 KB
/
Recordset.java
File metadata and controls
1780 lines (1468 loc) · 60.3 KB
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
package javaxt.sql;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
//******************************************************************************
//** Recordset Class
//*****************************************************************************/
/**
* Used to query and update records in a database.
*
******************************************************************************/
public class Recordset implements AutoCloseable {
private java.sql.ResultSet rs = null;
private java.sql.Statement stmt = null;
private int x;
private int n;
private boolean isReadOnly = true;
private String sqlString = null;
private Connection connection = null;
private Driver driver = null;
private boolean autoCommit = true;
private Value GeneratedKey;
private ArrayList keys = new ArrayList();
/**
* Returns a value that describes if the Recordset object is open, closed,
* connecting, executing or retrieving data
*/
private int State = 0;
/**
* Returns true if the current record position is after the last record,
* otherwise false.
*/
public boolean EOF = false;
/**
* Current record in the Recordset
*/
private javaxt.sql.Record record;
/**
* An array of tables found in the database
*/
private Table[] Tables = null;
private Integer maxRecords = null;
private Integer fetchSize = null;
private int numBatches=0;
private int batchSize=1;
private HashMap<String, java.sql.PreparedStatement> batchedStatements;
private long queryResponseTime, ellapsedTime, metadataQueryTime;
private long startTime, endTime;
private String queryID;
private static AtomicBoolean shuttingDown = new AtomicBoolean(false);
private static final Thread shutdownHook = getShutdownHook();
private static final ConcurrentHashMap<String, Recordset> queries =
new ConcurrentHashMap<>();
private static final AtomicLong openStatements = new AtomicLong(0);
private static final AtomicLong openRecordsets = new AtomicLong(0);
private static final AtomicLong openCalls = new AtomicLong(0);
private static final AtomicLong closeCalls = new AtomicLong(0);
private static boolean debugClose = false;
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class.
*/
public Recordset(){
if (shuttingDown.get()) throw new IllegalStateException("JVM shutting down");
}
//**************************************************************************
//** getShutdownHook
//**************************************************************************
/** Adds a listener to the jvm to watch for shutdown events.
*/
private static Thread getShutdownHook(){
Thread shutdownHook = new Thread() {
public void run() {
shuttingDown.set(true);
synchronized(queries){
java.util.Iterator<String> it = queries.keySet().iterator();
while (it.hasNext()){
Recordset rs = queries.get(it.next());
java.sql.Statement stmt = rs.stmt;
if (stmt!=null){
try{stmt.cancel();} catch(Exception e){}
try{stmt.close();} catch(Exception e){}
}
}
queries.clear();
}
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
return shutdownHook;
}
//**************************************************************************
//** isOpen
//**************************************************************************
/** Returns true if the recordset is open. This method is only supported on
* Java 1.6 or higher. Otherwise, the method will return false.
*/
public boolean isOpen(){
if (State!=0) {
//return !rs.isClosed();
int javaVersion = javaxt.utils.Java.getVersion();
if (javaVersion<6) return false;
else{
try{
return !((Boolean) rs.getClass().getMethod("isClosed").invoke(rs, null));
}
catch(Exception e){
return false;
}
}
}
else return false;
}
//**************************************************************************
//** isReadOnly
//**************************************************************************
/** Returns true if records are read-only.
*/
public boolean isReadOnly(){
return isReadOnly;
}
//**************************************************************************
//** Open
//**************************************************************************
/** Used to execute a query and access records in the database. Records
* fetched using this method cannot be updated or deleted and new records
* cannot be inserted into the database.
*
* @param sql SQL Query. Example: "SELECT * FROM EMPLOYEE"
* @param conn An active connection to the database.
*/
public java.sql.ResultSet open(String sql, Connection conn) throws SQLException {
return open(sql,conn,true);
}
//**************************************************************************
//** Open
//**************************************************************************
/** Used to execute a query and access records in the database.
*
* @param sqlString SQL Query. Example: "SELECT * FROM EMPLOYEE"
* @param connection An active connection to the database.
* @param ReadOnly Set whether the records are read-only. If true, records
* fetched using this method cannot be updated or deleted and new records
* cannot be inserted into the database. If false, records can be updated
* or deleted and new records can be inserted into the database.
*/
public java.sql.ResultSet open(String sqlString, Connection connection, boolean ReadOnly) throws SQLException {
if (shuttingDown.get()) throw new IllegalStateException("JVM shutting down");
if (connection==null) throw new SQLException("Connection is null.");
if (connection.isClosed()) throw new SQLException("Connection is closed.");
if (debugClose) openCalls.incrementAndGet();
rs = null;
stmt = null;
State = 0;
EOF = true;
Tables = null;
this.sqlString = sqlString;
this.connection = connection;
this.isReadOnly = ReadOnly;
this.driver = connection.getDatabase().getDriver();
if (driver==null) driver = new Driver("","","");
startTime = System.currentTimeMillis();
queryResponseTime = ellapsedTime = metadataQueryTime = endTime = 0;
java.sql.Connection Conn = connection.getConnection();
autoCommit = Conn.getAutoCommit();
queryID = UUID.randomUUID().toString();
synchronized(queries){
queries.put(queryID, this);
}
//Read-Only Connection
if (ReadOnly){
try{
//Set AutoCommit to false when fetchSize is specified.
//Otherwise it will fetch back all the records at once
if (fetchSize!=null){
try{
Conn.setAutoCommit(false);
}
catch(Exception e){}
}
//DB2 and SQLite only support forward cursors
if (driver.equals("DB2") || driver.equals("SQLite")){
stmt = Conn.createStatement(rs.TYPE_FORWARD_ONLY, rs.CONCUR_READ_ONLY);
}
else if (driver.equals("PostgreSQL")){
if (fetchSize!=null){
stmt = Conn.createStatement(rs.TYPE_FORWARD_ONLY, rs.CONCUR_READ_ONLY, rs.FETCH_FORWARD);
}
else{
stmt = Conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs.CONCUR_READ_ONLY);
}
}
//Default Connection
else{
try{
stmt = Conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs.CONCUR_READ_ONLY);
}
catch(SQLException e){
stmt = Conn.createStatement();
}
}
if (debugClose) openStatements.incrementAndGet();
if (fetchSize!=null) stmt.setFetchSize(fetchSize);
rs = stmt.executeQuery(sqlString);
if (debugClose) openRecordsets.incrementAndGet();
State = 1;
}
catch(SQLException e){
//System.out.println("ERROR Open RecordSet: " + e.toString());
synchronized(queries){
queries.remove(queryID);
}
throw e;
}
}
//Read-Write Connection
else{
/* Note that we don't actually use the rs and stmt objects when
inserting or updating records anymore. We can probably remove
all this code and simply use the ReadOnly code block above.
In read/write mode, it seems we only use the rs and stmt
objects to get field metadata via the init() method.
*/
try{
//SYBASE Connection
if (driver.equals("SYBASE")){
if (fetchSize!=null) Conn.setAutoCommit(false);
stmt = Conn.createStatement(rs.TYPE_FORWARD_ONLY,rs.CONCUR_UPDATABLE);
if (fetchSize!=null) stmt.setFetchSize(fetchSize);
rs = stmt.executeQuery(sqlString);
State = 1;
}
//SQLite Connection
else if (driver.equals("SQLite")){
if (fetchSize!=null) Conn.setAutoCommit(false);
stmt = Conn.createStatement(rs.TYPE_FORWARD_ONLY,rs.CONCUR_READ_ONLY); //xerial only seems to support this cursor
if (fetchSize!=null) stmt.setFetchSize(fetchSize);
rs = stmt.executeQuery(sqlString);
State = 1;
}
//DB2 Connection
else if (driver.equals("DB2")){
try{
if (fetchSize!=null) Conn.setAutoCommit(false);
stmt = Conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE);
if (fetchSize!=null) stmt.setFetchSize(fetchSize);
rs = stmt.executeQuery(sqlString);
State = 1;
}
catch(Exception e){
//System.out.println("createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE) Error:");
//System.out.println(e.toString());
rs = null;
}
if (rs==null){
try{
if (fetchSize!=null) Conn.setAutoCommit(false);
stmt = Conn.createStatement(rs.TYPE_FORWARD_ONLY,rs.CONCUR_UPDATABLE);
if (fetchSize!=null) stmt.setFetchSize(fetchSize);
rs = stmt.executeQuery(sqlString);
State = 1;
}
catch(Exception e){
//System.out.println("createStatement(rs.TYPE_FORWARD_ONLY,rs.CONCUR_UPDATABLE) Error:");
//System.out.println(e.toString());
}
}
}
//Default Connection
else{
if (fetchSize!=null) Conn.setAutoCommit(false);
stmt = Conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE);
if (fetchSize!=null) stmt.setFetchSize(fetchSize);
rs = stmt.executeQuery(sqlString);
/*
stmt.execute(sqlString, java.sql.Statement.RETURN_GENERATED_KEYS);
rs = stmt.getResultSet();
*/
State = 1;
}
if (stmt!=null && debugClose) openStatements.incrementAndGet();
if (rs!=null && debugClose) openRecordsets.incrementAndGet();
}
catch(SQLException e){
//System.out.println("ERROR Open RecordSet (RW): " + e.toString());
synchronized(queries){
queries.remove(queryID);
}
throw e;
}
}
endTime = System.currentTimeMillis();
queryResponseTime = endTime-startTime;
init();
return rs;
}
//**************************************************************************
//** open
//**************************************************************************
/** Used to initialize a Recordset using a standard Java ResultSet
*/
public void open(java.sql.ResultSet resultSet){
if (shuttingDown.get()) throw new IllegalStateException("JVM shutting down");
if (debugClose) openCalls.incrementAndGet();
startTime = System.currentTimeMillis();
queryResponseTime = ellapsedTime = metadataQueryTime = endTime = 0;
EOF = true;
rs = resultSet;
queryID = UUID.randomUUID().toString();
synchronized(queries){
queries.put(queryID, this);
}
init();
}
//**************************************************************************
//** init
//**************************************************************************
/** Used to initialize fields
*/
private void init(){
n = 0;
try{
//Create Fields
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
Field[] fields = new Field[cols];
for (int i=1; i<=cols; i++) {
fields[i-1] = new Field(i, rsmd);
}
this.record = new javaxt.sql.Record(fields);
rsmd = null;
x=-1;
if (rs!=null){
if (rs.next()){
EOF = false;
for (int i=1; i<=cols; i++) {
fields[i-1].setValue(new Value(rs.getObject(i)));
}
x+=1;
}
//Get Additional Metadata
//long mStart = java.util.Calendar.getInstance().getTimeInMillis();
//RecordCount = getRecordCount();
//updateFields();
//long mEnd = java.util.Calendar.getInstance().getTimeInMillis();
//MetadataQueryTime = mEnd-mStart;
metadataQueryTime = 0;
}
}
catch(SQLException e){
//e.printStackTrace();
//throw e;
}
}
//**************************************************************************
//** close
//**************************************************************************
/** Closes the Recordset freeing up database and jdbc resources.
*/
public void close(){
if (debugClose) closeCalls.incrementAndGet();
//Close recordset
try{
if (State==1) executeBatch();
if (!isReadOnly) commit();
if (rs!=null){
rs.close();
if (debugClose) openRecordsets.decrementAndGet();
}
if (stmt!=null){
//Some databases (e.g. PostgreSQL) will continue executing a long
//query even after closing the recordset. The only way to stop
//a long-running query is to cancel the statement. Note that
//cancelling a statement in SQLite calls sqlite3_interrupt()
//which causes issues when inserting, updating, or deleting
//records.
if (driver.equals("PostgreSQL")){
try{ stmt.cancel(); }
catch(Exception e){}
}
try{
stmt.close();
if (debugClose) openStatements.decrementAndGet();
}
catch(Exception e){
//e.printStackTrace();
}
}
}
catch(SQLException e){
e.printStackTrace();
SQLException ex = e.getNextException();
if (ex!=null) ex.printStackTrace();
}
//Remove recordset from the list of queries
synchronized(queries){
queries.remove(queryID);
}
//Reset autocommit
try{
connection.getConnection().setAutoCommit(autoCommit);
}
catch(Exception e){
//e.printStackTrace();
}
State = 0;
rs = null;
stmt = null;
driver = null;
sqlString = null;
keys.clear();
record = null;
endTime = System.currentTimeMillis();
ellapsedTime = endTime-startTime;
if (debugClose) javaxt.utils.Console.console.log(
openRecordsets + " openRecordsets, " +
openStatements + " openStatements, " +
(openCalls.get()-closeCalls.get()));
}
//**************************************************************************
//** getDatabase
//**************************************************************************
/** Returns connection information to the database
*/
public Database getDatabase(){
return this.connection.getDatabase();
}
//**************************************************************************
//** setFetchSize
//**************************************************************************
/** This method changes the block fetch size for server cursors. This may
* help avoid out of memory exceptions when retrieving a large number of
* records from the database. Set this method BEFORE opening the recordset.
*/
public void setFetchSize(int fetchSize){
if (fetchSize>0) this.fetchSize = fetchSize;
}
public Integer getFetchSize(){
return fetchSize;
}
//**************************************************************************
//** setMaxRecords
//**************************************************************************
/** Sets the maximum number of records to process
*/
public void setMaxRecords(int maxRecords){
if (maxRecords>0) this.maxRecords = maxRecords;
}
//**************************************************************************
//** getConnection
//**************************************************************************
/** Returns the database connection used to create/open the recordset.
*/
public Connection getConnection(){
return connection;
}
//**************************************************************************
//** Commit
//**************************************************************************
/** Used to explicitly commit an sql statement. May be useful for bulk
* update and update statements, depending on the underlying DBMS.
*/
public void commit(){
try{
//stmt.executeQuery("COMMIT");
connection.getConnection().commit();
}
catch(Exception e){
//System.out.println(e.toString());
}
}
private boolean InsertOnUpdate = false;
//**************************************************************************
//** AddNew
//**************************************************************************
/** Used to prepare the driver to insert new records to the database. Used
* in conjunction with the update method.
*/
public void addNew(){
if (State==1){
InsertOnUpdate = true;
record.update(null);
}
}
//**************************************************************************
//** Update
//**************************************************************************
/** Used to add or update a record in a table. Note that inserts can be
* batched using the setBatch() method to improve performance. When
* performing batch inserts, the update statements are queued and executed
* only after the batch size is reached.
*/
public void update() throws SQLException {
if (isReadOnly) throw new SQLException("Read only!");
if (State!=1) throw new SQLException("Recordset is closed!");
if (!isDirty()) return;
//Generate list of fields that require updates
ArrayList<Field> fields = new ArrayList<>();
for (Field field : record.fields){
if (field.getName()!=null && field.isDirty()) fields.add(field);
}
int numUpdates = fields.size();
//Get table name
Field f = record.getField(0);
String tableName = f.getTableName();
String schemaName = f.getSchema();
if (tableName==null){
updateFields(false);
tableName = f.getTableName();
schemaName = f.getSchema();
}
else{
if (schemaName==null){
updateFields(false);
schemaName = f.getSchema();
}
}
//if (tableName.contains(" ")) tableName = "[" + tableName + "]";
tableName = escape(tableName);
schemaName = escape(schemaName);
if (schemaName!=null) tableName = schemaName + "." + tableName;
//Construct a SQL insert/update statement
StringBuilder sql = new StringBuilder();
if (InsertOnUpdate){
sql.append("INSERT INTO " + tableName + " (");
for (int i=0; i<numUpdates; i++){
String colName = escape(fields.get(i).getName());
sql.append(colName);
if (numUpdates>1 && i<numUpdates-1){
sql.append(",");
}
}
sql.append(") VALUES (");
for (int i=0; i<numUpdates; i++){
if (i>0) sql.append(",");
sql.append(getQ(fields.get(i)));
}
sql.append(")");
}
else{
sql.append("UPDATE " + tableName + " SET ");
for (int i=0; i<numUpdates; i++){
String colName = escape(fields.get(i).getName());
sql.append(colName);
sql.append("=");
sql.append(getQ(fields.get(i)));
if (numUpdates>1 && i<numUpdates-1){
sql.append(", ");
}
}
//Find primary key for the table. This slows things down
//quite a bit but we need it for the "where" clause.
if (keys.isEmpty()){
try{
Table table = f.getT();
if (table==null){
updateFields(true);
table = f.getT();
}
Key[] arr = table.getPrimaryKeys();
if (arr!=null){
for (int i=0; i<arr.length; i++){
Key key = arr[i];
Field field = getField(key.getColumn());
if (field!=null) keys.add(field);
}
}
}
catch(Exception e){
//e.printStackTrace();
}
}
//Build the where clause
if (!keys.isEmpty()){
sql.append(" WHERE ");
for (int i=0; i<keys.size(); i++){
Object key = keys.get(i);
Field field;
if (key instanceof String){
field = getField((String) key);
keys.set(i, field);
}
else{
field = (Field) key;
}
fields.add(field);
if (i>0) sql.append(" AND ");
String colName = escape(field.getName());
sql.append(colName); sql.append("=?");
}
}
else{
//Since we don't have any keys, use the original where clause
String where = new Parser(this.sqlString).getWhereString();
if (where!=null){
sql.append(" WHERE "); sql.append(where);
}
//Find how many records will be affected by this update
int numRecords;
try (java.sql.ResultSet r2 = stmt.executeQuery(
"SELECT COUNT(*) FROM " + tableName + (where==null? "" : " WHERE " + where))){
try{
numRecords = r2.getInt(1);
}
catch(Exception e){
try{
r2.first(); //SQLServer needs this!
numRecords = r2.getInt(1);
}
catch(Exception ex){
numRecords = Integer.MAX_VALUE;
}
}
}
//Warn user that there might be a problem with the update
if (numRecords>1){
StringBuilder msg = new StringBuilder();
msg.append("WARNING: Updating " + tableName + " table without a unique key.\r\n");
msg.append("Multiple rows may be affected with this update.\r\n");
try{ int x = 1/0; } catch(Exception e){
java.io.ByteArrayOutputStream bas = new java.io.ByteArrayOutputStream();
java.io.PrintStream s = new java.io.PrintStream(bas, true);
e.printStackTrace(s);
s.close();
boolean append = false;
for (String line : bas.toString().split("\n")){
if (append){
msg.append("\t");
msg.append(line.trim());
msg.append("\r\n");
}
if (!append && line.contains(this.getClass().getCanonicalName())) append = true;
}
System.err.println(msg);
}
}
}
}
//Get prepared statement
java.sql.PreparedStatement stmt;
java.sql.Connection conn = connection.getConnection();
if (batchSize>1){
if (batchedStatements==null) batchedStatements = new java.util.HashMap<>();
stmt = batchedStatements.get(sql.toString());
if (stmt==null){
stmt = conn.prepareStatement(sql.toString());
batchedStatements.put(sql.toString(), stmt);
conn.setAutoCommit(false);
}
}
else{
try{
if (keys==null || keys.isEmpty()){
stmt = conn.prepareStatement(sql.toString(), java.sql.Statement.RETURN_GENERATED_KEYS);
}
else{
String[] columnNames = new String[keys.size()];
for (int i=0; i<columnNames.length; i++){
columnNames[i] = keys.get(i).toString();
}
stmt = conn.prepareStatement(sql.toString(), columnNames);
}
}
catch(Exception e){ //not all databases support auto generated keys
stmt = conn.prepareStatement(sql.toString());
}
}
//Set values using a prepared statement
update(stmt, fields);
//Update
if (batchSize==1){
try{
stmt.executeUpdate();
if (InsertOnUpdate){
try (java.sql.ResultSet generatedKeys = stmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
this.GeneratedKey = new Value(generatedKeys.getString(1));
}
}
catch(Exception e){
//not all databases support auto generated keys
}
}
stmt.close();
}
catch(SQLException e){
try{stmt.close();}catch(Exception ex){}
StringBuilder err = new StringBuilder();
err.append("Error executing update:\n");
err.append(sql.toString());
err.append("\n");
//err.append("\n Values:\n");
for (int i=0; i<fields.size(); i++) {
if (i>0) err.append("\n");
Field field = fields.get(i);
err.append(" - " + field.getName() + ": ");
String val = field.getValue().toString();
if (val!=null && val.length()>100) val = val.substring(0, 100) + "...";
err.append(val);
}
e.setNextException(new SQLException(err.toString()));
throw e;
}
if (InsertOnUpdate) InsertOnUpdate = false;
}
else{
stmt.addBatch();
numBatches++;
if (numBatches==batchSize){
executeBatch();
}
}
}
//**************************************************************************
//** update
//**************************************************************************
/** Used to set values in a PreparedStatement for inserting or updating
* records.
*/
protected static void update(java.sql.PreparedStatement stmt, ArrayList<Field> fields) throws SQLException {
try{ stmt.clearParameters(); }
catch(Exception e){}
int id = 1;
for (int i=0; i<fields.size(); i++) {
Field field = fields.get(i);
String FieldType = field.getClassName().toLowerCase();
if (FieldType.contains(".")) FieldType = FieldType.substring(FieldType.lastIndexOf(".")+1);
Value FieldValue = field.getValue();
//Special case for SQL Functions
if (FieldValue.toObject() instanceof Function){
Function function = (Function) FieldValue.toObject();
if (function.hasValues()){
for (Object obj : function.getValues()){
stmt.setObject(id, obj);
id++;
}
}
else{
//Do nothing!
}
continue; //Prevent the id from incrementing
}
if (FieldType.indexOf("string") >= 0)
stmt.setString(id, FieldValue.toString());
else if (FieldType.indexOf("int")>=0){
Integer val = FieldValue.toInteger();
if (val==null) stmt.setNull(id, java.sql.Types.INTEGER);
else stmt.setInt(id, val);
}
else if (FieldType.indexOf("short")>=0){
Short val = FieldValue.toShort();
if (val==null) stmt.setNull(id, java.sql.Types.SMALLINT);
else stmt.setShort(id, val);
}
else if (FieldType.indexOf("long")>=0){
Long val = FieldValue.toLong();
if (val==null) stmt.setNull(id, java.sql.Types.BIGINT);
else stmt.setLong(id, val);
}
else if (FieldType.indexOf("double")>=0){
Double val = FieldValue.toDouble();
if (val==null) stmt.setNull(id, java.sql.Types.DOUBLE);
else stmt.setDouble(id, val);
}
else if (FieldType.indexOf("float")>=0){
Float val = FieldValue.toFloat();
if (val==null) stmt.setNull(id, java.sql.Types.FLOAT);
else stmt.setFloat(id, val);
}
else if (FieldType.indexOf("bool")>=0){
Boolean val = FieldValue.toBoolean();
if (val==null) stmt.setNull(id, java.sql.Types.BIT);
else stmt.setBoolean(id, val);
}
else if (FieldType.indexOf("decimal")>=0)
stmt.setBigDecimal(id, FieldValue.toBigDecimal());
else if (FieldType.indexOf("timestamp")>=0)
stmt.setTimestamp(id, FieldValue.toTimeStamp());
else if (FieldType.indexOf("date")>=0){
if (FieldType.indexOf("datetime")>=0){
stmt.setTimestamp(id, FieldValue.toTimeStamp());
}
else{
javaxt.utils.Date d = FieldValue.toDate();
if (d==null) stmt.setNull(id, java.sql.Types.DATE);
else stmt.setDate(id, new java.sql.Date(d.getTime()));
}
}
else if (FieldType.indexOf("object")>=0)
stmt.setObject(id, FieldValue.toObject());
else if (FieldType.indexOf("map")>=0) //PostgreSQL HStore
stmt.setObject(id, FieldValue.toString(), java.sql.Types.OTHER);
else{
//System.out.println(i + " " + field.getName() + " " + FieldType);
stmt.setObject(id, FieldValue.toObject());
}
id++;
}
}
//**************************************************************************
//** escape
//**************************************************************************
private String escape(String colName){
if (colName==null) return null;
String[] keywords = Database.getReservedKeywords(connection);
colName = colName.trim();
if (colName.contains(" ") && !colName.startsWith("[")){
colName = "[" + colName + "]";
}
for (String keyWord : keywords){
if (colName.equalsIgnoreCase(keyWord)){
colName = "\"" + colName + "\"";
break;
}
}
return colName;
}
//**************************************************************************
//** getQ
//**************************************************************************
/** Returns an SQL fragment used to generate prepared statements. Typically,
* this method simply returns a "?". However, if the value for the field
* contains a function, or contains a spatial data type, additional