saturnflyer-activerecord-jdbc-adapter 0.9.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (183) hide show
  1. data/.gitignore +16 -0
  2. data/History.txt +225 -0
  3. data/LICENSE.txt +21 -0
  4. data/README.txt +161 -0
  5. data/Rakefile +28 -0
  6. data/VERSION +1 -0
  7. data/activerecord-jdbc-adapter.gemspec +277 -0
  8. data/adapters/derby/LICENSE.txt +21 -0
  9. data/adapters/derby/README.txt +5 -0
  10. data/adapters/derby/Rakefile +31 -0
  11. data/adapters/derby/lib/active_record/connection_adapters/jdbcderby_adapter.rb +30 -0
  12. data/adapters/h2/History.txt +0 -0
  13. data/adapters/h2/LICENSE.txt +21 -0
  14. data/adapters/h2/README.txt +5 -0
  15. data/adapters/h2/Rakefile +31 -0
  16. data/adapters/h2/lib/active_record/connection_adapters/jdbch2_adapter.rb +30 -0
  17. data/adapters/hsqldb/History.txt +0 -0
  18. data/adapters/hsqldb/LICENSE.txt +21 -0
  19. data/adapters/hsqldb/README.txt +5 -0
  20. data/adapters/hsqldb/Rakefile +31 -0
  21. data/adapters/hsqldb/lib/active_record/connection_adapters/jdbchsqldb_adapter.rb +30 -0
  22. data/adapters/mysql/History.txt +0 -0
  23. data/adapters/mysql/LICENSE.txt +21 -0
  24. data/adapters/mysql/README.txt +5 -0
  25. data/adapters/mysql/Rakefile +31 -0
  26. data/adapters/mysql/lib/active_record/connection_adapters/jdbcmysql_adapter.rb +30 -0
  27. data/adapters/postgresql/History.txt +0 -0
  28. data/adapters/postgresql/LICENSE.txt +21 -0
  29. data/adapters/postgresql/README.txt +5 -0
  30. data/adapters/postgresql/Rakefile +31 -0
  31. data/adapters/postgresql/lib/active_record/connection_adapters/jdbcpostgresql_adapter.rb +30 -0
  32. data/adapters/sqlite3/LICENSE.txt +21 -0
  33. data/adapters/sqlite3/README.txt +5 -0
  34. data/adapters/sqlite3/Rakefile +31 -0
  35. data/adapters/sqlite3/lib/active_record/connection_adapters/jdbcsqlite3_adapter.rb +30 -0
  36. data/bench/bench_attributes.rb +13 -0
  37. data/bench/bench_attributes_new.rb +14 -0
  38. data/bench/bench_create.rb +12 -0
  39. data/bench/bench_find_all.rb +12 -0
  40. data/bench/bench_find_all_mt.rb +25 -0
  41. data/bench/bench_model.rb +85 -0
  42. data/bench/bench_new.rb +12 -0
  43. data/bench/bench_new_valid.rb +12 -0
  44. data/bench/bench_valid.rb +13 -0
  45. data/drivers/derby/LICENSE.txt +1 -0
  46. data/drivers/derby/README.txt +6 -0
  47. data/drivers/derby/Rakefile +26 -0
  48. data/drivers/derby/lib/derby-10.5.3.0.jar +0 -0
  49. data/drivers/derby/lib/jdbc/derby.rb +11 -0
  50. data/drivers/h2/History.txt +0 -0
  51. data/drivers/h2/LICENSE.txt +2 -0
  52. data/drivers/h2/README.txt +6 -0
  53. data/drivers/h2/Rakefile +26 -0
  54. data/drivers/h2/lib/h2-1.1.107.jar +0 -0
  55. data/drivers/h2/lib/jdbc/h2.rb +10 -0
  56. data/drivers/hsqldb/History.txt +0 -0
  57. data/drivers/hsqldb/LICENSE.txt +2 -0
  58. data/drivers/hsqldb/README.txt +6 -0
  59. data/drivers/hsqldb/Rakefile +26 -0
  60. data/drivers/hsqldb/lib/hsqldb-1.8.0.7.jar +0 -0
  61. data/drivers/hsqldb/lib/jdbc/hsqldb.rb +10 -0
  62. data/drivers/mysql/History.txt +0 -0
  63. data/drivers/mysql/LICENSE.txt +1 -0
  64. data/drivers/mysql/README.txt +6 -0
  65. data/drivers/mysql/Rakefile +26 -0
  66. data/drivers/mysql/lib/jdbc/mysql.rb +10 -0
  67. data/drivers/mysql/lib/mysql-connector-java-5.0.4-bin.jar +0 -0
  68. data/drivers/postgres/History.txt +7 -0
  69. data/drivers/postgres/LICENSE.txt +12 -0
  70. data/drivers/postgres/README.txt +5 -0
  71. data/drivers/postgres/Rakefile +27 -0
  72. data/drivers/postgres/lib/jdbc/postgres.rb +25 -0
  73. data/drivers/postgres/lib/postgresql-8.3-604.jdbc3.jar +0 -0
  74. data/drivers/postgres/lib/postgresql-8.3-604.jdbc4.jar +0 -0
  75. data/drivers/sqlite3/LICENSE.txt +13 -0
  76. data/drivers/sqlite3/README.txt +6 -0
  77. data/drivers/sqlite3/Rakefile +26 -0
  78. data/drivers/sqlite3/lib/jdbc/sqlite3.rb +10 -0
  79. data/drivers/sqlite3/lib/sqlitejdbc-3.6.3.054.jar +0 -0
  80. data/lib/active_record/connection_adapters/cachedb_adapter.rb +1 -0
  81. data/lib/active_record/connection_adapters/derby_adapter.rb +13 -0
  82. data/lib/active_record/connection_adapters/h2_adapter.rb +13 -0
  83. data/lib/active_record/connection_adapters/hsqldb_adapter.rb +13 -0
  84. data/lib/active_record/connection_adapters/informix_adapter.rb +1 -0
  85. data/lib/active_record/connection_adapters/jdbc_adapter.rb +637 -0
  86. data/lib/active_record/connection_adapters/jdbc_adapter_spec.rb +14 -0
  87. data/lib/active_record/connection_adapters/jndi_adapter.rb +1 -0
  88. data/lib/active_record/connection_adapters/mysql_adapter.rb +13 -0
  89. data/lib/active_record/connection_adapters/oracle_adapter.rb +1 -0
  90. data/lib/active_record/connection_adapters/postgresql_adapter.rb +13 -0
  91. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +13 -0
  92. data/lib/jdbc_adapter.rb +27 -0
  93. data/lib/jdbc_adapter/jdbc.rake +104 -0
  94. data/lib/jdbc_adapter/jdbc_cachedb.rb +33 -0
  95. data/lib/jdbc_adapter/jdbc_db2.rb +191 -0
  96. data/lib/jdbc_adapter/jdbc_derby.rb +421 -0
  97. data/lib/jdbc_adapter/jdbc_firebird.rb +109 -0
  98. data/lib/jdbc_adapter/jdbc_hsqldb.rb +210 -0
  99. data/lib/jdbc_adapter/jdbc_informix.rb +147 -0
  100. data/lib/jdbc_adapter/jdbc_mimer.rb +141 -0
  101. data/lib/jdbc_adapter/jdbc_mssql.rb +333 -0
  102. data/lib/jdbc_adapter/jdbc_mysql.rb +233 -0
  103. data/lib/jdbc_adapter/jdbc_oracle.rb +374 -0
  104. data/lib/jdbc_adapter/jdbc_postgre.rb +483 -0
  105. data/lib/jdbc_adapter/jdbc_sqlite3.rb +360 -0
  106. data/lib/jdbc_adapter/jdbc_sybase.rb +50 -0
  107. data/lib/jdbc_adapter/missing_functionality_helper.rb +85 -0
  108. data/lib/jdbc_adapter/rake_tasks.rb +10 -0
  109. data/lib/jdbc_adapter/tsql_helper.rb +60 -0
  110. data/lib/jdbc_adapter/version.rb +5 -0
  111. data/pom.xml +57 -0
  112. data/rakelib/compile.rake +23 -0
  113. data/rakelib/package.rake +73 -0
  114. data/rakelib/rails.rake +41 -0
  115. data/src/java/jdbc_adapter/JdbcAdapterInternalService.java +53 -0
  116. data/src/java/jdbc_adapter/JdbcConnectionFactory.java +36 -0
  117. data/src/java/jdbc_adapter/JdbcDerbySpec.java +293 -0
  118. data/src/java/jdbc_adapter/JdbcMySQLSpec.java +133 -0
  119. data/src/java/jdbc_adapter/MssqlRubyJdbcConnection.java +71 -0
  120. data/src/java/jdbc_adapter/PostgresRubyJdbcConnection.java +55 -0
  121. data/src/java/jdbc_adapter/RubyJdbcConnection.java +1163 -0
  122. data/src/java/jdbc_adapter/SQLBlock.java +27 -0
  123. data/src/java/jdbc_adapter/Sqlite3RubyJdbcConnection.java +41 -0
  124. data/test/activerecord/connection_adapters/type_conversion_test.rb +31 -0
  125. data/test/activerecord/connections/native_jdbc_mysql/connection.rb +25 -0
  126. data/test/activerecord/jall.sh +7 -0
  127. data/test/activerecord/jtest.sh +3 -0
  128. data/test/cachedb_simple_test.rb +6 -0
  129. data/test/db/cachedb.rb +9 -0
  130. data/test/db/db2.rb +9 -0
  131. data/test/db/derby.rb +14 -0
  132. data/test/db/h2.rb +11 -0
  133. data/test/db/hsqldb.rb +12 -0
  134. data/test/db/informix.rb +11 -0
  135. data/test/db/jdbc.rb +11 -0
  136. data/test/db/jndi_config.rb +30 -0
  137. data/test/db/logger.rb +3 -0
  138. data/test/db/mssql.rb +9 -0
  139. data/test/db/mysql.rb +10 -0
  140. data/test/db/oracle.rb +34 -0
  141. data/test/db/postgres.rb +9 -0
  142. data/test/db/sqlite3.rb +15 -0
  143. data/test/db2_simple_test.rb +10 -0
  144. data/test/derby_migration_test.rb +21 -0
  145. data/test/derby_multibyte_test.rb +12 -0
  146. data/test/derby_simple_test.rb +12 -0
  147. data/test/generic_jdbc_connection_test.rb +9 -0
  148. data/test/h2_simple_test.rb +6 -0
  149. data/test/has_many_through.rb +79 -0
  150. data/test/hsqldb_simple_test.rb +6 -0
  151. data/test/informix_simple_test.rb +48 -0
  152. data/test/jdbc_adapter/jdbc_db2_test.rb +26 -0
  153. data/test/jdbc_adapter/jdbc_sybase_test.rb +33 -0
  154. data/test/jdbc_common.rb +24 -0
  155. data/test/jndi_callbacks_test.rb +38 -0
  156. data/test/jndi_test.rb +35 -0
  157. data/test/manualTestDatabase.rb +191 -0
  158. data/test/minirunit.rb +109 -0
  159. data/test/minirunit/testConnect.rb +14 -0
  160. data/test/minirunit/testH2.rb +73 -0
  161. data/test/minirunit/testHsqldb.rb +73 -0
  162. data/test/minirunit/testLoadActiveRecord.rb +3 -0
  163. data/test/minirunit/testMysql.rb +83 -0
  164. data/test/minirunit/testRawSelect.rb +24 -0
  165. data/test/models/add_not_null_column_to_table.rb +12 -0
  166. data/test/models/auto_id.rb +18 -0
  167. data/test/models/data_types.rb +28 -0
  168. data/test/models/entry.rb +23 -0
  169. data/test/models/mixed_case.rb +20 -0
  170. data/test/models/reserved_word.rb +18 -0
  171. data/test/mssql_simple_test.rb +6 -0
  172. data/test/mysql_multibyte_test.rb +10 -0
  173. data/test/mysql_nonstandard_primary_key_test.rb +43 -0
  174. data/test/mysql_simple_test.rb +26 -0
  175. data/test/oracle_simple_test.rb +29 -0
  176. data/test/postgres_mixed_case_test.rb +19 -0
  177. data/test/postgres_nonseq_pkey_test.rb +40 -0
  178. data/test/postgres_reserved_test.rb +22 -0
  179. data/test/postgres_simple_test.rb +12 -0
  180. data/test/simple.rb +397 -0
  181. data/test/sqlite3_simple_test.rb +179 -0
  182. data/test/sybase_jtds_simple_test.rb +6 -0
  183. metadata +294 -0
@@ -0,0 +1,133 @@
1
+ /***** BEGIN LICENSE BLOCK *****
2
+ * Copyright (c) 2006-2009 Nick Sieger <nick@nicksieger.com>
3
+ * Copyright (c) 2006-2007 Ola Bini <ola.bini@gmail.com>
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining
6
+ * a copy of this software and associated documentation files (the
7
+ * "Software"), to deal in the Software without restriction, including
8
+ * without limitation the rights to use, copy, modify, merge, publish,
9
+ * distribute, sublicense, and/or sell copies of the Software, and to
10
+ * permit persons to whom the Software is furnished to do so, subject to
11
+ * the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be
14
+ * included in all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ ***** END LICENSE BLOCK *****/
24
+
25
+ package jdbc_adapter;
26
+
27
+ import java.sql.Connection;
28
+
29
+ import org.jruby.RubyModule;
30
+ import org.jruby.RubyString;
31
+
32
+ import org.jruby.anno.JRubyMethod;
33
+ import org.jruby.runtime.ThreadContext;
34
+ import org.jruby.runtime.builtin.IRubyObject;
35
+
36
+ import org.jruby.util.ByteList;
37
+
38
+ public class JdbcMySQLSpec {
39
+ public static void load(RubyModule jdbcSpec) {
40
+ RubyModule mysql = jdbcSpec.defineModuleUnder("MySQL");
41
+ mysql.defineAnnotatedMethods(JdbcMySQLSpec.class);
42
+ }
43
+
44
+ private final static byte BACKQUOTE = '`';
45
+ private final static byte[] QUOTED_DOT = new byte[] {'`', '.', '`'};
46
+
47
+ private final static byte[] ZERO = new byte[] {'\\','0'};
48
+ private final static byte[] NEWLINE = new byte[] {'\\','n'};
49
+ private final static byte[] CARRIAGE = new byte[] {'\\','r'};
50
+ private final static byte[] ZED = new byte[] {'\\','Z'};
51
+ private final static byte[] DBL = new byte[] {'\\','"'};
52
+ private final static byte[] SINGLE = new byte[] {'\\','\''};
53
+ private final static byte[] ESCAPE = new byte[] {'\\','\\'};
54
+
55
+ @JRubyMethod(name = "quote_string", required = 1, frame=false)
56
+ public static IRubyObject quote_string(ThreadContext context, IRubyObject recv, IRubyObject string) {
57
+ ByteList bytes = ((RubyString) string).getByteList();
58
+ ByteList newBytes = new ByteList();
59
+
60
+ newBytes.append(bytes);
61
+
62
+ for(int i = newBytes.begin; i < newBytes.begin + newBytes.realSize; i++) {
63
+ byte[] rep = null;
64
+ switch (newBytes.bytes[i]) {
65
+ case 0: rep = ZERO; break;
66
+ case '\n': rep = NEWLINE; break;
67
+ case '\r': rep = CARRIAGE; break;
68
+ case 26: rep = ZED; break;
69
+ case '"': rep = DBL; break;
70
+ case '\'': rep = SINGLE; break;
71
+ case '\\': rep = ESCAPE; break;
72
+ }
73
+
74
+ if (rep != null) {
75
+ newBytes.replace(i, 1, rep);
76
+ i += rep.length - 1; // We subtract one since for loop already adds one
77
+ }
78
+ }
79
+
80
+ // Nothing changed, can return original
81
+ if (newBytes.length() == bytes.length()) return string;
82
+
83
+ return context.getRuntime().newString(newBytes);
84
+ }
85
+
86
+ @JRubyMethod(name = "quote_column_name", frame=false)
87
+ public static IRubyObject quote_column_name(ThreadContext context, IRubyObject recv, IRubyObject arg) {
88
+ ByteList bytes = arg.asString().getByteList();
89
+ ByteList newBytes = new ByteList();
90
+
91
+ newBytes.insert(0, BACKQUOTE);
92
+ newBytes.append(bytes);
93
+ newBytes.append(BACKQUOTE);
94
+
95
+ return context.getRuntime().newString(newBytes);
96
+ }
97
+
98
+ @JRubyMethod(name = "quote_table_name", frame=false)
99
+ public static IRubyObject quote_table_name(ThreadContext context, IRubyObject recv, IRubyObject arg) {
100
+ ByteList bytes = arg.asString().getByteList();
101
+ ByteList newBytes = new ByteList();
102
+
103
+ newBytes.insert(0, BACKQUOTE);
104
+ newBytes.append(bytes);
105
+ int i = 0;
106
+ while ((i = newBytes.indexOf('.')) != -1) {
107
+ newBytes.replace(i, 1, QUOTED_DOT);
108
+ }
109
+ newBytes.append(BACKQUOTE);
110
+
111
+ return context.getRuntime().newString(newBytes);
112
+ }
113
+
114
+ /**
115
+ * HACK HACK HACK See http://bugs.mysql.com/bug.php?id=36565
116
+ * MySQL's statement cancel timer can cause memory leaks, so cancel it
117
+ * if we loaded MySQL classes from the same classloader as JRuby
118
+ */
119
+ @JRubyMethod(module = true, frame = false)
120
+ public static IRubyObject kill_cancel_timer(ThreadContext context, IRubyObject recv, IRubyObject raw_connection) {
121
+ Connection conn = (Connection) raw_connection.dataGetStruct();
122
+ if (conn != null && conn.getClass().getClassLoader() == recv.getRuntime().getJRubyClassLoader()) {
123
+ try {
124
+ java.lang.reflect.Field f = conn.getClass().getDeclaredField("cancelTimer");
125
+ f.setAccessible(true);
126
+ java.util.Timer timer = (java.util.Timer) f.get(null);
127
+ timer.cancel();
128
+ } catch (Exception e) {
129
+ }
130
+ }
131
+ return recv.getRuntime().getNil();
132
+ }
133
+ }
@@ -0,0 +1,71 @@
1
+ /*
2
+ **** BEGIN LICENSE BLOCK *****
3
+ * Copyright (c) 2006-2009 Nick Sieger <nick@nicksieger.com>
4
+ * Copyright (c) 2006-2007 Ola Bini <ola.bini@gmail.com>
5
+ * Copyright (c) 2008-2009 Thomas E Enebo <enebo@acm.org>
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining
8
+ * a copy of this software and associated documentation files (the
9
+ * "Software"), to deal in the Software without restriction, including
10
+ * without limitation the rights to use, copy, modify, merge, publish,
11
+ * distribute, sublicense, and/or sell copies of the Software, and to
12
+ * permit persons to whom the Software is furnished to do so, subject to
13
+ * the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be
16
+ * included in all copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
+ ***** END LICENSE BLOCK *****/
26
+ package jdbc_adapter;
27
+
28
+ import java.sql.ResultSet;
29
+ import java.sql.SQLException;
30
+ import java.sql.Types;
31
+ import org.jruby.Ruby;
32
+ import org.jruby.RubyClass;
33
+ import org.jruby.runtime.ObjectAllocator;
34
+ import org.jruby.runtime.builtin.IRubyObject;
35
+
36
+ /**
37
+ *
38
+ * @author nicksieger
39
+ */
40
+ public class MssqlRubyJdbcConnection extends RubyJdbcConnection {
41
+
42
+ protected MssqlRubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
43
+ super(runtime, metaClass);
44
+ }
45
+
46
+ public static RubyClass createMssqlJdbcConnectionClass(Ruby runtime, RubyClass jdbcConnection) {
47
+ RubyClass clazz = RubyJdbcConnection.getConnectionAdapters(runtime).defineClassUnder("MssqlJdbcConnection",
48
+ jdbcConnection, MSSQL_JDBCCONNECTION_ALLOCATOR);
49
+ clazz.defineAnnotatedMethods(MssqlRubyJdbcConnection.class);
50
+
51
+ return clazz;
52
+ }
53
+ private static ObjectAllocator MSSQL_JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
54
+
55
+ public IRubyObject allocate(Ruby runtime, RubyClass klass) {
56
+ return new MssqlRubyJdbcConnection(runtime, klass);
57
+ }
58
+ };
59
+
60
+ /**
61
+ * Treat LONGVARCHAR as CLOB on Mssql for purposes of converting a JDBC value to Ruby.
62
+ */
63
+ @Override
64
+ protected IRubyObject jdbcToRuby(Ruby runtime, int column, int type, ResultSet resultSet)
65
+ throws SQLException {
66
+ if (type == Types.LONGVARCHAR) {
67
+ type = Types.CLOB;
68
+ }
69
+ return super.jdbcToRuby(runtime, column, type, resultSet);
70
+ }
71
+ }
@@ -0,0 +1,55 @@
1
+ /*
2
+ **** BEGIN LICENSE BLOCK *****
3
+ * Copyright (c) 2006-2009 Nick Sieger <nick@nicksieger.com>
4
+ * Copyright (c) 2006-2007 Ola Bini <ola.bini@gmail.com>
5
+ * Copyright (c) 2008-2009 Thomas E Enebo <enebo@acm.org>
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining
8
+ * a copy of this software and associated documentation files (the
9
+ * "Software"), to deal in the Software without restriction, including
10
+ * without limitation the rights to use, copy, modify, merge, publish,
11
+ * distribute, sublicense, and/or sell copies of the Software, and to
12
+ * permit persons to whom the Software is furnished to do so, subject to
13
+ * the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be
16
+ * included in all copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
+ ***** END LICENSE BLOCK *****/
26
+ package jdbc_adapter;
27
+
28
+ import org.jruby.Ruby;
29
+ import org.jruby.RubyClass;
30
+ import org.jruby.runtime.ObjectAllocator;
31
+ import org.jruby.runtime.builtin.IRubyObject;
32
+
33
+ /**
34
+ *
35
+ * @author enebo
36
+ */
37
+ public class PostgresRubyJdbcConnection extends RubyJdbcConnection {
38
+ protected PostgresRubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
39
+ super(runtime, metaClass);
40
+ }
41
+
42
+ public static RubyClass createPostgresJdbcConnectionClass(Ruby runtime, RubyClass jdbcConnection) {
43
+ RubyClass clazz = RubyJdbcConnection.getConnectionAdapters(runtime).defineClassUnder("PostgresJdbcConnection",
44
+ jdbcConnection, POSTGRES_JDBCCONNECTION_ALLOCATOR);
45
+ clazz.defineAnnotatedMethods(PostgresRubyJdbcConnection.class);
46
+
47
+ return clazz;
48
+ }
49
+
50
+ private static ObjectAllocator POSTGRES_JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
51
+ public IRubyObject allocate(Ruby runtime, RubyClass klass) {
52
+ return new PostgresRubyJdbcConnection(runtime, klass);
53
+ }
54
+ };
55
+ }
@@ -0,0 +1,1163 @@
1
+ /*
2
+ **** BEGIN LICENSE BLOCK *****
3
+ * Copyright (c) 2006-2009 Nick Sieger <nick@nicksieger.com>
4
+ * Copyright (c) 2006-2007 Ola Bini <ola.bini@gmail.com>
5
+ * Copyright (c) 2008-2009 Thomas E Enebo <enebo@acm.org>
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining
8
+ * a copy of this software and associated documentation files (the
9
+ * "Software"), to deal in the Software without restriction, including
10
+ * without limitation the rights to use, copy, modify, merge, publish,
11
+ * distribute, sublicense, and/or sell copies of the Software, and to
12
+ * permit persons to whom the Software is furnished to do so, subject to
13
+ * the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be
16
+ * included in all copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
+ ***** END LICENSE BLOCK *****/
26
+ package jdbc_adapter;
27
+
28
+ import java.io.ByteArrayInputStream;
29
+ import java.io.IOException;
30
+ import java.io.InputStream;
31
+ import java.io.Reader;
32
+ import java.io.StringReader;
33
+ import org.jruby.Ruby;
34
+ import org.jruby.RubyClass;
35
+ import org.jruby.RubyModule;
36
+ import org.jruby.RubyObject;
37
+ import org.jruby.RubyObjectAdapter;
38
+ import org.jruby.anno.JRubyMethod;
39
+ import org.jruby.javasupport.JavaEmbedUtils;
40
+ import org.jruby.runtime.ObjectAllocator;
41
+ import org.jruby.runtime.ThreadContext;
42
+ import org.jruby.runtime.builtin.IRubyObject;
43
+ import org.jruby.util.ByteList;
44
+
45
+ import java.sql.Connection;
46
+ import java.sql.DatabaseMetaData;
47
+ import java.sql.PreparedStatement;
48
+ import java.sql.ResultSet;
49
+ import java.sql.ResultSetMetaData;
50
+ import java.sql.SQLException;
51
+ import java.sql.Statement;
52
+ import java.sql.Timestamp;
53
+ import java.sql.Types;
54
+ import java.text.DateFormat;
55
+ import java.text.SimpleDateFormat;
56
+ import java.util.ArrayList;
57
+ import java.util.Calendar;
58
+ import java.util.Date;
59
+ import java.util.List;
60
+ import org.jruby.RubyArray;
61
+ import org.jruby.RubyHash;
62
+ import org.jruby.RubyNumeric;
63
+ import org.jruby.RubyString;
64
+ import org.jruby.RubySymbol;
65
+ import org.jruby.RubyTime;
66
+ import org.jruby.exceptions.RaiseException;
67
+ import org.jruby.javasupport.Java;
68
+ import org.jruby.javasupport.JavaObject;
69
+ import org.jruby.runtime.Arity;
70
+ import org.jruby.runtime.Block;
71
+
72
+ /**
73
+ * Part of our ActiveRecord::ConnectionAdapters::Connection impl.
74
+ */
75
+ public class RubyJdbcConnection extends RubyObject {
76
+ private static final String[] TABLE_TYPE = new String[]{"TABLE"};
77
+
78
+ private static RubyObjectAdapter rubyApi;
79
+
80
+ protected RubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
81
+ super(runtime, metaClass);
82
+ }
83
+
84
+ public static RubyClass createJdbcConnectionClass(Ruby runtime) {
85
+ RubyClass jdbcConnection = getConnectionAdapters(runtime).defineClassUnder("JdbcConnection",
86
+ runtime.getObject(), JDBCCONNECTION_ALLOCATOR);
87
+ jdbcConnection.defineAnnotatedMethods(RubyJdbcConnection.class);
88
+
89
+ rubyApi = JavaEmbedUtils.newObjectAdapter();
90
+
91
+ return jdbcConnection;
92
+ }
93
+
94
+ private static ObjectAllocator JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
95
+ public IRubyObject allocate(Ruby runtime, RubyClass klass) {
96
+ return new RubyJdbcConnection(runtime, klass);
97
+ }
98
+ };
99
+
100
+ protected static RubyModule getConnectionAdapters(Ruby runtime) {
101
+ return (RubyModule) runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters");
102
+ }
103
+
104
+ @JRubyMethod(name = "begin")
105
+ public IRubyObject begin(ThreadContext context) throws SQLException {
106
+ final Ruby runtime = context.getRuntime();
107
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
108
+ public Object call(Connection c) throws SQLException {
109
+ getConnection(true).setAutoCommit(false);
110
+ return runtime.getNil();
111
+ }
112
+ });
113
+ }
114
+
115
+ @JRubyMethod(name = {"columns", "columns_internal"}, required = 1, optional = 2)
116
+ public IRubyObject columns_internal(final ThreadContext context, final IRubyObject[] args)
117
+ throws SQLException, IOException {
118
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
119
+ public Object call(Connection c) throws SQLException {
120
+ ResultSet results = null;
121
+ try {
122
+ String table_name = rubyApi.convertToRubyString(args[0]).getUnicodeValue();
123
+ String schemaName = null;
124
+
125
+ int index = table_name.indexOf(".");
126
+ if(index != -1) {
127
+ schemaName = table_name.substring(0, index);
128
+ table_name = table_name.substring(index + 1);
129
+ }
130
+
131
+ DatabaseMetaData metadata = c.getMetaData();
132
+
133
+ if(args.length > 2) schemaName = toStringOrNull(args[2]);
134
+
135
+ if (schemaName != null) schemaName = caseConvertIdentifierForJdbc(metadata, schemaName);
136
+ table_name = caseConvertIdentifierForJdbc(metadata, table_name);
137
+
138
+ String[] tableTypes = new String[]{"TABLE","VIEW","SYNONYM"};
139
+ RubyArray matchingTables = (RubyArray) tableLookupBlock(context.getRuntime(),
140
+ c.getCatalog(), schemaName, table_name, tableTypes, false).call(c);
141
+ if (matchingTables.isEmpty()) {
142
+ throw new SQLException("Table " + table_name + " does not exist");
143
+ }
144
+
145
+ results = metadata.getColumns(c.getCatalog(),schemaName,table_name,null);
146
+ return unmarshal_columns(context, metadata, results);
147
+ } finally {
148
+ close(results);
149
+ }
150
+ }
151
+ });
152
+ }
153
+
154
+ @JRubyMethod(name = "commit")
155
+ public IRubyObject commit(ThreadContext context) throws SQLException {
156
+ Connection connection = getConnection(true);
157
+
158
+ if (!connection.getAutoCommit()) {
159
+ try {
160
+ connection.commit();
161
+ } finally {
162
+ connection.setAutoCommit(true);
163
+ }
164
+ }
165
+
166
+ return context.getRuntime().getNil();
167
+ }
168
+
169
+ @JRubyMethod(name = "connection", frame = false)
170
+ public IRubyObject connection() {
171
+ if (getConnection() == null) reconnect();
172
+
173
+ return getInstanceVariable("@connection");
174
+ }
175
+
176
+ @JRubyMethod(name = "database_name", frame = false)
177
+ public IRubyObject database_name(ThreadContext context) throws SQLException {
178
+ Connection connection = getConnection(true);
179
+ String name = connection.getCatalog();
180
+
181
+ if (null == name) {
182
+ name = connection.getMetaData().getUserName();
183
+
184
+ if (null == name) name = "db1";
185
+ }
186
+
187
+ return context.getRuntime().newString(name);
188
+ }
189
+
190
+ @JRubyMethod(name = "disconnect!", frame = false)
191
+ public IRubyObject disconnect() {
192
+ return setConnection(null);
193
+ }
194
+
195
+ @JRubyMethod(name = "execute_id_insert", required = 2)
196
+ public IRubyObject execute_id_insert(ThreadContext context, final IRubyObject sql,
197
+ final IRubyObject id) throws SQLException {
198
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
199
+ public Object call(Connection c) throws SQLException {
200
+ PreparedStatement ps = c.prepareStatement(rubyApi.convertToRubyString(sql).getUnicodeValue());
201
+ try {
202
+ ps.setLong(1, RubyNumeric.fix2long(id));
203
+ ps.executeUpdate();
204
+ } finally {
205
+ close(ps);
206
+ }
207
+ return id;
208
+ }
209
+ });
210
+ }
211
+
212
+ @JRubyMethod(name = "execute_insert", required = 1)
213
+ public IRubyObject execute_insert(final ThreadContext context, final IRubyObject sql)
214
+ throws SQLException {
215
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
216
+ public Object call(Connection c) throws SQLException {
217
+ Statement stmt = null;
218
+ try {
219
+ stmt = c.createStatement();
220
+ stmt.executeUpdate(rubyApi.convertToRubyString(sql).getUnicodeValue(), Statement.RETURN_GENERATED_KEYS);
221
+ return unmarshal_id_result(context.getRuntime(), stmt.getGeneratedKeys());
222
+ } finally {
223
+ close(stmt);
224
+ }
225
+ }
226
+ });
227
+ }
228
+
229
+ @JRubyMethod(name = "execute_query", required = 1)
230
+ public IRubyObject execute_query(final ThreadContext context, IRubyObject _sql)
231
+ throws SQLException, IOException {
232
+ String sql = rubyApi.convertToRubyString(_sql).getUnicodeValue();
233
+
234
+ return executeQuery(context, sql, 0);
235
+ }
236
+
237
+ @JRubyMethod(name = "execute_query", required = 2)
238
+ public IRubyObject execute_query(final ThreadContext context, IRubyObject _sql,
239
+ IRubyObject _maxRows) throws SQLException, IOException {
240
+ String sql = rubyApi.convertToRubyString(_sql).getUnicodeValue();
241
+ int maxrows = RubyNumeric.fix2int(_maxRows);
242
+
243
+ return executeQuery(context, sql, maxrows);
244
+ }
245
+
246
+ protected IRubyObject executeQuery(final ThreadContext context, final String query, final int maxRows) {
247
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
248
+ public Object call(Connection c) throws SQLException {
249
+ Statement stmt = null;
250
+ try {
251
+ DatabaseMetaData metadata = c.getMetaData();
252
+ stmt = c.createStatement();
253
+ stmt.setMaxRows(maxRows);
254
+ return unmarshalResult(context, metadata, stmt.executeQuery(query), false);
255
+ } finally {
256
+ close(stmt);
257
+ }
258
+ }
259
+ });
260
+ }
261
+
262
+ @JRubyMethod(name = "execute_update", required = 1)
263
+ public IRubyObject execute_update(final ThreadContext context, final IRubyObject sql)
264
+ throws SQLException {
265
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
266
+ public Object call(Connection c) throws SQLException {
267
+ Statement stmt = null;
268
+ try {
269
+ stmt = c.createStatement();
270
+ return context.getRuntime().newFixnum((long)stmt.executeUpdate(rubyApi.convertToRubyString(sql).getUnicodeValue()));
271
+ } finally {
272
+ close(stmt);
273
+ }
274
+ }
275
+ });
276
+ }
277
+
278
+ @JRubyMethod(name = "indexes")
279
+ public IRubyObject indexes(ThreadContext context, IRubyObject tableName, IRubyObject name, IRubyObject schemaName) {
280
+ return indexes(context, toStringOrNull(tableName), toStringOrNull(name), toStringOrNull(schemaName));
281
+ }
282
+
283
+ private static final int INDEX_TABLE_NAME = 3;
284
+ private static final int INDEX_NON_UNIQUE = 4;
285
+ private static final int INDEX_NAME = 6;
286
+ private static final int INDEX_COLUMN_NAME = 9;
287
+
288
+ /**
289
+ * Default JDBC introspection for index metadata on the JdbcConnection.
290
+ *
291
+ * JDBC index metadata is denormalized (multiple rows may be returned for
292
+ * one index, one row per column in the index), so a simple block-based
293
+ * filter like that used for tables doesn't really work here. Callers
294
+ * should filter the return from this method instead.
295
+ */
296
+ protected IRubyObject indexes(final ThreadContext context, final String tableNameArg, final String name, final String schemaNameArg) {
297
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
298
+ public Object call(Connection c) throws SQLException {
299
+ Ruby runtime = context.getRuntime();
300
+ DatabaseMetaData metadata = c.getMetaData();
301
+ String tableName = caseConvertIdentifierForJdbc(metadata, tableNameArg);
302
+ String schemaName = caseConvertIdentifierForJdbc(metadata, schemaNameArg);
303
+
304
+ ResultSet resultSet = null;
305
+ List indexes = new ArrayList();
306
+ try {
307
+ resultSet = metadata.getIndexInfo(null, schemaName, tableName, false, false);
308
+ List primaryKeys = primaryKeys(context, tableName);
309
+ String currentIndex = null;
310
+ RubyModule indexDefinitionClass = getConnectionAdapters(runtime).getClass("IndexDefinition");
311
+
312
+ while (resultSet.next()) {
313
+ String indexName = resultSet.getString(INDEX_NAME);
314
+
315
+ if (indexName == null) continue;
316
+
317
+ indexName = caseConvertIdentifierForRails(metadata, indexName);
318
+
319
+ RubyString columnName = RubyString.newUnicodeString(runtime, caseConvertIdentifierForRails(metadata, resultSet.getString(INDEX_COLUMN_NAME)));
320
+
321
+ if (primaryKeys.contains(columnName)) continue;
322
+
323
+ // We are working on a new index
324
+ if (!indexName.equals(currentIndex)) {
325
+ currentIndex = indexName;
326
+
327
+ tableName = caseConvertIdentifierForRails(metadata, resultSet.getString(INDEX_TABLE_NAME));
328
+ boolean nonUnique = resultSet.getBoolean(INDEX_NON_UNIQUE);
329
+
330
+ IRubyObject indexDefinition = indexDefinitionClass.callMethod(context, "new",
331
+ new IRubyObject[] {
332
+ RubyString.newUnicodeString(runtime, tableName),
333
+ RubyString.newUnicodeString(runtime, indexName),
334
+ runtime.newBoolean(!nonUnique),
335
+ runtime.newArray()
336
+ });
337
+
338
+ // empty list for column names, we'll add to that in just a bit
339
+ indexes.add(indexDefinition);
340
+ }
341
+
342
+ // One or more columns can be associated with an index
343
+ IRubyObject lastIndex = (IRubyObject) indexes.get(indexes.size() - 1);
344
+
345
+ if (lastIndex != null) {
346
+ lastIndex.callMethod(context, "columns").callMethod(context, "<<", columnName);
347
+ }
348
+ }
349
+
350
+ return runtime.newArray(indexes);
351
+ } finally {
352
+ close(resultSet);
353
+ }
354
+ }
355
+ });
356
+ }
357
+
358
+ @JRubyMethod(name = "insert?", required = 1, meta = true, frame = false)
359
+ public static IRubyObject insert_p(ThreadContext context, IRubyObject recv, IRubyObject _sql) {
360
+ ByteList sql = rubyApi.convertToRubyString(_sql).getByteList();
361
+
362
+ return context.getRuntime().newBoolean(startsWithNoCaseCmp(sql, INSERT));
363
+ }
364
+
365
+ /*
366
+ * sql, values, types, name = nil, pk = nil, id_value = nil, sequence_name = nil
367
+ */
368
+ @JRubyMethod(name = "insert_bind", required = 3, rest = true)
369
+ public IRubyObject insert_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException {
370
+ final Ruby runtime = context.getRuntime();
371
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
372
+ public Object call(Connection c) throws SQLException {
373
+ PreparedStatement ps = null;
374
+ try {
375
+ ps = c.prepareStatement(rubyApi.convertToRubyString(args[0]).toString(), Statement.RETURN_GENERATED_KEYS);
376
+ setValuesOnPS(ps, context, args[1], args[2]);
377
+ ps.executeUpdate();
378
+ return unmarshal_id_result(runtime, ps.getGeneratedKeys());
379
+ } finally {
380
+ close(ps);
381
+ }
382
+ }
383
+ });
384
+ }
385
+
386
+ @JRubyMethod(name = "native_database_types", frame = false)
387
+ public IRubyObject native_database_types() {
388
+ return getInstanceVariable("@native_database_types");
389
+ }
390
+
391
+
392
+ @JRubyMethod(name = "primary_keys", required = 1)
393
+ public IRubyObject primary_keys(ThreadContext context, IRubyObject tableName) throws SQLException {
394
+ return context.getRuntime().newArray(primaryKeys(context, tableName.toString()));
395
+ }
396
+
397
+ protected List primaryKeys(final ThreadContext context, final String tableNameArg) {
398
+ return (List) withConnectionAndRetry(context, new SQLBlock() {
399
+ public Object call(Connection c) throws SQLException {
400
+ Ruby runtime = context.getRuntime();
401
+ DatabaseMetaData metadata = c.getMetaData();
402
+ String tableName = caseConvertIdentifierForJdbc(metadata, tableNameArg);
403
+ ResultSet resultSet = null;
404
+ List keyNames = new ArrayList();
405
+ try {
406
+ resultSet = metadata.getPrimaryKeys(null, null, tableName);
407
+
408
+ while (resultSet.next()) {
409
+ keyNames.add(RubyString.newUnicodeString(runtime,
410
+ caseConvertIdentifierForRails(metadata, resultSet.getString(4))));
411
+ }
412
+ } finally {
413
+ close(resultSet);
414
+ }
415
+
416
+ return keyNames;
417
+ }
418
+ });
419
+ }
420
+
421
+ @JRubyMethod(name = "reconnect!")
422
+ public IRubyObject reconnect() {
423
+ return setConnection(getConnectionFactory().newConnection());
424
+ }
425
+
426
+
427
+ @JRubyMethod(name = "rollback")
428
+ public IRubyObject rollback(ThreadContext context) throws SQLException {
429
+ final Ruby runtime = context.getRuntime();
430
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
431
+ public Object call(Connection c) throws SQLException {
432
+ Connection connection = getConnection(true);
433
+
434
+ if (!connection.getAutoCommit()) {
435
+ try {
436
+ connection.rollback();
437
+ } finally {
438
+ connection.setAutoCommit(true);
439
+ }
440
+ }
441
+
442
+ return runtime.getNil();
443
+ }
444
+ });
445
+ }
446
+
447
+ @JRubyMethod(name = "select?", required = 1, meta = true, frame = false)
448
+ public static IRubyObject select_p(ThreadContext context, IRubyObject recv, IRubyObject _sql) {
449
+ ByteList sql = rubyApi.convertToRubyString(_sql).getByteList();
450
+
451
+ return context.getRuntime().newBoolean(startsWithNoCaseCmp(sql, SELECT) ||
452
+ startsWithNoCaseCmp(sql, SHOW) || startsWithNoCaseCmp(sql, CALL));
453
+ }
454
+
455
+ @JRubyMethod(name = "set_native_database_types")
456
+ public IRubyObject set_native_database_types(ThreadContext context) throws SQLException, IOException {
457
+ Ruby runtime = context.getRuntime();
458
+ DatabaseMetaData metadata = getConnection(true).getMetaData();
459
+ IRubyObject types = unmarshalResult(context, metadata, metadata.getTypeInfo(), true);
460
+ IRubyObject typeConverter = getConnectionAdapters(runtime).getConstant("JdbcTypeConverter");
461
+ IRubyObject value = rubyApi.callMethod(rubyApi.callMethod(typeConverter, "new", types), "choose_best_types");
462
+ setInstanceVariable("@native_types", value);
463
+
464
+ return runtime.getNil();
465
+ }
466
+
467
+ @JRubyMethod(name = "tables")
468
+ public IRubyObject tables(ThreadContext context) {
469
+ return tables(context, null, null, null, TABLE_TYPE);
470
+ }
471
+
472
+ @JRubyMethod(name = "tables")
473
+ public IRubyObject tables(ThreadContext context, IRubyObject catalog) {
474
+ return tables(context, toStringOrNull(catalog), null, null, TABLE_TYPE);
475
+ }
476
+
477
+ @JRubyMethod(name = "tables")
478
+ public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern) {
479
+ return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), null, TABLE_TYPE);
480
+ }
481
+
482
+ @JRubyMethod(name = "tables")
483
+ public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern, IRubyObject tablePattern) {
484
+ return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), toStringOrNull(tablePattern), TABLE_TYPE);
485
+ }
486
+
487
+ @JRubyMethod(name = "tables", required = 4, rest = true)
488
+ public IRubyObject tables(ThreadContext context, IRubyObject[] args) {
489
+ return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), getTypes(args[3]));
490
+ }
491
+
492
+ protected IRubyObject tables(ThreadContext context, String catalog, String schemaPattern, String tablePattern, String[] types) {
493
+ return (IRubyObject) withConnectionAndRetry(context, tableLookupBlock(context.getRuntime(), catalog, schemaPattern, tablePattern, types, false));
494
+ }
495
+
496
+ /*
497
+ * sql, values, types, name = nil
498
+ */
499
+ @JRubyMethod(name = "update_bind", required = 3, rest = true)
500
+ public IRubyObject update_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException {
501
+ final Ruby runtime = context.getRuntime();
502
+ Arity.checkArgumentCount(runtime, args, 3, 4);
503
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
504
+ public Object call(Connection c) throws SQLException {
505
+ PreparedStatement ps = null;
506
+ try {
507
+ ps = c.prepareStatement(rubyApi.convertToRubyString(args[0]).toString());
508
+ setValuesOnPS(ps, context, args[1], args[2]);
509
+ ps.executeUpdate();
510
+ } finally {
511
+ close(ps);
512
+ }
513
+ return runtime.getNil();
514
+ }
515
+ });
516
+ }
517
+
518
+ @JRubyMethod(name = "with_connection_retry_guard", frame = true)
519
+ public IRubyObject with_connection_retry_guard(final ThreadContext context, final Block block) {
520
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
521
+ public Object call(Connection c) throws SQLException {
522
+ return block.call(context, new IRubyObject[] { wrappedConnection(c) });
523
+ }
524
+ });
525
+ }
526
+
527
+ /*
528
+ * (is binary?, colname, tablename, primary key, id, value)
529
+ */
530
+ @JRubyMethod(name = "write_large_object", required = 6)
531
+ public IRubyObject write_large_object(ThreadContext context, final IRubyObject[] args)
532
+ throws SQLException, IOException {
533
+ final Ruby runtime = context.getRuntime();
534
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
535
+ public Object call(Connection c) throws SQLException {
536
+ String sql = "UPDATE " + rubyApi.convertToRubyString(args[2])
537
+ + " SET " + rubyApi.convertToRubyString(args[1])
538
+ + " = ? WHERE " + rubyApi.convertToRubyString(args[3])
539
+ + "=" + rubyApi.convertToRubyString(args[4]);
540
+ PreparedStatement ps = null;
541
+ try {
542
+ ps = c.prepareStatement(sql);
543
+ if (args[0].isTrue()) { // binary
544
+ ByteList outp = rubyApi.convertToRubyString(args[5]).getByteList();
545
+ ps.setBinaryStream(1, new ByteArrayInputStream(outp.bytes,
546
+ outp.begin, outp.realSize), outp.realSize);
547
+ } else { // clob
548
+ String ss = rubyApi.convertToRubyString(args[5]).getUnicodeValue();
549
+ ps.setCharacterStream(1, new StringReader(ss), ss.length());
550
+ }
551
+ ps.executeUpdate();
552
+ } finally {
553
+ close(ps);
554
+ }
555
+ return runtime.getNil();
556
+ }
557
+ });
558
+ }
559
+
560
+ /**
561
+ * Convert an identifier coming back from the database to a case which Rails is expecting.
562
+ *
563
+ * Assumption: Rails identifiers will be quoted for mixed or will stay mixed
564
+ * as identifier names in Rails itself. Otherwise, they expect identifiers to
565
+ * be lower-case. Databases which store identifiers uppercase should be made
566
+ * lower-case.
567
+ *
568
+ * Assumption 2: It is always safe to convert all upper case names since it appears that
569
+ * some adapters do not report StoresUpper/Lower/Mixed correctly (am I right postgres/mysql?).
570
+ */
571
+ public static String caseConvertIdentifierForRails(DatabaseMetaData metadata, String value)
572
+ throws SQLException {
573
+ if (value == null) return null;
574
+
575
+ return metadata.storesUpperCaseIdentifiers() ? value.toLowerCase() : value;
576
+ }
577
+
578
+ /**
579
+ * Convert an identifier destined for a method which cares about the databases internal
580
+ * storage case. Methods like DatabaseMetaData.getPrimaryKeys() needs the table name to match
581
+ * the internal storage name. Arbtrary queries and the like DO NOT need to do this.
582
+ */
583
+ public static String caseConvertIdentifierForJdbc(DatabaseMetaData metadata, String value)
584
+ throws SQLException {
585
+ if (value == null) return null;
586
+
587
+ if (metadata.storesUpperCaseIdentifiers()) {
588
+ return value.toUpperCase();
589
+ } else if (metadata.storesLowerCaseIdentifiers()) {
590
+ return value.toLowerCase();
591
+ }
592
+
593
+ return value;
594
+ }
595
+
596
+ // helpers
597
+ protected static void close(Connection connection) {
598
+ if (connection != null) {
599
+ try {
600
+ connection.close();
601
+ } catch(Exception e) {}
602
+ }
603
+ }
604
+
605
+ public static void close(ResultSet resultSet) {
606
+ if (resultSet != null) {
607
+ try {
608
+ resultSet.close();
609
+ } catch(Exception e) {}
610
+ }
611
+ }
612
+
613
+ public static void close(Statement statement) {
614
+ if (statement != null) {
615
+ try {
616
+ statement.close();
617
+ } catch(Exception e) {}
618
+ }
619
+ }
620
+
621
+ protected IRubyObject config_value(ThreadContext context, String key) {
622
+ IRubyObject config_hash = getInstanceVariable("@config");
623
+
624
+ return config_hash.callMethod(context, "[]", context.getRuntime().newSymbol(key));
625
+ }
626
+
627
+ private static String toStringOrNull(IRubyObject arg) {
628
+ return arg.isNil() ? null : arg.toString();
629
+ }
630
+
631
+ protected IRubyObject floatToRuby(Ruby runtime, ResultSet resultSet, float floatValue)
632
+ throws SQLException, IOException {
633
+ if (floatValue == 0 && resultSet.wasNull()) return runtime.getNil();
634
+
635
+ return runtime.newFloat(floatValue);
636
+ }
637
+
638
+ protected Connection getConnection() {
639
+ return getConnection(false);
640
+ }
641
+
642
+ protected Connection getConnection(boolean error) {
643
+ Connection conn = (Connection) dataGetStruct();
644
+ if(error && conn == null) {
645
+ RubyClass err = getRuntime().getModule("ActiveRecord").getClass("ConnectionNotEstablished");
646
+ throw new RaiseException(getRuntime(), err, "no connection available", false);
647
+ }
648
+ return conn;
649
+ }
650
+
651
+ protected JdbcConnectionFactory getConnectionFactory() throws RaiseException {
652
+ IRubyObject connection_factory = getInstanceVariable("@connection_factory");
653
+ JdbcConnectionFactory factory = null;
654
+ try {
655
+ factory = (JdbcConnectionFactory) JavaEmbedUtils.rubyToJava(
656
+ connection_factory.getRuntime(), connection_factory, JdbcConnectionFactory.class);
657
+ } catch (Exception e) {
658
+ factory = null;
659
+ }
660
+ if (factory == null) {
661
+ throw getRuntime().newRuntimeError("@connection_factory not set properly");
662
+ }
663
+ return factory;
664
+ }
665
+
666
+ private static String[] getTypes(IRubyObject typeArg) {
667
+ if (!(typeArg instanceof RubyArray)) return new String[] { typeArg.toString() };
668
+
669
+ IRubyObject[] arr = rubyApi.convertToJavaArray(typeArg);
670
+ String[] types = new String[arr.length];
671
+ for (int i = 0; i < types.length; i++) {
672
+ types[i] = arr[i].toString();
673
+ }
674
+
675
+ return types;
676
+ }
677
+
678
+ private static int getTypeValueFor(Ruby runtime, IRubyObject type) throws SQLException {
679
+ // How could this ever yield anything useful?
680
+ if (!(type instanceof RubySymbol)) type = rubyApi.callMethod(type, "class");
681
+
682
+ // Assumption; If this is a symbol then it will be backed by an interned string. (enebo)
683
+ String internedValue = type.asJavaString();
684
+
685
+ if(internedValue == "string") {
686
+ return Types.VARCHAR;
687
+ } else if(internedValue == "text") {
688
+ return Types.CLOB;
689
+ } else if(internedValue == "integer") {
690
+ return Types.INTEGER;
691
+ } else if(internedValue == "decimal") {
692
+ return Types.DECIMAL;
693
+ } else if(internedValue == "float") {
694
+ return Types.FLOAT;
695
+ } else if(internedValue == "datetime") {
696
+ return Types.TIMESTAMP;
697
+ } else if(internedValue == "timestamp") {
698
+ return Types.TIMESTAMP;
699
+ } else if(internedValue == "time") {
700
+ return Types.TIME;
701
+ } else if(internedValue == "date") {
702
+ return Types.DATE;
703
+ } else if(internedValue == "binary") {
704
+ return Types.BLOB;
705
+ } else if(internedValue == "boolean") {
706
+ return Types.BOOLEAN;
707
+ } else {
708
+ return -1;
709
+ }
710
+ }
711
+
712
+ private boolean isConnectionBroken(ThreadContext context, Connection c) {
713
+ try {
714
+ IRubyObject alive = config_value(context, "connection_alive_sql");
715
+ if (select_p(context, this, alive).isTrue()) {
716
+ String connectionSQL = rubyApi.convertToRubyString(alive).toString();
717
+ Statement s = c.createStatement();
718
+ try {
719
+ s.execute(connectionSQL);
720
+ } finally {
721
+ close(s);
722
+ }
723
+ return false;
724
+ } else {
725
+ return !c.isClosed();
726
+ }
727
+ } catch (Exception sx) {
728
+ return true;
729
+ }
730
+ }
731
+
732
+ protected IRubyObject integerToRuby(Ruby runtime, ResultSet resultSet, long longValue)
733
+ throws SQLException, IOException {
734
+ if (longValue == 0 && resultSet.wasNull()) return runtime.getNil();
735
+
736
+ return runtime.newFixnum(longValue);
737
+ }
738
+
739
+ protected IRubyObject jdbcToRuby(Ruby runtime, int column, int type, ResultSet resultSet)
740
+ throws SQLException {
741
+ try {
742
+ switch (type) {
743
+ case Types.BINARY:
744
+ case Types.BLOB:
745
+ case Types.LONGVARBINARY:
746
+ case Types.VARBINARY:
747
+ case Types.LONGVARCHAR:
748
+ return streamToRuby(runtime, resultSet, resultSet.getBinaryStream(column));
749
+ case Types.CLOB:
750
+ return readerToRuby(runtime, resultSet, resultSet.getCharacterStream(column));
751
+ case Types.TIMESTAMP:
752
+ return timestampToRuby(runtime, resultSet, resultSet.getTimestamp(column));
753
+ case Types.INTEGER: case Types.SMALLINT: case Types.TINYINT:
754
+ return integerToRuby(runtime, resultSet, resultSet.getLong(column));
755
+ case Types.REAL:
756
+ return floatToRuby(runtime, resultSet, resultSet.getFloat(column));
757
+ default:
758
+ return stringToRuby(runtime, resultSet, resultSet.getString(column));
759
+ }
760
+ } catch (IOException ioe) {
761
+ throw (SQLException) new SQLException(ioe.getMessage()).initCause(ioe);
762
+ }
763
+ }
764
+
765
+ protected void populateFromResultSet(ThreadContext context, Ruby runtime, List results,
766
+ ResultSet resultSet, ColumnData[] columns) throws SQLException {
767
+ int columnCount = columns.length;
768
+
769
+ while (resultSet.next()) {
770
+ RubyHash row = RubyHash.newHash(runtime);
771
+
772
+ for (int i = 0; i < columnCount; i++) {
773
+ row.op_aset(context, columns[i].name, jdbcToRuby(runtime, i + 1, columns[i].type, resultSet));
774
+ }
775
+ results.add(row);
776
+ }
777
+ }
778
+
779
+
780
+ protected IRubyObject readerToRuby(Ruby runtime, ResultSet resultSet, Reader reader)
781
+ throws SQLException, IOException {
782
+ if (reader == null && resultSet.wasNull()) return runtime.getNil();
783
+
784
+ StringBuffer str = new StringBuffer(2048);
785
+ try {
786
+ char[] buf = new char[2048];
787
+
788
+ for (int n = reader.read(buf); n != -1; n = reader.read(buf)) {
789
+ str.append(buf, 0, n);
790
+ }
791
+ } finally {
792
+ reader.close();
793
+ }
794
+
795
+ return RubyString.newUnicodeString(runtime, str.toString());
796
+ }
797
+
798
+ private IRubyObject setConnection(Connection c) {
799
+ close(getConnection()); // Close previously open connection if there is one
800
+
801
+ IRubyObject rubyconn = c != null ? wrappedConnection(c) : getRuntime().getNil();
802
+ setInstanceVariable("@connection", rubyconn);
803
+ dataWrapStruct(c);
804
+ return this;
805
+ }
806
+
807
+ private final static DateFormat FORMAT = new SimpleDateFormat("%y-%M-%d %H:%m:%s");
808
+
809
+ private static void setValue(PreparedStatement ps, int index, ThreadContext context,
810
+ IRubyObject value, IRubyObject type) throws SQLException {
811
+ final int tp = getTypeValueFor(context.getRuntime(), type);
812
+ if(value.isNil()) {
813
+ ps.setNull(index, tp);
814
+ return;
815
+ }
816
+
817
+ switch(tp) {
818
+ case Types.VARCHAR:
819
+ case Types.CLOB:
820
+ ps.setString(index, RubyString.objAsString(context, value).toString());
821
+ break;
822
+ case Types.INTEGER:
823
+ ps.setLong(index, RubyNumeric.fix2long(value));
824
+ break;
825
+ case Types.FLOAT:
826
+ ps.setDouble(index, ((RubyNumeric)value).getDoubleValue());
827
+ break;
828
+ case Types.TIMESTAMP:
829
+ case Types.TIME:
830
+ case Types.DATE:
831
+ if(!(value instanceof RubyTime)) {
832
+ try {
833
+ Date dd = FORMAT.parse(RubyString.objAsString(context, value).toString());
834
+ ps.setTimestamp(index, new java.sql.Timestamp(dd.getTime()), Calendar.getInstance());
835
+ } catch(Exception e) {
836
+ ps.setString(index, RubyString.objAsString(context, value).toString());
837
+ }
838
+ } else {
839
+ RubyTime rubyTime = (RubyTime) value;
840
+ java.util.Date date = rubyTime.getJavaDate();
841
+ long millis = date.getTime();
842
+ long micros = rubyTime.microseconds() - millis / 1000;
843
+ java.sql.Timestamp ts = new java.sql.Timestamp(millis);
844
+ java.util.Calendar cal = Calendar.getInstance();
845
+ cal.setTime(date);
846
+ ts.setNanos((int)(micros * 1000));
847
+ ps.setTimestamp(index, ts, cal);
848
+ }
849
+ break;
850
+ case Types.BOOLEAN:
851
+ ps.setBoolean(index, value.isTrue());
852
+ break;
853
+ default: throw new RuntimeException("type " + type + " not supported in _bind yet");
854
+ }
855
+ }
856
+
857
+ private static void setValuesOnPS(PreparedStatement ps, ThreadContext context,
858
+ IRubyObject valuesArg, IRubyObject typesArg) throws SQLException {
859
+ RubyArray values = (RubyArray) valuesArg;
860
+ RubyArray types = (RubyArray) typesArg;
861
+
862
+ for(int i=0, j=values.getLength(); i<j; i++) {
863
+ setValue(ps, i+1, context, values.eltInternal(i), types.eltInternal(i));
864
+ }
865
+ }
866
+
867
+ protected IRubyObject streamToRuby(Ruby runtime, ResultSet resultSet, InputStream is)
868
+ throws SQLException, IOException {
869
+ if (is == null && resultSet.wasNull()) return runtime.getNil();
870
+
871
+ ByteList str = new ByteList(2048);
872
+ try {
873
+ byte[] buf = new byte[2048];
874
+
875
+ for (int n = is.read(buf); n != -1; n = is.read(buf)) {
876
+ str.append(buf, 0, n);
877
+ }
878
+ } finally {
879
+ is.close();
880
+ }
881
+
882
+ return runtime.newString(str);
883
+ }
884
+
885
+ protected IRubyObject stringToRuby(Ruby runtime, ResultSet resultSet, String string)
886
+ throws SQLException, IOException {
887
+ if (string == null && resultSet.wasNull()) return runtime.getNil();
888
+
889
+ return RubyString.newUnicodeString(runtime, string);
890
+ }
891
+
892
+ private static final int TABLE_NAME = 3;
893
+
894
+ protected SQLBlock tableLookupBlock(final Ruby runtime,
895
+ final String catalog, final String schemapat,
896
+ final String tablepat, final String[] types, final boolean downCase) {
897
+ return new SQLBlock() {
898
+ public Object call(Connection c) throws SQLException {
899
+ ResultSet rs = null;
900
+ try {
901
+ DatabaseMetaData metadata = c.getMetaData();
902
+ String clzName = metadata.getClass().getName().toLowerCase();
903
+ boolean isOracle = clzName.indexOf("oracle") != -1 || clzName.indexOf("oci") != -1;
904
+
905
+ String realschema = schemapat;
906
+ String realtablepat = tablepat;
907
+
908
+ if (realtablepat != null) realtablepat = caseConvertIdentifierForJdbc(metadata, realtablepat);
909
+ if (realschema != null) realschema = caseConvertIdentifierForJdbc(metadata, realschema);
910
+
911
+ rs = metadata.getTables(catalog, realschema, realtablepat, types);
912
+ List arr = new ArrayList();
913
+ while (rs.next()) {
914
+ String name;
915
+
916
+ if (downCase) {
917
+ name = rs.getString(TABLE_NAME).toLowerCase();
918
+ } else {
919
+ name = caseConvertIdentifierForRails(metadata, rs.getString(TABLE_NAME));
920
+ }
921
+ // Handle stupid Oracle 10g RecycleBin feature
922
+ if (!isOracle || !name.startsWith("bin$")) {
923
+ arr.add(RubyString.newUnicodeString(runtime, name));
924
+ }
925
+ }
926
+ return runtime.newArray(arr);
927
+ } finally {
928
+ close(rs);
929
+ }
930
+ }
931
+ };
932
+ }
933
+
934
+ protected IRubyObject timestampToRuby(Ruby runtime, ResultSet resultSet, Timestamp time)
935
+ throws SQLException, IOException {
936
+ if (time == null && resultSet.wasNull()) return runtime.getNil();
937
+
938
+ String str = time.toString();
939
+ if (str.endsWith(" 00:00:00.0")) {
940
+ str = str.substring(0, str.length() - (" 00:00:00.0".length()));
941
+ }
942
+
943
+ return RubyString.newUnicodeString(runtime, str);
944
+ }
945
+
946
+ private static final int COLUMN_NAME = 4;
947
+ private static final int DATA_TYPE = 5;
948
+ private static final int TYPE_NAME = 6;
949
+ private static final int COLUMN_SIZE = 7;
950
+ private static final int DECIMAL_DIGITS = 9;
951
+ private static final int COLUMN_DEF = 13;
952
+ private static final int IS_NULLABLE = 18;
953
+
954
+ private int intFromResultSet(ResultSet resultSet, int column) throws SQLException {
955
+ int precision = resultSet.getInt(column);
956
+
957
+ return precision == 0 && resultSet.wasNull() ? -1 : precision;
958
+ }
959
+
960
+ /**
961
+ * Create a string which represents a sql type usable by Rails from the resultSet column
962
+ * metadata object.
963
+ *
964
+ * @param numberAsBoolean the database uses decimal as a boolean data type
965
+ * because it does not support optional SQL92 type or mandatory SQL99
966
+ * booleans.
967
+ */
968
+ private String typeFromResultSet(ResultSet resultSet, boolean numberAsBoolean) throws SQLException {
969
+ int precision = intFromResultSet(resultSet, COLUMN_SIZE);
970
+ int scale = intFromResultSet(resultSet, DECIMAL_DIGITS);
971
+
972
+ // Assume db's which use decimal for boolean will not also specify a
973
+ // valid precision 1 decimal also. Seems sketchy to me...
974
+ if (numberAsBoolean && precision != 1 &&
975
+ resultSet.getInt(DATA_TYPE) == java.sql.Types.DECIMAL) precision = -1;
976
+
977
+ String type = resultSet.getString(TYPE_NAME);
978
+ if (precision > 0) {
979
+ type += "(" + precision;
980
+ if(scale > 0) type += "," + scale;
981
+ type += ")";
982
+ }
983
+
984
+ return type;
985
+ }
986
+
987
+ private IRubyObject defaultValueFromResultSet(Ruby runtime, ResultSet resultSet)
988
+ throws SQLException {
989
+ String defaultValue = resultSet.getString(COLUMN_DEF);
990
+
991
+ return defaultValue == null ? runtime.getNil() : RubyString.newUnicodeString(runtime, defaultValue);
992
+ }
993
+
994
+ private IRubyObject unmarshal_columns(ThreadContext context, DatabaseMetaData metadata,
995
+ ResultSet rs) throws SQLException {
996
+ try {
997
+ Ruby runtime = context.getRuntime();
998
+ List columns = new ArrayList();
999
+ String clzName = metadata.getClass().getName().toLowerCase();
1000
+ boolean isOracle = clzName.indexOf("oracle") != -1 || clzName.indexOf("oci") != -1;
1001
+
1002
+ RubyHash types = (RubyHash) native_database_types();
1003
+ IRubyObject jdbcCol = getConnectionAdapters(runtime).getConstant("JdbcColumn");
1004
+
1005
+ while(rs.next()) {
1006
+ IRubyObject column = jdbcCol.callMethod(context, "new",
1007
+ new IRubyObject[] {
1008
+ getInstanceVariable("@config"),
1009
+ RubyString.newUnicodeString(runtime,
1010
+ caseConvertIdentifierForRails(metadata, rs.getString(COLUMN_NAME))),
1011
+ defaultValueFromResultSet(runtime, rs),
1012
+ RubyString.newUnicodeString(runtime, typeFromResultSet(rs, isOracle)),
1013
+ runtime.newBoolean(!rs.getString(IS_NULLABLE).trim().equals("NO"))
1014
+ });
1015
+ columns.add(column);
1016
+
1017
+ IRubyObject tp = (IRubyObject)types.fastARef(column.callMethod(context,"type"));
1018
+ if(tp != null && !tp.isNil() && tp.callMethod(context, "[]", runtime.newSymbol("limit")).isNil()) {
1019
+ column.callMethod(context, "limit=", runtime.getNil());
1020
+ if(!column.callMethod(context, "type").equals(runtime.newSymbol("decimal"))) {
1021
+ column.callMethod(context, "precision=", runtime.getNil());
1022
+ }
1023
+ }
1024
+ }
1025
+ return runtime.newArray(columns);
1026
+ } finally {
1027
+ close(rs);
1028
+ }
1029
+ }
1030
+
1031
+
1032
+ public static IRubyObject unmarshal_id_result(Ruby runtime, ResultSet rs) throws SQLException {
1033
+ try {
1034
+ if (rs.next() && rs.getMetaData().getColumnCount() > 0) {
1035
+ return runtime.newFixnum(rs.getLong(1));
1036
+ }
1037
+ return runtime.getNil();
1038
+ } finally {
1039
+ close(rs);
1040
+ }
1041
+ }
1042
+
1043
+ /**
1044
+ * Converts a jdbc resultset into an array (rows) of hashes (row) that AR expects.
1045
+ *
1046
+ * @param downCase should column names only be in lower case?
1047
+ */
1048
+ protected IRubyObject unmarshalResult(ThreadContext context, DatabaseMetaData metadata,
1049
+ ResultSet resultSet, boolean downCase) throws SQLException {
1050
+ Ruby runtime = context.getRuntime();
1051
+ List results = new ArrayList();
1052
+
1053
+ try {
1054
+ ColumnData[] columns = ColumnData.setup(runtime, metadata, resultSet.getMetaData(), downCase);
1055
+
1056
+ populateFromResultSet(context, runtime, results, resultSet, columns);
1057
+ } finally {
1058
+ close(resultSet);
1059
+ }
1060
+
1061
+ return runtime.newArray(results);
1062
+ }
1063
+
1064
+ protected Object withConnectionAndRetry(ThreadContext context, SQLBlock block) {
1065
+ int tries = 1;
1066
+ int i = 0;
1067
+ Throwable toWrap = null;
1068
+ boolean autoCommit = false;
1069
+ while (i < tries) {
1070
+ Connection c = getConnection(true);
1071
+ try {
1072
+ autoCommit = c.getAutoCommit();
1073
+ return block.call(c);
1074
+ } catch (Exception e) {
1075
+ toWrap = e;
1076
+ while (toWrap.getCause() != null && toWrap.getCause() != toWrap) {
1077
+ toWrap = toWrap.getCause();
1078
+ }
1079
+ i++;
1080
+ if (autoCommit) {
1081
+ if (i == 1) {
1082
+ tries = (int) rubyApi.convertToRubyInteger(config_value(context, "retry_count")).getLongValue();
1083
+ if (tries <= 0) {
1084
+ tries = 1;
1085
+ }
1086
+ }
1087
+ if (isConnectionBroken(context, c)) {
1088
+ reconnect();
1089
+ } else {
1090
+ throw wrap(context, toWrap);
1091
+ }
1092
+ }
1093
+ }
1094
+ }
1095
+ throw wrap(context, toWrap);
1096
+ }
1097
+
1098
+ private static RuntimeException wrap(ThreadContext context, Throwable exception) {
1099
+ RubyClass err = context.getRuntime().getModule("ActiveRecord").getClass("ActiveRecordError");
1100
+ return (RuntimeException) new RaiseException(context.getRuntime(), err, exception.getMessage(), false).initCause(exception);
1101
+ }
1102
+
1103
+ private IRubyObject wrappedConnection(Connection c) {
1104
+ return Java.java_to_ruby(this, JavaObject.wrap(getRuntime(), c), Block.NULL_BLOCK);
1105
+ }
1106
+
1107
+ private static int whitespace(int start, ByteList bl) {
1108
+ int end = bl.begin + bl.realSize;
1109
+
1110
+ for (int i = start; i < end; i++) {
1111
+ if (!Character.isWhitespace(bl.bytes[i])) return i;
1112
+ }
1113
+
1114
+ return end;
1115
+ }
1116
+
1117
+ private static byte[] CALL = new byte[]{'c', 'a', 'l', 'l'};
1118
+ private static byte[] INSERT = new byte[] {'i', 'n', 's', 'e', 'r', 't'};
1119
+ private static byte[] SELECT = new byte[] {'s', 'e', 'l', 'e', 'c', 't'};
1120
+ private static byte[] SHOW = new byte[] {'s', 'h', 'o', 'w'};
1121
+
1122
+ private static boolean startsWithNoCaseCmp(ByteList bytelist, byte[] compare) {
1123
+ int p = whitespace(bytelist.begin, bytelist);
1124
+
1125
+ // What the hell is this for?
1126
+ if (bytelist.bytes[p] == '(') p = whitespace(p, bytelist);
1127
+
1128
+ for (int i = 0; i < bytelist.realSize && i < compare.length; i++) {
1129
+ if (Character.toLowerCase(bytelist.bytes[p + i]) != compare[i]) return false;
1130
+ }
1131
+
1132
+ return true;
1133
+ }
1134
+
1135
+ public static class ColumnData {
1136
+ public IRubyObject name;
1137
+ public int type;
1138
+
1139
+ public ColumnData(IRubyObject name, int type) {
1140
+ this.name = name;
1141
+ this.type = type;
1142
+ }
1143
+
1144
+ public static ColumnData[] setup(Ruby runtime, DatabaseMetaData databaseMetadata,
1145
+ ResultSetMetaData metadata, boolean downCase) throws SQLException {
1146
+ int columnsCount = metadata.getColumnCount();
1147
+ ColumnData[] columns = new ColumnData[columnsCount];
1148
+
1149
+ for (int i = 1; i <= columnsCount; i++) { // metadata is one-based
1150
+ String name;
1151
+ if (downCase) {
1152
+ name = metadata.getColumnLabel(i).toLowerCase();
1153
+ } else {
1154
+ name = RubyJdbcConnection.caseConvertIdentifierForRails(databaseMetadata, metadata.getColumnLabel(i));
1155
+ }
1156
+
1157
+ columns[i - 1] = new ColumnData(RubyString.newUnicodeString(runtime, name), metadata.getColumnType(i));
1158
+ }
1159
+
1160
+ return columns;
1161
+ }
1162
+ }
1163
+ }