/
FBConnection.java
1302 lines (1108 loc) · 45.8 KB
/
FBConnection.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
/*
* Firebird Open Source JavaEE Connector - JDBC Driver
*
* Distributable under LGPL license.
* You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html
*
* This program 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
* LGPL License for more details.
*
* This file was created by members of the firebird development team.
* All individual contributions remain the Copyright (C) of those
* individuals. Contributors to this file are either listed here or
* can be obtained from a source control history command.
*
* All rights reserved.
*/
package org.firebirdsql.jdbc;
import org.firebirdsql.gds.DatabaseParameterBuffer;
import org.firebirdsql.gds.ISCConstants;
import org.firebirdsql.gds.JaybirdErrorCodes;
import org.firebirdsql.gds.TransactionParameterBuffer;
import org.firebirdsql.gds.impl.DatabaseParameterBufferExtension;
import org.firebirdsql.gds.impl.GDSHelper;
import org.firebirdsql.gds.ng.FbDatabase;
import org.firebirdsql.gds.ng.FbExceptionBuilder;
import org.firebirdsql.jca.FBConnectionRequestInfo;
import org.firebirdsql.jca.FBLocalTransaction;
import org.firebirdsql.jca.FBManagedConnection;
import org.firebirdsql.jca.FirebirdLocalTransaction;
import org.firebirdsql.jdbc.escape.FBEscapedParser;
import org.firebirdsql.logging.Logger;
import org.firebirdsql.logging.LoggerFactory;
import org.firebirdsql.util.SQLExceptionChainBuilder;
import javax.resource.ResourceException;
import java.lang.ref.WeakReference;
import java.sql.*;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import static org.firebirdsql.gds.impl.DatabaseParameterBufferExtension.GENERATED_KEYS_ENABLED;
import static org.firebirdsql.gds.impl.DatabaseParameterBufferExtension.IGNORE_PROCEDURE_TYPE;
import static org.firebirdsql.gds.impl.DatabaseParameterBufferExtension.USE_FIREBIRD_AUTOCOMMIT;
/**
* The class <code>FBConnection</code> is a handle to a
* {@link FBManagedConnection} and implements {@link Connection}.
*
* @author <a href="mailto:d_jencks@users.sourceforge.net">David Jencks</a>
* @author <a href="mailto:mrotteveel@users.sourceforge.net">Mark Rotteveel</a>
*/
@SuppressWarnings("RedundantThrows")
public class FBConnection implements FirebirdConnection, Synchronizable {
private static final Logger log = LoggerFactory.getLogger(FBConnection.class);
private static final String GET_CLIENT_INFO_SQL = "SELECT "
+ " rdb$get_context('USER_SESSION', ?) session_context "
+ " , rdb$get_context('USER_TRANSACTION', ?) tx_context "
+ "FROM rdb$database";
private static final String SET_CLIENT_INFO_SQL = "SELECT "
+ " rdb$set_context('USER_SESSION', ?, ?) session_context "
+ "FROM rdb$database";
private static final String PERMISSION_SET_NETWORK_TIMEOUT = "setNetworkTimeout";
protected FBManagedConnection mc;
private FBLocalTransaction localTransaction;
private FBDatabaseMetaData metaData;
protected final InternalTransactionCoordinator txCoordinator;
private SQLWarning firstWarning;
// This set contains all allocated but not closed statements
// It is used to close them before the connection is closed
protected final Set<Statement> activeStatements = Collections.synchronizedSet(new HashSet<Statement>());
private int resultSetHoldability = ResultSet.CLOSE_CURSORS_AT_COMMIT;
private StoredProcedureMetaData storedProcedureMetaData;
private GeneratedKeysSupport generatedKeysSupport;
/**
* Create a new AbstractConnection instance based on a
* {@link FBManagedConnection}.
*
* @param mc A FBManagedConnection around which this connection is based
*/
public FBConnection(FBManagedConnection mc) {
this.mc = mc;
txCoordinator = new InternalTransactionCoordinator(this);
FBConnectionRequestInfo cri = mc.getConnectionRequestInfo();
resultSetHoldability = cri.hasArgument(DatabaseParameterBufferExtension.RESULT_SET_HOLDABLE)
? ResultSet.HOLD_CURSORS_OVER_COMMIT
: ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
public FBObjectListener.StatementListener getStatementListener() {
return txCoordinator;
}
@Override
public int getHoldability() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
return resultSetHoldability;
}
}
@Override
public void setHoldability(int holdability) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
this.resultSetHoldability = holdability;
}
}
/**
* Check if this connection is valid. This method should be invoked before
* executing any action in this class.
*
* @throws SQLException if this connection has been closed and cannot be
* used anymore.
*/
protected void checkValidity() throws SQLException {
if (isClosed()) {
throw new FBSQLException("This connection is closed and cannot be used now.",
SQLStateConstants.SQL_STATE_CONNECTION_CLOSED);
}
}
/**
* This method should be invoked by each of the statements in the
* {@link Statement#close()} method. Here we remove statement from the
* <code>activeStatements</code> set, so we do not need to close it
* later.
*
* @param stmt statement that was closed.
*/
void notifyStatementClosed(FBStatement stmt) {
if (!activeStatements.remove(stmt)) {
if (stmt instanceof FBPreparedStatement && ((FBPreparedStatement) stmt).isInitialized()) {
// Close was likely triggered by finalizer of a prepared statement that failed on prepare in
// the constructor: Do not log warning
return;
}
log.warn("Specified statement was not created by this connection: " + stmt);
}
}
/**
* This method closes all active statements and cleans resources.
*
* @throws SQLException if at least one of the active statements failed
* to close gracefully.
*/
protected void freeStatements() throws SQLException {
// copy statements to avoid concurrent modification exception
List<Statement> statements = new ArrayList<>(activeStatements);
// iterate through the set, close statements and collect exceptions
SQLExceptionChainBuilder<SQLException> chain = new SQLExceptionChainBuilder<>();
for (Statement stmt : statements) {
try {
stmt.close();
} catch(SQLException ex) {
chain.append(ex);
}
}
// throw exception if there is any
if (chain.hasException()) throw chain.getException();
}
/**
* Set the {@link FBManagedConnection} around which this connection is
* based.
* @param mc The FBManagedConnection around which this connection is based
*/
public void setManagedConnection(FBManagedConnection mc) {
synchronized (getSynchronizationObject()) {
//close any prepared statements we may have executed.
if (this.mc != mc && metaData != null) {
try {
metaData.close();
} finally {
metaData = null;
}
}
this.mc = mc;
}
}
public FBManagedConnection getManagedConnection() {
synchronized (getSynchronizationObject()) {
return mc;
}
}
@Override
public FbDatabase getFbDatabase() throws SQLException {
return getGDSHelper().getCurrentDatabase();
}
/**
* Get database parameter buffer for this connection.
*
* @return instance of {@link DatabaseParameterBuffer}.
*/
public DatabaseParameterBuffer getDatabaseParameterBuffer() {
return mc != null ? mc.getConnectionRequestInfo().getDpb() : null;
}
@Deprecated
@Override
public void setTransactionParameters(int isolationLevel, int[] parameters) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
TransactionParameterBuffer tpbParams = createTransactionParameterBuffer();
for (int parameter : parameters) {
tpbParams.addArgument(parameter);
}
setTransactionParameters(isolationLevel, tpbParams);
}
}
@Override
public TransactionParameterBuffer getTransactionParameters(int isolationLevel) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
return mc.getTransactionParameters(isolationLevel);
}
}
@Override
public TransactionParameterBuffer createTransactionParameterBuffer() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
return getFbDatabase().createTransactionParameterBuffer();
}
}
@Override
public void setTransactionParameters(int isolationLevel, TransactionParameterBuffer tpb) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
if (mc.isManagedEnvironment()) {
throw new FBSQLException("Cannot set transaction parameters in managed environment.");
}
mc.setTransactionParameters(isolationLevel, tpb);
}
}
@Override
public void setTransactionParameters(TransactionParameterBuffer tpb) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
try {
if (getLocalTransaction().inTransaction()) {
throw new FBSQLException("Cannot set transaction parameters when transaction is already started.");
}
mc.setTransactionParameters(tpb);
} catch (ResourceException ex) {
throw new FBSQLException(ex);
}
}
}
@Override
public Statement createStatement() throws SQLException {
return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
}
@Override
public Blob createBlob() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
return new FBBlob(getGDSHelper(), txCoordinator);
}
}
@Override
public Clob createClob() throws SQLException {
FBBlob blob = (FBBlob)createBlob();
return new FBClob(blob);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
checkValidity();
throw new FBDriverNotCapableException("Type STRUCT not supported");
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
checkValidity();
throw new FBDriverNotCapableException("Type ARRAY not yet supported");
}
@Override
public String nativeSQL(String sql) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
return FBEscapedParser.toNativeSql(sql);
}
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
if (getAutoCommit() == autoCommit) {
return;
}
// FIXME : Behavior in switch might be wrong, see also setSavePoint
txCoordinator.switchTransactionCoordinator(autoCommit);
}
}
protected void setTransactionCoordinator(boolean managedConnection, boolean autoCommit) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
txCoordinator.setTransactionCoordinator(managedConnection, autoCommit);
}
}
public void setManagedEnvironment(boolean managedConnection) throws SQLException {
synchronized (getSynchronizationObject()) {
setTransactionCoordinator(managedConnection, true);
}
}
@Override
public boolean getAutoCommit() throws SQLException {
synchronized (getSynchronizationObject()) {
if (isClosed()) {
throw new FBSQLException("You cannot getAutoCommit on an unassociated closed connection.");
}
return txCoordinator.getAutoCommit();
}
}
@Override
public void commit() throws SQLException {
synchronized (getSynchronizationObject()) {
if (isClosed()) {
throw new FBSQLException(
"You cannot commit a closed connection.",
SQLStateConstants.SQL_STATE_CONNECTION_CLOSED);
}
if (mc.inDistributedTransaction()) {
throw new FBSQLException("Connection enlisted in distributed transaction", SQLStateConstants.SQL_STATE_INVALID_TX_STATE);
}
txCoordinator.commit();
invalidateTransactionLifetimeObjects();
}
}
@Override
public void rollback() throws SQLException {
synchronized (getSynchronizationObject()) {
if (isClosed()) {
throw new FBSQLException(
"You cannot rollback closed connection.",
SQLStateConstants.SQL_STATE_CONNECTION_CLOSED);
}
if (mc.inDistributedTransaction()) {
throw new FBSQLException("Connection enlisted in distributed transaction", SQLStateConstants.SQL_STATE_INVALID_TX_STATE);
}
txCoordinator.rollback();
invalidateTransactionLifetimeObjects();
}
}
/**
* Invalidate everything that should only last for the lifetime of the current transaction.
*/
protected void invalidateTransactionLifetimeObjects(){
invalidateSavepoints();
storedProcedureMetaData = null;
}
/**
* {@inheritDoc}
* <p>
* Implementation note: Certain fatal errors also result in a closed Connection.
* </p>
*/
@Override
public void close() throws SQLException {
SQLExceptionChainBuilder<SQLException> chainBuilder = new SQLExceptionChainBuilder<>();
synchronized (getSynchronizationObject()) {
if (log.isTraceEnabled()) {
log.trace("Connection closed requested at", new RuntimeException("Connection close logging"));
}
try {
freeStatements();
if (metaData != null) metaData.close();
} catch (SQLException e) {
chainBuilder.append(e);
} finally {
metaData = null;
if (mc != null) {
// leave managed transactions alone, they are normally
// committed after the Connection handle is closed.
if (!mc.inDistributedTransaction()) {
try {
txCoordinator.handleConnectionClose();
} catch (SQLException e) {
chainBuilder.append(e);
} finally {
try {
setAutoCommit(true);
} catch (SQLException e) {
if (!SQLStateConstants.SQL_STATE_CONNECTION_CLOSED.equals(e.getSQLState())) {
chainBuilder.append(e);
}
}
}
}
mc.close(this);
mc = null;
}
}
}
if (chainBuilder.hasException()) {
throw chainBuilder.getException();
}
}
@Override
public boolean isClosed() {
return mc == null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
if (timeout < 0) {
throw new SQLException("Timeout should be >= 0", SQLStateConstants.SQL_STATE_INVALID_ARG_VALUE);
}
synchronized (getSynchronizationObject()) {
if (isClosed()) {
return false;
}
// TODO Check if we can set the connection timeout temporarily for this call
if (timeout != 0) {
addWarning(new SQLWarning(
String.format("Connection.isValid does not support non-zero timeouts, timeout value %d has been ignored",
timeout)));
}
try {
getFbDatabase().getDatabaseInfo(
new byte[] { ISCConstants.isc_info_ods_version, ISCConstants.isc_info_end }, 10);
return true;
} catch (SQLException ex) {
return false;
}
}
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
if (metaData == null)
metaData = new FBDatabaseMetaData(this);
return metaData;
}
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
try {
if (getLocalTransaction().inTransaction() && !mc.isManagedEnvironment())
throw new FBSQLException("Calling setReadOnly(boolean) method " +
"is not allowed when transaction is already started.");
mc.setReadOnly(readOnly);
} catch (ResourceException ex) {
throw new FBSQLException(ex);
}
}
}
@Override
public boolean isReadOnly() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
return mc.isReadOnly();
}
}
/**
* {@inheritDoc}
* <p>
* Implementation ignores calls to this method as catalogs are not supported.
* </p>
*/
@Override
public void setCatalog(String catalog) throws SQLException {
checkValidity();
}
/**
* {@inheritDoc}
*
* @return Always {@code null} as catalogs are not supported.
*/
@Override
public String getCatalog() throws SQLException {
checkValidity();
return null;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
try {
if (!getAutoCommit() && !mc.isManagedEnvironment())
txCoordinator.commit();
mc.setTransactionIsolation(level);
} catch (ResourceException re) {
throw new FBSQLException(re);
}
}
}
@Override
public int getTransactionIsolation() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
try {
return mc.getTransactionIsolation();
} catch (ResourceException e) {
throw new FBSQLException(e);
}
}
}
@Override
public SQLWarning getWarnings() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
return firstWarning;
}
}
@Override
public void clearWarnings() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
firstWarning = null;
}
}
@Override
public Statement createStatement(int resultSetType,
int resultSetConcurrency) throws SQLException {
return createStatement(resultSetType, resultSetConcurrency, this.resultSetHoldability);
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
if (resultSetHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT &&
resultSetType == ResultSet.TYPE_FORWARD_ONLY) {
addWarning(FbExceptionBuilder
.forWarning(JaybirdErrorCodes.jb_resultSetTypeUpgradeReasonHoldability)
.toFlatSQLException(SQLWarning.class));
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
}
if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) {
addWarning(FbExceptionBuilder
.forWarning(JaybirdErrorCodes.jb_resultSetTypeDowngradeReasonScrollSensitive)
.toFlatSQLException(SQLWarning.class));
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
}
checkHoldability(resultSetType, resultSetHoldability);
Statement stmt = new FBStatement(getGDSHelper(), resultSetType, resultSetConcurrency, resultSetHoldability,
txCoordinator);
activeStatements.add(stmt);
return stmt;
}
}
/**
* Check whether result set type and holdability are compatible.
*
* @param resultSetType desired result set type.
* @param resultSetHoldability desired result set holdability.
*
* @throws SQLException if specified result set type and holdability are
* not compatibe.
*/
private void checkHoldability(int resultSetType, int resultSetHoldability) throws SQLException {
boolean holdable =
resultSetHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT;
boolean notScrollable = resultSetType != ResultSet.TYPE_SCROLL_INSENSITIVE;
if (holdable && notScrollable)
throw new FBDriverNotCapableException(
"Holdable cursors are supported only " +
"for scrollable insensitive result sets.");
}
@Override
public PreparedStatement prepareStatement(String sql,
int resultSetType, int resultSetConcurrency) throws SQLException {
return prepareStatement(sql, resultSetType, resultSetConcurrency, this.resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql,
int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
return prepareStatement(sql, resultSetType, resultSetConcurrency,
resultSetHoldability, false, false);
}
// TODO Why unused? Remove?
protected PreparedStatement prepareMetaDataStatement(String sql,
int resultSetType, int resultSetConcurrency) throws SQLException {
return prepareStatement(sql, resultSetType, resultSetConcurrency,
resultSetHoldability, true, false);
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
GeneratedKeysSupport.Query query = getGeneratedKeysSupport()
.buildQuery(sql, autoGeneratedKeys);
return prepareStatement(query);
}
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
GeneratedKeysSupport.Query query = getGeneratedKeysSupport()
.buildQuery(sql, columnIndexes);
return prepareStatement(query);
}
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
GeneratedKeysSupport.Query query = getGeneratedKeysSupport()
.buildQuery(sql, columnNames);
return prepareStatement(query);
}
}
/**
* Prepares a statement for generated keys.
*
* @param query AbstractGeneratedKeysQuery instance
* @return PreparedStatement object
* @throws SQLException if a database access error occurs
* or this method is called on a closed connection
*/
private PreparedStatement prepareStatement(GeneratedKeysSupport.Query query) throws SQLException {
if (query.generatesKeys()) {
return prepareStatement(query.getQueryString(),
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT,
false, true);
} else {
return prepareStatement(query.getQueryString());
}
}
protected PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability, boolean metaData, boolean generatedKeys) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
if (resultSetHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT
&& resultSetType == ResultSet.TYPE_FORWARD_ONLY) {
addWarning(FbExceptionBuilder
.forWarning(JaybirdErrorCodes.jb_resultSetTypeUpgradeReasonHoldability)
.toFlatSQLException(SQLWarning.class));
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
} else if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) {
addWarning(FbExceptionBuilder
.forWarning(JaybirdErrorCodes.jb_resultSetTypeDowngradeReasonScrollSensitive)
.toFlatSQLException(SQLWarning.class));
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
}
checkHoldability(resultSetType, resultSetHoldability);
FBObjectListener.StatementListener coordinator = txCoordinator;
if (metaData)
coordinator = new InternalTransactionCoordinator.MetaDataTransactionCoordinator(txCoordinator);
FBObjectListener.BlobListener blobCoordinator = metaData ? null : txCoordinator;
PreparedStatement stmt = new FBPreparedStatement(getGDSHelper(), sql, resultSetType, resultSetConcurrency, resultSetHoldability,
coordinator, blobCoordinator, metaData, false, generatedKeys);
activeStatements.add(stmt);
return stmt;
}
}
@Override
public CallableStatement prepareCall(String sql,
int resultSetType, int resultSetConcurrency) throws SQLException {
return prepareCall(sql, resultSetType, resultSetConcurrency, this.resultSetHoldability);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
if (resultSetHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT
&& resultSetType == ResultSet.TYPE_FORWARD_ONLY) {
addWarning(FbExceptionBuilder
.forWarning(JaybirdErrorCodes.jb_resultSetTypeUpgradeReasonHoldability)
.toFlatSQLException(SQLWarning.class));
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
} else if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) {
addWarning(FbExceptionBuilder
.forWarning(JaybirdErrorCodes.jb_resultSetTypeDowngradeReasonScrollSensitive)
.toFlatSQLException(SQLWarning.class));
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
}
if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) {
addWarning(FbExceptionBuilder
.forWarning(JaybirdErrorCodes.jb_concurrencyResetReadOnlyReasonStoredProcedure)
.toSQLException(SQLWarning.class));
resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
}
checkHoldability(resultSetType, resultSetHoldability);
if (storedProcedureMetaData == null) {
storedProcedureMetaData = StoredProcedureMetaDataFactory.getInstance(this);
}
FBCallableStatement stmt = new FBCallableStatement(getGDSHelper(), sql, resultSetType, resultSetConcurrency, resultSetHoldability,
storedProcedureMetaData, txCoordinator, txCoordinator);
activeStatements.add(stmt);
return stmt;
}
}
@Override
public Map<String,Class<?>> getTypeMap() throws SQLException {
return new HashMap<>();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
throw new FBDriverNotCapableException();
}
private Set<String> clientInfoPropNames = new HashSet<>();
private static final AtomicIntegerFieldUpdater<FBConnection> SAVEPOINT_COUNTER_UPDATE =
AtomicIntegerFieldUpdater.newUpdater(FBConnection.class, "savepointCounter");
private volatile int savepointCounter;
private final List<FBSavepoint> savepoints = new ArrayList<>();
private int getNextSavepointCounter() {
return SAVEPOINT_COUNTER_UPDATE.getAndIncrement(this);
}
@Override
public Savepoint setSavepoint() throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
FBSavepoint savepoint = new FBSavepoint(getNextSavepointCounter());
setSavepoint(savepoint);
return savepoint;
}
}
/**
* Set the savepoint on the server.
*
* @param savepoint savepoint to set.
*
* @throws SQLException if something went wrong.
*/
private void setSavepoint(FBSavepoint savepoint) throws SQLException {
if (getAutoCommit()) {
throw new SQLException("Connection.setSavepoint() method cannot be used in auto-commit mode.",
SQLStateConstants.SQL_STATE_INVALID_TX_STATE);
}
if (mc.inDistributedTransaction()) {
throw new SQLException("Connection enlisted in distributed transaction",
SQLStateConstants.SQL_STATE_INVALID_TX_STATE);
}
txCoordinator.ensureTransaction();
StringBuilder setSavepoint = new StringBuilder("SAVEPOINT ");
getQuoteStrategy().appendQuoted(savepoint.getServerSavepointId(), setSavepoint);
getGDSHelper().executeImmediate(setSavepoint.toString());
savepoints.add(savepoint);
}
/**
* Creates a named savepoint.
* <p>
* Savepoint names need to be valid Firebird identifiers, and the maximum length is restricted to the maximum
* identifier length (see {@link DatabaseMetaData#getMaxColumnNameLength()}. The implementation will take care of
* quoting the savepoint name appropriately for the connection dialect. The {@code name} should be passed unquoted.
* </p>
* <p>
* With connection dialect 1, the name is restricted to the rules for unquoted identifier names, that is, its
* characters are restricted to {@code A-Za-z0-9$_} and handled case insensitive.
* </p>
* <p>
* For dialect 2 and 3, the name is restricted to the rules for Firebird quoted identifiers (essentially any
* printable character and space is valid), and the name is handled case sensitive.
* </p>
*
* @param name
* Savepoint name
* @return Savepoint object
* @throws SQLException
* if a database access error occurs, this method is called while participating in a distributed
* transaction, this method is called on a closed connection or this {@code Connection} object is currently
* in auto-commit mode
*/
@Override
public Savepoint setSavepoint(String name) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
FBSavepoint savepoint = new FBSavepoint(name);
setSavepoint(savepoint);
return savepoint;
}
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
if (getAutoCommit()) {
throw new SQLException("Connection.rollback(Savepoint) method cannot be used in auto-commit mode.",
SQLStateConstants.SQL_STATE_INVALID_TX_STATE);
}
// TODO The error message and actual condition do not match
if (!(savepoint instanceof FBSavepoint)) {
throw new SQLException("Specified savepoint was not obtained from this connection.");
}
if (mc.inDistributedTransaction()) {
throw new SQLException("Connection enlisted in distributed transaction",
SQLStateConstants.SQL_STATE_INVALID_TX_STATE);
}
FBSavepoint fbSavepoint = (FBSavepoint) savepoint;
if (!fbSavepoint.isValid()) {
throw new SQLException("Savepoint is no longer valid.");
}
StringBuilder rollbackSavepoint = new StringBuilder("ROLLBACK TO ");
getQuoteStrategy().appendQuoted(fbSavepoint.getServerSavepointId(), rollbackSavepoint);
getGDSHelper().executeImmediate(rollbackSavepoint.toString());
}
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
synchronized (getSynchronizationObject()) {
checkValidity();
if (getAutoCommit()) {
throw new SQLException("Connection.releaseSavepoint() method cannot be used in auto-commit mode.",
SQLStateConstants.SQL_STATE_INVALID_TX_STATE);
}
// TODO The error message and actual condition do not match
if (!(savepoint instanceof FBSavepoint)) {
throw new SQLException("Specified savepoint was not obtained from this connection.");
}
FBSavepoint fbSavepoint = (FBSavepoint) savepoint;
if (!fbSavepoint.isValid()) {
throw new SQLException("Savepoint is no longer valid.");
}
StringBuilder rollbackSavepoint = new StringBuilder("RELEASE SAVEPOINT ");
getQuoteStrategy().appendQuoted(fbSavepoint.getServerSavepointId(), rollbackSavepoint).append(" ONLY");
getGDSHelper().executeImmediate(rollbackSavepoint.toString());
fbSavepoint.invalidate();
savepoints.remove(fbSavepoint);
}
}
/**
* Invalidate all savepoints.
*/
protected void invalidateSavepoints() {
synchronized (getSynchronizationObject()) {
for (FBSavepoint savepoint : savepoints) {
savepoint.invalidate();
}
savepoints.clear();
}
}
//-------------------------------------------
//Borrowed from javax.resource.cci.Connection
/**
* Returns a FBLocalTransaction instance that enables a component to
* demarcate resource manager local transactions on this connection.
*/
public FirebirdLocalTransaction getLocalTransaction() {
synchronized (getSynchronizationObject()) {
if (localTransaction == null)
localTransaction = new FBLocalTransaction(mc, this);
return localTransaction;
}
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface != null && iface.isAssignableFrom(FBConnection.class);
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
if (!isWrapperFor(iface))
throw new SQLException("Unable to unwrap to class " + iface.getName());
return iface.cast(this);
}
/**
* {@inheritDoc}