-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathRubyJdbcConnection.java
More file actions
3866 lines (3325 loc) · 160 KB
/
Copy pathRubyJdbcConnection.java
File metadata and controls
3866 lines (3325 loc) · 160 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
/***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2012-2013 Karol Bucek <self@kares.org>
* Copyright (c) 2006-2011 Nick Sieger <nick@nicksieger.com>
* Copyright (c) 2006-2007 Ola Bini <ola.bini@gmail.com>
* Copyright (c) 2008-2009 Thomas E Enebo <enebo@acm.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
***** END LICENSE BLOCK *****/
package arjdbc.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Array;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Date;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLRecoverableException;
import java.sql.SQLTransientException;
import java.sql.Savepoint;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import arjdbc.util.StringHelper;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBasicObject;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyException;
import org.jruby.RubyFixnum;
import org.jruby.RubyHash;
import org.jruby.RubyIO;
import org.jruby.RubyInteger;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.RubyTime;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.bigdecimal.RubyBigDecimal;
import org.jruby.ext.date.RubyDate;
import org.jruby.ext.date.RubyDateTime;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.callsite.CachingCallSite;
import org.jruby.runtime.callsite.FunctionalCachingCallSite;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.util.ByteList;
import org.jruby.util.SafePropertyAccessor;
import org.jruby.util.TypeConverter;
import arjdbc.util.DateTimeUtils;
import arjdbc.util.ObjectSupport;
import arjdbc.util.StringCache;
import static arjdbc.jdbc.DataSourceConnectionFactory.*;
import static arjdbc.util.StringHelper.*;
import static org.jruby.RubyTime.getLocalTimeZone;
/**
* Most of our ActiveRecord::ConnectionAdapters::JdbcConnection implementation.
*/
public class RubyJdbcConnection extends RubyObject {
private static final long serialVersionUID = 3803945791317576818L;
private static final String[] TABLE_TYPE = new String[] { "TABLE" };
private static final String[] TABLE_TYPES = new String[] { "TABLE", "VIEW", "SYNONYM" };
private ConnectionFactory connectionFactory;
private IRubyObject config;
private IRubyObject adapter; // the AbstractAdapter instance we belong to
private volatile boolean connected = true;
private RubyClass attributeClass;
private RubyClass timeZoneClass;
private boolean lazy = false; // final once set on initialize
private boolean jndi; // final once set on initialize
private boolean configureConnection = true; // final once initialized
private int fetchSize = 0; // 0 = JDBC default
protected RubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
attributeClass = runtime.getModule("ActiveModel").getClass("Attribute");
timeZoneClass = runtime.getModule("ActiveSupport").getClass("TimeWithZone");
}
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyJdbcConnection(runtime, klass);
}
};
public static RubyClass createJdbcConnectionClass(final Ruby runtime) {
final RubyClass JdbcConnection = getConnectionAdapters(runtime).
defineClassUnder("JdbcConnection", runtime.getObject(), ALLOCATOR);
JdbcConnection.defineAnnotatedMethods(RubyJdbcConnection.class);
return JdbcConnection;
}
public static RubyClass getJdbcConnection(final Ruby runtime) {
return (RubyClass) getConnectionAdapters(runtime).getConstantAt("JdbcConnection");
}
protected static RubyModule ActiveRecord(ThreadContext context) {
return context.runtime.getModule("ActiveRecord");
}
public static RubyClass getBase(final Ruby runtime) {
return (RubyClass) runtime.getModule("ActiveRecord").getConstantAt("Base");
}
/**
* @param runtime
* @return <code>ActiveRecord::Result</code>
*/
public static RubyClass getResult(final Ruby runtime) {
return (RubyClass) runtime.getModule("ActiveRecord").getConstantAt("Result");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters</code>
*/
public static RubyModule getConnectionAdapters(final Ruby runtime) {
return (RubyModule) runtime.getModule("ActiveRecord").getConstantAt("ConnectionAdapters");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters::IndexDefinition</code>
*/
protected static RubyClass getIndexDefinition(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("IndexDefinition");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters::ForeignKeyDefinition</code>
* @note only since AR 4.2
*/
protected static RubyClass getForeignKeyDefinition(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("ForeignKeyDefinition");
}
/**
* @param runtime
* @return <code>ActiveRecord::JDBCError</code>
*/
protected static RubyClass getJDBCError(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("JDBCError");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionNotEstablished</code>
*/
protected static RubyClass getConnectionNotEstablished(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("ConnectionNotEstablished");
}
/**
* @param runtime
* @return <code>ActiveRecord::NoDatabaseError</code>
*/
protected static RubyClass getNoDatabaseError(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("NoDatabaseError");
}
/**
* @param runtime
* @return <code>ActiveRecord::TransactionIsolationError</code>
*/
protected static RubyClass getTransactionIsolationError(final Ruby runtime) {
return (RubyClass) runtime.getModule("ActiveRecord").getConstant("TransactionIsolationError");
}
@JRubyMethod(name = "transaction_isolation", alias = "get_transaction_isolation")
public IRubyObject get_transaction_isolation(final ThreadContext context) {
return withConnection(context, connection -> {
final int level = connection.getTransactionIsolation();
final String isolationSymbol = formatTransactionIsolationLevel(level);
if ( isolationSymbol == null ) return context.nil;
return context.runtime.newSymbol(isolationSymbol);
});
}
@JRubyMethod(name = "transaction_isolation=", alias = "set_transaction_isolation")
public IRubyObject set_transaction_isolation(final ThreadContext context, final IRubyObject isolation) {
return withConnection(context, connection -> {
final int level;
if ( isolation.isNil() ) {
level = connection.getMetaData().getDefaultTransactionIsolation();
}
else {
level = mapTransactionIsolationLevel(isolation);
}
connection.setTransactionIsolation(level);
final String isolationSymbol = formatTransactionIsolationLevel(level);
if ( isolationSymbol == null ) return context.nil;
return context.runtime.newSymbol(isolationSymbol);
});
}
public static String formatTransactionIsolationLevel(final int level) {
if ( level == Connection.TRANSACTION_READ_UNCOMMITTED ) return "read_uncommitted"; // 1
if ( level == Connection.TRANSACTION_READ_COMMITTED ) return "read_committed"; // 2
if ( level == Connection.TRANSACTION_REPEATABLE_READ ) return "repeatable_read"; // 4
if ( level == Connection.TRANSACTION_SERIALIZABLE ) return "serializable"; // 8
if ( level == 0 ) return null;
throw new IllegalArgumentException("unexpected transaction isolation level: " + level);
}
/*
def transaction_isolation_levels
{
read_uncommitted: "READ UNCOMMITTED",
read_committed: "READ COMMITTED",
repeatable_read: "REPEATABLE READ",
serializable: "SERIALIZABLE"
}
end
*/
public static int mapTransactionIsolationLevel(final IRubyObject isolation) {
final Object isolationString;
if ( isolation instanceof RubySymbol ) {
isolationString = ((RubySymbol) isolation).asJavaString(); // RubySymbol (interned)
}
else {
isolationString = isolation.asString().toString().toLowerCase(Locale.ENGLISH).intern();
}
if ( isolationString == "read_uncommitted" ) return Connection.TRANSACTION_READ_UNCOMMITTED; // 1
if ( isolationString == "read_committed" ) return Connection.TRANSACTION_READ_COMMITTED; // 2
if ( isolationString == "repeatable_read" ) return Connection.TRANSACTION_REPEATABLE_READ; // 4
if ( isolationString == "serializable" ) return Connection.TRANSACTION_SERIALIZABLE; // 8
throw new IllegalArgumentException(
"unexpected isolation level: " + isolation + " (" + isolationString + ")"
);
}
@JRubyMethod(name = "supports_transaction_isolation?", optional = 1)
public IRubyObject supports_transaction_isolation_p(final ThreadContext context,
final IRubyObject[] args) throws SQLException {
final IRubyObject isolation = args.length > 0 ? args[0] : null;
return withConnection(context, (Callable<IRubyObject>) connection -> {
final DatabaseMetaData metaData = connection.getMetaData();
final boolean supported;
if ( isolation != null && ! isolation.isNil() ) {
final int level = mapTransactionIsolationLevel(isolation);
supported = metaData.supportsTransactionIsolationLevel(level);
}
else {
final int level = metaData.getDefaultTransactionIsolation();
supported = level > Connection.TRANSACTION_NONE; // > 0
}
return context.runtime.newBoolean(supported);
});
}
@JRubyMethod(name = {"begin", "transaction"}, required = 1) // optional isolation argument for AR-4.0
public IRubyObject begin(final ThreadContext context, final IRubyObject isolation) {
try { // handleException == false so we can handle setTXIsolation
return withConnection(context, false, connection -> beginTransaction(context, connection, isolation == context.nil ? null : isolation));
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = {"begin", "transaction"}) // optional isolation argument for AR-4.0
public IRubyObject begin(final ThreadContext context) {
try { // handleException == false so we can handle setTXIsolation
return withConnection(context, false, connection -> beginTransaction(context, connection, null));
} catch (SQLException e) {
return handleException(context, e);
}
}
protected IRubyObject beginTransaction(final ThreadContext context, final Connection connection,
final IRubyObject isolation) throws SQLException {
if ( isolation != null ) {
setTransactionIsolation(context, connection, isolation);
}
if ( connection.getAutoCommit() ) connection.setAutoCommit(false);
return context.nil;
}
protected void setTransactionIsolation(final ThreadContext context, final Connection connection,
final IRubyObject isolation) throws SQLException {
final int level = mapTransactionIsolationLevel(isolation);
try {
connection.setTransactionIsolation(level);
}
catch (SQLException e) {
RubyClass txError = ActiveRecord(context).getClass("TransactionIsolationError");
if ( txError != null ) throw wrapException(context, txError, e);
throw e; // let it roll - will be wrapped into a JDBCError (non 4.0)
}
}
@JRubyMethod(name = "commit")
public IRubyObject commit(final ThreadContext context) {
try {
final Connection connection = getConnectionInternal(true);
if ( ! connection.getAutoCommit() ) {
try {
connection.commit();
resetSavepoints(context, connection); // if any
return context.runtime.newBoolean(true);
}
finally {
connection.setAutoCommit(true);
}
}
return context.nil;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "rollback")
public IRubyObject rollback(final ThreadContext context) {
try {
final Connection connection = getConnectionInternal(true);
if ( ! connection.getAutoCommit() ) {
try {
connection.rollback();
resetSavepoints(context, connection); // if any
return context.tru;
} finally {
connection.setAutoCommit(true);
}
}
return context.nil;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "supports_savepoints?")
public IRubyObject supports_savepoints_p(final ThreadContext context) throws SQLException {
return withConnection(context, (Callable<IRubyObject>) connection -> {
final DatabaseMetaData metaData = connection.getMetaData();
return context.runtime.newBoolean( metaData.supportsSavepoints() );
});
}
@JRubyMethod(name = "create_savepoint") // not used
public IRubyObject create_savepoint(final ThreadContext context) {
return create_savepoint(context, context.nil);
}
@JRubyMethod(name = "create_savepoint", required = 1)
public IRubyObject create_savepoint(final ThreadContext context, IRubyObject name) {
try {
final Connection connection = getConnectionInternal(true);
connection.setAutoCommit(false);
final Savepoint savepoint ;
// NOTE: this will auto-start a DB transaction even invoked outside
// of a AR (Ruby) transaction (`transaction { ... create_savepoint }`)
// it would be nice if AR knew about this TX although that's kind of
// "really advanced" functionality - likely not to be implemented ...
if ( name != context.nil ) {
savepoint = connection.setSavepoint(name.toString());
}
else {
savepoint = connection.setSavepoint();
name = RubyString.newString( context.runtime, Integer.toString( savepoint.getSavepointId() ));
}
getSavepoints(context).put(name, savepoint);
return name;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "rollback_savepoint", required = 1)
public IRubyObject rollback_savepoint(final ThreadContext context, final IRubyObject name) {
if (name == context.nil) throw context.runtime.newArgumentError("nil savepoint name given");
try {
final Connection connection = getConnectionInternal(true);
Savepoint savepoint = getSavepoints(context).get(name);
if ( savepoint == null ) {
throw context.runtime.newRuntimeError("could not rollback savepoint: '" + name + "' (not set)");
}
connection.rollback(savepoint);
return context.nil;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "release_savepoint", required = 1)
public IRubyObject release_savepoint(final ThreadContext context, final IRubyObject name) {
if (name == context.nil) throw context.runtime.newArgumentError("nil savepoint name given");
try {
Object savepoint = getSavepoints(context).remove(name);
if (savepoint == null) throw newSavepointNotSetError(context, name, "release");
// NOTE: RubyHash.remove does not convert to Java as get does :
if (!(savepoint instanceof Savepoint)) {
savepoint = ((IRubyObject) savepoint).toJava(Savepoint.class);
}
final Connection connection = getConnectionInternal(true);
releaseSavepoint(connection, (Savepoint) savepoint);
return context.nil;
}
catch (SQLException e) {
return handleException(context, e);
}
}
// MSSQL doesn't support releasing savepoints so we make it possible to override the actual release action
protected void releaseSavepoint(final Connection connection, final Savepoint savepoint) throws SQLException {
connection.releaseSavepoint(savepoint);
}
protected static RuntimeException newSavepointNotSetError(final ThreadContext context, final IRubyObject name, final String op) {
RubyClass StatementInvalid = ActiveRecord(context).getClass("StatementInvalid");
return context.runtime.newRaiseException(StatementInvalid, "could not " + op + " savepoint: '" + name + "' (not set)");
}
// NOTE: this is iternal API - not to be used by user-code !
@JRubyMethod(name = "marked_savepoint_names")
public IRubyObject marked_savepoint_names(final ThreadContext context) {
@SuppressWarnings("unchecked")
final Map<IRubyObject, Savepoint> savepoints = getSavepoints(false);
if ( savepoints != null ) {
final RubyArray names = context.runtime.newArray(savepoints.size());
for ( Map.Entry<IRubyObject, ?> entry : savepoints.entrySet() ) {
names.append( entry.getKey() ); // keys are RubyString instances
}
return names;
}
return context.runtime.newEmptyArray();
}
protected Map<IRubyObject, Savepoint> getSavepoints(final ThreadContext context) {
return getSavepoints(true);
}
@SuppressWarnings("unchecked")
private Map<IRubyObject, Savepoint> getSavepoints(final boolean init) {
if ( hasInternalVariable("savepoints") ) {
return (Map<IRubyObject, Savepoint>) getInternalVariable("savepoints");
}
if ( init ) {
Map<IRubyObject, Savepoint> savepoints = new LinkedHashMap<>(4);
setInternalVariable("savepoints", savepoints);
return savepoints;
}
return null;
}
protected boolean resetSavepoints(final ThreadContext context, final Connection connection) throws SQLException {
if ( hasInternalVariable("savepoints") ) {
removeInternalVariable("savepoints");
return true;
}
return false;
}
@JRubyMethod(required = 2)
public final IRubyObject initialize(final ThreadContext context, final IRubyObject config, final IRubyObject adapter) {
doInitialize(context, config, adapter);
return this;
}
protected void doInitialize(final ThreadContext context, final IRubyObject config, final IRubyObject adapter) {
this.config = config;
this.adapter = adapter;
this.jndi = setupConnectionFactory(context);
this.lazy = jndi; // JNDIs are lazy by default otherwise eager
try {
if (adapter == null || adapter == context.nil) {
warn(context, "adapter not set, please pass adapter on JdbcConnection#initialize(config, adapter)");
}
if (!lazy) setConnection(newConnection());
}
catch (SQLException e) {
String message = e.getMessage();
if ( message == null ) message = e.getSQLState();
throw wrapException(context, e, message);
}
IRubyObject value = getConfigValue(context, "configure_connection");
if ( value == context.nil ) this.configureConnection = true;
else {
this.configureConnection = value != context.fals;
}
IRubyObject jdbcFetchSize = getConfigValue(context, "jdbc_fetch_size");
if (jdbcFetchSize != context.nil) {
this.fetchSize = RubyNumeric.fix2int(jdbcFetchSize);
}
}
@JRubyMethod(name = "adapter")
public IRubyObject adapter(final ThreadContext context) {
return adapter == null ? context.nil : adapter;
}
@JRubyMethod(name = "connection_factory")
public IRubyObject connection_factory() {
return convertJavaToRuby( getConnectionFactory() );
}
@JRubyMethod(name = "connection_factory=", required = 1)
public IRubyObject set_connection_factory(final IRubyObject factory) {
setConnectionFactory( (ConnectionFactory) factory.toJava(ConnectionFactory.class) );
return factory;
}
private void configureConnection() {
if ( ! configureConnection ) return; // return false;
if ( adapter != null && ! adapter.isNil() ) {
if ( adapter.respondsTo("configure_connection") ) {
final ThreadContext context = getRuntime().getCurrentContext();
adapter.callMethod(context, "configure_connection");
}
}
}
@JRubyMethod(name = "configure_connection")
public IRubyObject configure_connection(final ThreadContext context) {
if ( ! lazy || getConnectionImpl() != null ) configureConnection();
return context.nil;
}
@JRubyMethod(name = "jdbc_connection", alias = "connection")
public final IRubyObject connection(final ThreadContext context) {
return convertJavaToRuby( connectionImpl(context) );
}
@JRubyMethod(name = "jdbc_connection", alias = "connection", required = 1)
public final IRubyObject connection(final ThreadContext context, final IRubyObject unwrap) {
if ( unwrap == context.nil || unwrap == context.fals ) {
return connection(context);
}
Connection connection = connectionImpl(context);
try {
if ( connection.isWrapperFor(Connection.class) ) {
return convertJavaToRuby( connection.unwrap(Connection.class) );
}
}
catch (AbstractMethodError | SQLException e) {
debugStackTrace(context, e);
warn(context, "driver/pool connection does not support unwrapping: " + e);
}
return convertJavaToRuby( connection );
}
private Connection connectionImpl(final ThreadContext context) {
Connection connection = getConnection(false);
if ( connection == null ) {
synchronized (this) {
connection = getConnection(false);
if ( connection == null ) {
reconnect(context);
connection = getConnection(false);
}
}
}
return connection;
}
@JRubyMethod(name = "active?", alias = "valid?")
public RubyBoolean active_p(final ThreadContext context) {
if ( ! connected ) return context.fals;
if (jndi) {
// for JNDI the data-source / pool is supposed to
// manage connections for us thus no valid check!
boolean active = getConnectionFactory() != null;
return context.runtime.newBoolean( active );
}
final Connection connection = getConnection(false);
if ( connection == null ) return context.fals; // unlikely
return context.runtime.newBoolean( isConnectionValid(context, connection) );
}
@JRubyMethod(name = "really_valid?")
public RubyBoolean really_valid_p(final ThreadContext context) {
final Connection connection = getConnection(true);
if (connection == null) return context.fals;
return context.runtime.newBoolean(isConnectionValid(context, connection));
}
@JRubyMethod(name = "disconnect!")
public synchronized IRubyObject disconnect(final ThreadContext context) {
setConnection(null); connected = false;
return context.nil;
}
@JRubyMethod(name = "reconnect!")
public synchronized IRubyObject reconnect(final ThreadContext context) {
try {
connectImpl( ! lazy ); connected = true;
}
catch (SQLException e) {
debugStackTrace(context, e);
handleException(context, e);
}
return context.nil;
}
private void connectImpl(final boolean forceConnection) throws SQLException {
setConnection( forceConnection ? newConnection() : null );
if (forceConnection) {
if (getConnectionImpl() == null) throw new SQLException("Didn't get a connection. Wrong URL?");
configureConnection();
}
}
@JRubyMethod(name = "read_only?")
public IRubyObject is_read_only(final ThreadContext context) {
try {
final Connection connection = getConnectionInternal(false);
if (connection != null) {
return context.runtime.newBoolean(connection.isReadOnly());
}
} catch (SQLException e) {
return handleException(context, e);
}
return context.nil;
}
@JRubyMethod(name = "read_only=")
public IRubyObject set_read_only(final ThreadContext context, final IRubyObject flag) {
try {
final Connection connection = getConnectionInternal(true);
connection.setReadOnly( flag.isTrue() );
return context.runtime.newBoolean( connection.isReadOnly() );
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = { "open?" /* "conn?" */ })
public IRubyObject open_p(final ThreadContext context) {
try {
final Connection connection = getConnectionInternal(false);
if (connection == null) return context.fals;
// NOTE: isClosed method generally cannot be called to determine
// whether a connection to a database is valid or invalid ...
return context.runtime.newBoolean(!connection.isClosed());
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "closed?")
public IRubyObject closed_p(ThreadContext context) {
try {
final Connection connection = getConnectionInternal(false);
if (connection == null) return context.fals;
// NOTE: isClosed method generally cannot be called to determine
// whether a connection to a database is valid or invalid ...
return context.runtime.newBoolean(connection.isClosed());
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "close")
public IRubyObject close(final ThreadContext context) {
final Connection connection = getConnection(false);
if (connection == null) return context.fals;
try {
if (connection.isClosed()) return context.fals;
setConnection(null); // does connection.close();
} catch (Exception e) {
debugStackTrace(context, e);
return context.nil;
}
// ActiveRecord expects a closed connection to not try and re-open a connection
// whereas JNDI expects that.
if (!jndi) disconnect(context);
return context.tru;
}
@JRubyMethod(name = "database_name")
public IRubyObject database_name(final ThreadContext context) {
return withConnection(context, connection -> {
String name = connection.getCatalog();
if ( name == null ) {
name = connection.getMetaData().getUserName();
if ( name == null ) return context.nil;
}
return context.runtime.newString(name);
});
}
@JRubyMethod(name = "execute", required = 1)
public IRubyObject execute(final ThreadContext context, final IRubyObject sql) {
final String query = sqlString(sql);
return withConnection(context, connection -> {
Statement statement = null;
try {
statement = createStatement(context, connection);
// For DBs that do support multiple statements, lets return the last result set
// to be consistent with AR
boolean hasResultSet = doExecute(statement, query);
int updateCount = statement.getUpdateCount();
IRubyObject result = context.nil; // If no results, return nil
ResultSet resultSet;
while (hasResultSet || updateCount != -1) {
if (hasResultSet) {
resultSet = statement.getResultSet();
// Unfortunately the result set gets closed when getMoreResults()
// is called, so we have to process the result sets as we get them
// this shouldn't be an issue in most cases since we're only getting 1 result set anyways
//result = mapExecuteResult(context, connection, resultSet);
result = mapToRawResult(context, connection, resultSet, false);
resultSet.close();
} else {
result = context.runtime.newFixnum(updateCount);
}
// Check to see if there is another result set
hasResultSet = statement.getMoreResults();
updateCount = statement.getUpdateCount();
}
return result;
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
protected Statement createStatement(final ThreadContext context, final Connection connection)
throws SQLException {
final Statement statement = connection.createStatement();
IRubyObject escapeProcessing = getConfigValue(context, "statement_escape_processing");
// NOTE: disable (driver) escape processing by default, it's not really
// needed for AR statements ... if users need it they might configure :
if ( escapeProcessing == context.nil ) {
statement.setEscapeProcessing(false);
}
else {
statement.setEscapeProcessing(escapeProcessing.isTrue());
}
if (fetchSize != 0) statement.setFetchSize(fetchSize);
return statement;
}
/**
* Execute a query using the given statement.
* @param statement
* @param query
* @return true if the first result is a <code>ResultSet</code>;
* false if it is an update count or there are no results
* @throws SQLException
*/
protected boolean doExecute(final Statement statement, final String query) throws SQLException {
return statement.execute(query);
}
protected IRubyObject mapExecuteResult(final ThreadContext context,
final Connection connection, final ResultSet resultSet) throws SQLException{
return mapQueryResult(context, connection, resultSet);
}
private static String[] createStatementPk(IRubyObject pk) {
String[] statementPk;
if (pk instanceof RubyArray) {
RubyArray ary = (RubyArray) pk;
int size = ary.size();
statementPk = new String[size];
for (int i = 0; i < size; i++) {
statementPk[i] = sqlString(ary.eltInternal(i));
}
} else {
statementPk = new String[] { sqlString(pk) };
}
return statementPk;
}
/**
* Executes an INSERT SQL statement
* @param context
* @param sql
* @param pk Rails PK
* @return ActiveRecord::Result
* @throws SQLException
*/
@JRubyMethod(name = "execute_insert_pk", required = 2)
public IRubyObject execute_insert_pk(final ThreadContext context, final IRubyObject sql, final IRubyObject pk) {
return withConnection(context, connection -> {
Statement statement = null;
final String query = sqlString(sql);
try {
statement = createStatement(context, connection);
if (pk == context.nil || pk == context.fals || !supportsGeneratedKeys(connection)) {
statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
} else {
statement.executeUpdate(query, createStatementPk(pk));
}
return mapGeneratedKeys(context, connection, statement);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
@Deprecated
@JRubyMethod(name = "execute_insert", required = 1)
public IRubyObject execute_insert(final ThreadContext context, final IRubyObject sql) {
return execute_insert_pk(context, sql, context.nil);
}
/**
* Executes an INSERT SQL statement using a prepared statement
* @param context
* @param sql
* @param binds RubyArray of values to be bound to the query
* @param pk Rails PK
* @return ActiveRecord::Result
* @throws SQLException
*/
@JRubyMethod(name = "execute_insert_pk", required = 3)
public IRubyObject execute_insert_pk(final ThreadContext context, final IRubyObject sql, final IRubyObject binds,
final IRubyObject pk) {
return withConnection(context, connection -> {
PreparedStatement statement = null;
final String query = sqlString(sql);
try {
if (pk == context.nil || pk == context.fals || !supportsGeneratedKeys(connection)) {
statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
} else {
statement = connection.prepareStatement(query, createStatementPk(pk));
}
setStatementParameters(context, connection, statement, (RubyArray) binds);
statement.executeUpdate();
return mapGeneratedKeys(context, connection, statement);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
@Deprecated
@JRubyMethod(name = "execute_insert", required = 2)
public IRubyObject execute_insert(final ThreadContext context, final IRubyObject binds, final IRubyObject sql) {
return execute_insert_pk(context, sql, binds, context.nil);
}
/**
* Executes an UPDATE (DELETE) SQL statement
* @param context
* @param sql
* @return affected row count
* @throws SQLException
*/
@JRubyMethod(name = {"execute_update", "execute_delete"}, required = 1)
public IRubyObject execute_update(final ThreadContext context, final IRubyObject sql) {
return withConnection(context, (Callable<IRubyObject>) connection -> {
Statement statement = null;
final String query = sqlString(sql);
try {
statement = createStatement(context, connection);
final int rowCount = statement.executeUpdate(query);
return context.runtime.newFixnum(rowCount);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
/**
* Executes an UPDATE (DELETE) SQL using a prepared statement
* @param context
* @param sql
* @return affected row count
* @throws SQLException
*
* @see #execute_update(ThreadContext, IRubyObject)
*/
@JRubyMethod(name = {"execute_prepared_update", "execute_prepared_delete"}, required = 2)
public IRubyObject execute_prepared_update(final ThreadContext context, final IRubyObject sql, final IRubyObject binds) {
return withConnection(context, (Callable<IRubyObject>) connection -> {
PreparedStatement statement = null;
final String query = sqlString(sql);
try {
statement = connection.prepareStatement(query);
setStatementParameters(context, connection, statement, (RubyArray) binds);
final int rowCount = statement.executeUpdate();
return context.runtime.newFixnum(rowCount);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}