intentmedia-activerecord-jdbc-adapter 1.1.1.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (177) hide show
  1. data/History.txt +404 -0
  2. data/LICENSE.txt +21 -0
  3. data/README.txt +181 -0
  4. data/Rakefile +10 -0
  5. data/lib/active_record/connection_adapters/derby_adapter.rb +1 -0
  6. data/lib/active_record/connection_adapters/h2_adapter.rb +1 -0
  7. data/lib/active_record/connection_adapters/hsqldb_adapter.rb +1 -0
  8. data/lib/active_record/connection_adapters/informix_adapter.rb +1 -0
  9. data/lib/active_record/connection_adapters/jdbc_adapter.rb +1 -0
  10. data/lib/active_record/connection_adapters/jndi_adapter.rb +1 -0
  11. data/lib/active_record/connection_adapters/mssql_adapter.rb +1 -0
  12. data/lib/active_record/connection_adapters/mysql2_adapter.rb +1 -0
  13. data/lib/active_record/connection_adapters/mysql_adapter.rb +1 -0
  14. data/lib/active_record/connection_adapters/oracle_adapter.rb +1 -0
  15. data/lib/active_record/connection_adapters/postgresql_adapter.rb +1 -0
  16. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +1 -0
  17. data/lib/activerecord-jdbc-adapter.rb +8 -0
  18. data/lib/arel/engines/sql/compilers/db2_compiler.rb +9 -0
  19. data/lib/arel/engines/sql/compilers/derby_compiler.rb +6 -0
  20. data/lib/arel/engines/sql/compilers/h2_compiler.rb +6 -0
  21. data/lib/arel/engines/sql/compilers/hsqldb_compiler.rb +15 -0
  22. data/lib/arel/engines/sql/compilers/jdbc_compiler.rb +6 -0
  23. data/lib/arel/engines/sql/compilers/mssql_compiler.rb +46 -0
  24. data/lib/arel/visitors/compat.rb +13 -0
  25. data/lib/arel/visitors/db2.rb +17 -0
  26. data/lib/arel/visitors/derby.rb +21 -0
  27. data/lib/arel/visitors/hsqldb.rb +26 -0
  28. data/lib/arel/visitors/sql_server.rb +46 -0
  29. data/lib/arjdbc.rb +29 -0
  30. data/lib/arjdbc/db2.rb +2 -0
  31. data/lib/arjdbc/db2/adapter.rb +413 -0
  32. data/lib/arjdbc/derby.rb +7 -0
  33. data/lib/arjdbc/derby/adapter.rb +348 -0
  34. data/lib/arjdbc/derby/connection_methods.rb +18 -0
  35. data/lib/arjdbc/discover.rb +92 -0
  36. data/lib/arjdbc/firebird.rb +2 -0
  37. data/lib/arjdbc/firebird/adapter.rb +131 -0
  38. data/lib/arjdbc/h2.rb +4 -0
  39. data/lib/arjdbc/h2/adapter.rb +36 -0
  40. data/lib/arjdbc/h2/connection_methods.rb +12 -0
  41. data/lib/arjdbc/hsqldb.rb +4 -0
  42. data/lib/arjdbc/hsqldb/adapter.rb +184 -0
  43. data/lib/arjdbc/hsqldb/connection_methods.rb +14 -0
  44. data/lib/arjdbc/informix.rb +3 -0
  45. data/lib/arjdbc/informix/adapter.rb +138 -0
  46. data/lib/arjdbc/informix/connection_methods.rb +10 -0
  47. data/lib/arjdbc/jdbc.rb +2 -0
  48. data/lib/arjdbc/jdbc/adapter.rb +285 -0
  49. data/lib/arjdbc/jdbc/callbacks.rb +44 -0
  50. data/lib/arjdbc/jdbc/column.rb +38 -0
  51. data/lib/arjdbc/jdbc/compatibility.rb +51 -0
  52. data/lib/arjdbc/jdbc/connection.rb +128 -0
  53. data/lib/arjdbc/jdbc/connection_methods.rb +16 -0
  54. data/lib/arjdbc/jdbc/core_ext.rb +24 -0
  55. data/lib/arjdbc/jdbc/discover.rb +18 -0
  56. data/lib/arjdbc/jdbc/driver.rb +44 -0
  57. data/lib/arjdbc/jdbc/extension.rb +47 -0
  58. data/lib/arjdbc/jdbc/java.rb +14 -0
  59. data/lib/arjdbc/jdbc/jdbc.rake +127 -0
  60. data/lib/arjdbc/jdbc/missing_functionality_helper.rb +87 -0
  61. data/lib/arjdbc/jdbc/quoted_primary_key.rb +28 -0
  62. data/lib/arjdbc/jdbc/railtie.rb +9 -0
  63. data/lib/arjdbc/jdbc/rake_tasks.rb +10 -0
  64. data/lib/arjdbc/jdbc/require_driver.rb +16 -0
  65. data/lib/arjdbc/jdbc/type_converter.rb +127 -0
  66. data/lib/arjdbc/mimer.rb +2 -0
  67. data/lib/arjdbc/mimer/adapter.rb +142 -0
  68. data/lib/arjdbc/mssql.rb +4 -0
  69. data/lib/arjdbc/mssql/adapter.rb +472 -0
  70. data/lib/arjdbc/mssql/connection_methods.rb +30 -0
  71. data/lib/arjdbc/mssql/limit_helpers.rb +92 -0
  72. data/lib/arjdbc/mssql/tsql_helper.rb +61 -0
  73. data/lib/arjdbc/mysql.rb +4 -0
  74. data/lib/arjdbc/mysql/adapter.rb +416 -0
  75. data/lib/arjdbc/mysql/connection_methods.rb +27 -0
  76. data/lib/arjdbc/oracle.rb +3 -0
  77. data/lib/arjdbc/oracle/adapter.rb +412 -0
  78. data/lib/arjdbc/oracle/connection_methods.rb +11 -0
  79. data/lib/arjdbc/postgresql.rb +4 -0
  80. data/lib/arjdbc/postgresql/adapter.rb +579 -0
  81. data/lib/arjdbc/postgresql/connection_methods.rb +21 -0
  82. data/lib/arjdbc/sqlite3.rb +4 -0
  83. data/lib/arjdbc/sqlite3/adapter.rb +381 -0
  84. data/lib/arjdbc/sqlite3/connection_methods.rb +34 -0
  85. data/lib/arjdbc/sybase.rb +2 -0
  86. data/lib/arjdbc/sybase/adapter.rb +46 -0
  87. data/lib/arjdbc/version.rb +8 -0
  88. data/lib/generators/jdbc/jdbc_generator.rb +9 -0
  89. data/lib/jdbc_adapter.rb +2 -0
  90. data/lib/jdbc_adapter/rake_tasks.rb +3 -0
  91. data/lib/jdbc_adapter/version.rb +3 -0
  92. data/lib/pg.rb +26 -0
  93. data/rails_generators/jdbc_generator.rb +15 -0
  94. data/rails_generators/templates/config/initializers/jdbc.rb +7 -0
  95. data/rails_generators/templates/lib/tasks/jdbc.rake +8 -0
  96. data/rakelib/compile.rake +25 -0
  97. data/rakelib/db.rake +19 -0
  98. data/rakelib/package.rake +91 -0
  99. data/rakelib/rails.rake +41 -0
  100. data/rakelib/test.rake +81 -0
  101. data/src/java/arjdbc/derby/DerbyModule.java +322 -0
  102. data/src/java/arjdbc/h2/H2RubyJdbcConnection.java +70 -0
  103. data/src/java/arjdbc/informix/InformixRubyJdbcConnection.java +74 -0
  104. data/src/java/arjdbc/jdbc/AdapterJavaService.java +66 -0
  105. data/src/java/arjdbc/jdbc/JdbcConnectionFactory.java +36 -0
  106. data/src/java/arjdbc/jdbc/RubyJdbcConnection.java +1305 -0
  107. data/src/java/arjdbc/jdbc/SQLBlock.java +48 -0
  108. data/src/java/arjdbc/mssql/MssqlRubyJdbcConnection.java +127 -0
  109. data/src/java/arjdbc/mysql/MySQLModule.java +134 -0
  110. data/src/java/arjdbc/mysql/MySQLRubyJdbcConnection.java +87 -0
  111. data/src/java/arjdbc/oracle/OracleRubyJdbcConnection.java +85 -0
  112. data/src/java/arjdbc/postgresql/PostgresqlRubyJdbcConnection.java +57 -0
  113. data/src/java/arjdbc/sqlite3/Sqlite3RubyJdbcConnection.java +64 -0
  114. data/test/abstract_db_create.rb +124 -0
  115. data/test/activerecord/connection_adapters/type_conversion_test.rb +31 -0
  116. data/test/activerecord/connections/native_jdbc_mysql/connection.rb +25 -0
  117. data/test/db/db2.rb +11 -0
  118. data/test/db/derby.rb +12 -0
  119. data/test/db/h2.rb +11 -0
  120. data/test/db/hsqldb.rb +13 -0
  121. data/test/db/informix.rb +11 -0
  122. data/test/db/jdbc.rb +11 -0
  123. data/test/db/jndi_config.rb +40 -0
  124. data/test/db/logger.rb +3 -0
  125. data/test/db/mssql.rb +9 -0
  126. data/test/db/mysql.rb +10 -0
  127. data/test/db/oracle.rb +34 -0
  128. data/test/db/postgres.rb +9 -0
  129. data/test/db/sqlite3.rb +11 -0
  130. data/test/db2_simple_test.rb +66 -0
  131. data/test/derby_migration_test.rb +68 -0
  132. data/test/derby_multibyte_test.rb +12 -0
  133. data/test/derby_simple_test.rb +99 -0
  134. data/test/generic_jdbc_connection_test.rb +29 -0
  135. data/test/h2_simple_test.rb +41 -0
  136. data/test/has_many_through.rb +79 -0
  137. data/test/helper.rb +5 -0
  138. data/test/hsqldb_simple_test.rb +6 -0
  139. data/test/informix_simple_test.rb +48 -0
  140. data/test/jdbc_common.rb +25 -0
  141. data/test/jndi_callbacks_test.rb +40 -0
  142. data/test/jndi_test.rb +25 -0
  143. data/test/manualTestDatabase.rb +191 -0
  144. data/test/models/add_not_null_column_to_table.rb +12 -0
  145. data/test/models/auto_id.rb +18 -0
  146. data/test/models/data_types.rb +28 -0
  147. data/test/models/entry.rb +43 -0
  148. data/test/models/mixed_case.rb +25 -0
  149. data/test/models/reserved_word.rb +18 -0
  150. data/test/models/string_id.rb +18 -0
  151. data/test/models/validates_uniqueness_of_string.rb +19 -0
  152. data/test/mssql_db_create_test.rb +26 -0
  153. data/test/mssql_identity_insert_test.rb +19 -0
  154. data/test/mssql_legacy_types_test.rb +58 -0
  155. data/test/mssql_limit_offset_test.rb +136 -0
  156. data/test/mssql_multibyte_test.rb +18 -0
  157. data/test/mssql_simple_test.rb +55 -0
  158. data/test/mysql_db_create_test.rb +27 -0
  159. data/test/mysql_info_test.rb +123 -0
  160. data/test/mysql_multibyte_test.rb +10 -0
  161. data/test/mysql_nonstandard_primary_key_test.rb +42 -0
  162. data/test/mysql_simple_test.rb +49 -0
  163. data/test/oracle_simple_test.rb +18 -0
  164. data/test/oracle_specific_test.rb +83 -0
  165. data/test/pick_rails_version.rb +3 -0
  166. data/test/postgres_db_create_test.rb +32 -0
  167. data/test/postgres_drop_db_test.rb +16 -0
  168. data/test/postgres_mixed_case_test.rb +29 -0
  169. data/test/postgres_nonseq_pkey_test.rb +38 -0
  170. data/test/postgres_reserved_test.rb +22 -0
  171. data/test/postgres_schema_search_path_test.rb +44 -0
  172. data/test/postgres_simple_test.rb +65 -0
  173. data/test/postgres_table_alias_length_test.rb +15 -0
  174. data/test/simple.rb +546 -0
  175. data/test/sqlite3_simple_test.rb +233 -0
  176. data/test/sybase_jtds_simple_test.rb +28 -0
  177. metadata +259 -0
@@ -0,0 +1,70 @@
1
+ /*
2
+ **** BEGIN LICENSE BLOCK *****
3
+ * Copyright (c) 2006-2010 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
+
27
+ package arjdbc.h2;
28
+
29
+ import java.sql.ResultSet;
30
+ import java.sql.SQLException;
31
+ import java.sql.Types;
32
+
33
+ import arjdbc.jdbc.RubyJdbcConnection;
34
+
35
+ import org.jruby.Ruby;
36
+ import org.jruby.RubyClass;
37
+ import org.jruby.runtime.ObjectAllocator;
38
+ import org.jruby.runtime.builtin.IRubyObject;
39
+
40
+ /**
41
+ *
42
+ * @author nicksieger
43
+ */
44
+ public class H2RubyJdbcConnection extends RubyJdbcConnection {
45
+ protected H2RubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
46
+ super(runtime, metaClass);
47
+ }
48
+
49
+ public static RubyClass createH2JdbcConnectionClass(Ruby runtime, RubyClass jdbcConnection) {
50
+ RubyClass clazz = RubyJdbcConnection.getConnectionAdapters(runtime).defineClassUnder("H2JdbcConnection",
51
+ jdbcConnection, H2_JDBCCONNECTION_ALLOCATOR);
52
+ clazz.defineAnnotatedMethods(H2RubyJdbcConnection.class);
53
+
54
+ return clazz;
55
+ }
56
+
57
+ private static ObjectAllocator H2_JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
58
+ public IRubyObject allocate(Ruby runtime, RubyClass klass) {
59
+ return new H2RubyJdbcConnection(runtime, klass);
60
+ }
61
+ };
62
+
63
+ /**
64
+ * H2 supports schemas.
65
+ */
66
+ @Override
67
+ protected boolean databaseSupportsSchemas() {
68
+ return true;
69
+ }
70
+ }
@@ -0,0 +1,74 @@
1
+ /*
2
+ **** BEGIN LICENSE BLOCK *****
3
+ * Copyright (c) 2006-2010 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
+
27
+ package arjdbc.informix;
28
+
29
+ import java.sql.ResultSet;
30
+ import java.sql.SQLException;
31
+ import java.sql.Types;
32
+
33
+ import arjdbc.jdbc.RubyJdbcConnection;
34
+
35
+ import org.jruby.Ruby;
36
+ import org.jruby.RubyClass;
37
+ import org.jruby.runtime.ObjectAllocator;
38
+ import org.jruby.runtime.builtin.IRubyObject;
39
+
40
+ /**
41
+ *
42
+ * @author nicksieger
43
+ */
44
+ public class InformixRubyJdbcConnection extends RubyJdbcConnection {
45
+ protected InformixRubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
46
+ super(runtime, metaClass);
47
+ }
48
+
49
+ public static RubyClass createInformixJdbcConnectionClass(Ruby runtime, RubyClass jdbcConnection) {
50
+ RubyClass clazz = RubyJdbcConnection.getConnectionAdapters(runtime).defineClassUnder("InformixJdbcConnection",
51
+ jdbcConnection, INFORMIX_JDBCCONNECTION_ALLOCATOR);
52
+ clazz.defineAnnotatedMethods(InformixRubyJdbcConnection.class);
53
+
54
+ return clazz;
55
+ }
56
+
57
+ private static ObjectAllocator INFORMIX_JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
58
+ public IRubyObject allocate(Ruby runtime, RubyClass klass) {
59
+ return new InformixRubyJdbcConnection(runtime, klass);
60
+ }
61
+ };
62
+
63
+ /**
64
+ * Treat LONGVARCHAR as CLOB on Informix for purposes of converting a JDBC value to Ruby.
65
+ */
66
+ @Override
67
+ protected IRubyObject jdbcToRuby(Ruby runtime, int column, int type, ResultSet resultSet)
68
+ throws SQLException {
69
+ if (type == Types.LONGVARCHAR) {
70
+ type = Types.CLOB;
71
+ }
72
+ return super.jdbcToRuby(runtime, column, type, resultSet);
73
+ }
74
+ }
@@ -0,0 +1,66 @@
1
+ /*
2
+ **** BEGIN LICENSE BLOCK *****
3
+ * Copyright (c) 2006-2010 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
+
27
+ package arjdbc.jdbc;
28
+
29
+ import java.io.IOException;
30
+
31
+ import arjdbc.derby.DerbyModule;
32
+ import arjdbc.h2.H2RubyJdbcConnection;
33
+ import arjdbc.informix.InformixRubyJdbcConnection;
34
+ import arjdbc.mssql.MssqlRubyJdbcConnection;
35
+ import arjdbc.mysql.MySQLModule;
36
+ import arjdbc.mysql.MySQLRubyJdbcConnection;
37
+ import arjdbc.oracle.OracleRubyJdbcConnection;
38
+ import arjdbc.postgresql.PostgresqlRubyJdbcConnection;
39
+ import arjdbc.sqlite3.Sqlite3RubyJdbcConnection;
40
+
41
+ import org.jruby.Ruby;
42
+ import org.jruby.RubyClass;
43
+ import org.jruby.RubyModule;
44
+ import org.jruby.RubyObjectAdapter;
45
+ import org.jruby.javasupport.JavaEmbedUtils;
46
+ import org.jruby.runtime.load.BasicLibraryService;
47
+
48
+ public class AdapterJavaService implements BasicLibraryService {
49
+ private static RubyObjectAdapter rubyApi;
50
+
51
+ public boolean basicLoad(final Ruby runtime) throws IOException {
52
+ RubyClass jdbcConnection = RubyJdbcConnection.createJdbcConnectionClass(runtime);
53
+ PostgresqlRubyJdbcConnection.createPostgresqlJdbcConnectionClass(runtime, jdbcConnection);
54
+ MssqlRubyJdbcConnection.createMssqlJdbcConnectionClass(runtime, jdbcConnection);
55
+ InformixRubyJdbcConnection.createInformixJdbcConnectionClass(runtime, jdbcConnection);
56
+ OracleRubyJdbcConnection.createOracleJdbcConnectionClass(runtime, jdbcConnection);
57
+ Sqlite3RubyJdbcConnection.createSqlite3JdbcConnectionClass(runtime, jdbcConnection);
58
+ H2RubyJdbcConnection.createH2JdbcConnectionClass(runtime, jdbcConnection);
59
+ MySQLRubyJdbcConnection.createMySQLJdbcConnectionClass(runtime, jdbcConnection);
60
+ RubyModule arJdbc = runtime.getOrCreateModule("ArJdbc");
61
+ rubyApi = JavaEmbedUtils.newObjectAdapter();
62
+ MySQLModule.load(arJdbc);
63
+ DerbyModule.load(arJdbc, rubyApi);
64
+ return true;
65
+ }
66
+ }
@@ -0,0 +1,36 @@
1
+ /***** BEGIN LICENSE BLOCK *****
2
+ * Copyright (c) 2006-2010 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 arjdbc.jdbc;
26
+
27
+ import java.sql.Connection;
28
+
29
+ /**
30
+ * Interface to be implemented in Ruby for retrieving a new connection
31
+ *
32
+ * @author nicksieger
33
+ */
34
+ public interface JdbcConnectionFactory {
35
+ Connection newConnection();
36
+ }
@@ -0,0 +1,1305 @@
1
+ /*
2
+ **** BEGIN LICENSE BLOCK *****
3
+ * Copyright (c) 2006-2010 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 arjdbc.jdbc;
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 java.math.BigInteger;
34
+ import java.sql.Connection;
35
+ import java.sql.DatabaseMetaData;
36
+ import java.sql.PreparedStatement;
37
+ import java.sql.ResultSet;
38
+ import java.sql.ResultSetMetaData;
39
+ import java.sql.SQLException;
40
+ import java.sql.Statement;
41
+ import java.sql.Timestamp;
42
+ import java.sql.Types;
43
+ import java.text.DateFormat;
44
+ import java.text.SimpleDateFormat;
45
+ import java.util.ArrayList;
46
+ import java.util.Calendar;
47
+ import java.util.Date;
48
+ import java.util.List;
49
+
50
+ import org.jruby.Ruby;
51
+ import org.jruby.RubyArray;
52
+ import org.jruby.RubyBignum;
53
+ import org.jruby.RubyClass;
54
+ import org.jruby.RubyHash;
55
+ import org.jruby.RubyModule;
56
+ import org.jruby.RubyNumeric;
57
+ import org.jruby.RubyObject;
58
+ import org.jruby.RubyObjectAdapter;
59
+ import org.jruby.RubyString;
60
+ import org.jruby.RubySymbol;
61
+ import org.jruby.RubyTime;
62
+ import org.jruby.anno.JRubyMethod;
63
+ import org.jruby.exceptions.RaiseException;
64
+ import org.jruby.javasupport.Java;
65
+ import org.jruby.javasupport.JavaEmbedUtils;
66
+ import org.jruby.javasupport.JavaObject;
67
+ import org.jruby.javasupport.util.RuntimeHelpers;
68
+ import org.jruby.runtime.Arity;
69
+ import org.jruby.runtime.Block;
70
+ import org.jruby.runtime.ObjectAllocator;
71
+ import org.jruby.runtime.ThreadContext;
72
+ import org.jruby.runtime.builtin.IRubyObject;
73
+ import org.jruby.util.ByteList;
74
+
75
+ /**
76
+ * Part of our ActiveRecord::ConnectionAdapters::Connection impl.
77
+ */
78
+ public class RubyJdbcConnection extends RubyObject {
79
+ private static final String[] TABLE_TYPE = new String[]{"TABLE"};
80
+
81
+ private static RubyObjectAdapter rubyApi;
82
+
83
+ protected RubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
84
+ super(runtime, metaClass);
85
+ }
86
+
87
+ public static RubyClass createJdbcConnectionClass(Ruby runtime) {
88
+ RubyClass jdbcConnection = getConnectionAdapters(runtime).defineClassUnder("JdbcConnection",
89
+ runtime.getObject(), JDBCCONNECTION_ALLOCATOR);
90
+ jdbcConnection.defineAnnotatedMethods(RubyJdbcConnection.class);
91
+
92
+ rubyApi = JavaEmbedUtils.newObjectAdapter();
93
+
94
+ return jdbcConnection;
95
+ }
96
+
97
+ private static ObjectAllocator JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
98
+ public IRubyObject allocate(Ruby runtime, RubyClass klass) {
99
+ return new RubyJdbcConnection(runtime, klass);
100
+ }
101
+ };
102
+
103
+ protected static RubyModule getConnectionAdapters(Ruby runtime) {
104
+ return (RubyModule) runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters");
105
+ }
106
+
107
+ @JRubyMethod(name = "begin")
108
+ public IRubyObject begin(ThreadContext context) throws SQLException {
109
+ final Ruby runtime = context.getRuntime();
110
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
111
+ public Object call(Connection c) throws SQLException {
112
+ getConnection(true).setAutoCommit(false);
113
+ return runtime.getNil();
114
+ }
115
+ });
116
+ }
117
+
118
+ @JRubyMethod(name = {"columns", "columns_internal"}, required = 1, optional = 2)
119
+ public IRubyObject columns_internal(final ThreadContext context, final IRubyObject[] args)
120
+ throws SQLException, IOException {
121
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
122
+ public Object call(Connection c) throws SQLException {
123
+ ResultSet results = null, pkeys = null;
124
+ try {
125
+ String table_name = rubyApi.convertToRubyString(args[0]).getUnicodeValue();
126
+ String schemaName = null;
127
+
128
+ final String[] name_parts = table_name.split( "\\." );
129
+ if ( name_parts.length > 3 ) {
130
+ throw new SQLException("Table name '" + table_name + "' should not contain more than 2 '.'");
131
+ }
132
+
133
+ DatabaseMetaData metadata = c.getMetaData();
134
+ String clzName = metadata.getClass().getName().toLowerCase();
135
+ boolean isDB2 = clzName.indexOf("db2") != -1 || clzName.indexOf("as400") != -1;
136
+
137
+ String catalog = c.getCatalog();
138
+ if( name_parts.length == 2 ) {
139
+ schemaName = name_parts[0];
140
+ table_name = name_parts[1];
141
+ }
142
+ else if ( name_parts.length == 3 ) {
143
+ catalog = name_parts[0];
144
+ schemaName = name_parts[1];
145
+ table_name = name_parts[2];
146
+ }
147
+
148
+ if(args.length > 2 && schemaName == null) schemaName = toStringOrNull(args[2]);
149
+
150
+ if (schemaName != null) schemaName = caseConvertIdentifierForJdbc(metadata, schemaName);
151
+ table_name = caseConvertIdentifierForJdbc(metadata, table_name);
152
+
153
+ if (schemaName != null && !isDB2 && !databaseSupportsSchemas()) { catalog = schemaName; }
154
+
155
+ String[] tableTypes = new String[]{"TABLE","VIEW","SYNONYM"};
156
+ RubyArray matchingTables = (RubyArray) tableLookupBlock(context.getRuntime(),
157
+ catalog, schemaName, table_name, tableTypes, false).call(c);
158
+ if (matchingTables.isEmpty()) {
159
+ throw new SQLException("Table " + table_name + " does not exist");
160
+ }
161
+
162
+ results = metadata.getColumns(catalog,schemaName,table_name,null);
163
+ pkeys = metadata.getPrimaryKeys(catalog,schemaName,table_name);
164
+ return unmarshal_columns(context, metadata, results, pkeys);
165
+ } finally {
166
+ close(results);
167
+ close(pkeys);
168
+ }
169
+ }
170
+ });
171
+ }
172
+
173
+ @JRubyMethod(name = "commit")
174
+ public IRubyObject commit(ThreadContext context) throws SQLException {
175
+ Connection connection = getConnection(true);
176
+
177
+ if (!connection.getAutoCommit()) {
178
+ try {
179
+ connection.commit();
180
+ } finally {
181
+ connection.setAutoCommit(true);
182
+ }
183
+ }
184
+
185
+ return context.getRuntime().getNil();
186
+ }
187
+
188
+ @JRubyMethod(name = "connection", frame = false)
189
+ public IRubyObject connection() {
190
+ if (getConnection() == null) reconnect();
191
+
192
+ return getInstanceVariable("@connection");
193
+ }
194
+
195
+ @JRubyMethod(name = "database_name", frame = false)
196
+ public IRubyObject database_name(ThreadContext context) throws SQLException {
197
+ Connection connection = getConnection(true);
198
+ String name = connection.getCatalog();
199
+
200
+ if (null == name) {
201
+ name = connection.getMetaData().getUserName();
202
+
203
+ if (null == name) name = "db1";
204
+ }
205
+
206
+ return context.getRuntime().newString(name);
207
+ }
208
+
209
+ @JRubyMethod(name = "disconnect!", frame = false)
210
+ public IRubyObject disconnect() {
211
+ return setConnection(null);
212
+ }
213
+
214
+ @JRubyMethod
215
+ public IRubyObject execute(final ThreadContext context, final IRubyObject sql) {
216
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
217
+ public Object call(Connection c) throws SQLException {
218
+ Statement stmt = null;
219
+ String query = rubyApi.convertToRubyString(sql).getUnicodeValue();
220
+ try {
221
+ stmt = c.createStatement();
222
+ if (genericExecute(stmt, query)) {
223
+ return unmarshalResults(context, c.getMetaData(), stmt, false);
224
+ } else {
225
+ return unmarshalKeysOrUpdateCount(context, c, stmt);
226
+ }
227
+ } catch (SQLException sqe) {
228
+ if (context.getRuntime().isDebug()) {
229
+ System.out.println("Error SQL: " + query);
230
+ }
231
+ throw sqe;
232
+ } finally {
233
+ close(stmt);
234
+ }
235
+ }
236
+ });
237
+ }
238
+
239
+ protected boolean genericExecute(Statement stmt, String query) throws SQLException {
240
+ return stmt.execute(query);
241
+ }
242
+
243
+ protected IRubyObject unmarshalKeysOrUpdateCount(ThreadContext context, Connection c, Statement stmt) throws SQLException {
244
+ IRubyObject key = context.getRuntime().getNil();
245
+ if (c.getMetaData().supportsGetGeneratedKeys()) {
246
+ key = unmarshal_id_result(context.getRuntime(), stmt.getGeneratedKeys());
247
+ }
248
+ if (key.isNil()) {
249
+ return context.getRuntime().newFixnum(stmt.getUpdateCount());
250
+ } else {
251
+ return key;
252
+ }
253
+ }
254
+
255
+ @JRubyMethod(name = "execute_id_insert", required = 2)
256
+ public IRubyObject execute_id_insert(final ThreadContext context, final IRubyObject sql,
257
+ final IRubyObject id) throws SQLException {
258
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
259
+ public Object call(Connection c) throws SQLException {
260
+ String insert = rubyApi.convertToRubyString(sql).getUnicodeValue();
261
+ PreparedStatement ps = c.prepareStatement(insert);
262
+ try {
263
+ ps.setLong(1, RubyNumeric.fix2long(id));
264
+ ps.executeUpdate();
265
+ } catch (SQLException sqe) {
266
+ if (context.getRuntime().isDebug()) {
267
+ System.out.println("Error SQL: " + insert);
268
+ }
269
+ throw sqe;
270
+ } finally {
271
+ close(ps);
272
+ }
273
+ return id;
274
+ }
275
+ });
276
+ }
277
+
278
+ @JRubyMethod(name = "execute_insert", required = 1)
279
+ public IRubyObject execute_insert(final ThreadContext context, final IRubyObject sql)
280
+ throws SQLException {
281
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
282
+ public Object call(Connection c) throws SQLException {
283
+ Statement stmt = null;
284
+ String insert = rubyApi.convertToRubyString(sql).getUnicodeValue();
285
+ try {
286
+ stmt = c.createStatement();
287
+ stmt.executeUpdate(insert, Statement.RETURN_GENERATED_KEYS);
288
+ return unmarshal_id_result(context.getRuntime(), stmt.getGeneratedKeys());
289
+ } catch (SQLException sqe) {
290
+ if (context.getRuntime().isDebug()) {
291
+ System.out.println("Error SQL: " + insert);
292
+ }
293
+ throw sqe;
294
+ } finally {
295
+ close(stmt);
296
+ }
297
+ }
298
+ });
299
+ }
300
+
301
+ @JRubyMethod(name = "execute_query", required = 1)
302
+ public IRubyObject execute_query(final ThreadContext context, IRubyObject _sql)
303
+ throws SQLException, IOException {
304
+ String sql = rubyApi.convertToRubyString(_sql).getUnicodeValue();
305
+
306
+ return executeQuery(context, sql, 0);
307
+ }
308
+
309
+ @JRubyMethod(name = "execute_query", required = 2)
310
+ public IRubyObject execute_query(final ThreadContext context, IRubyObject _sql,
311
+ IRubyObject _maxRows) throws SQLException, IOException {
312
+ String sql = rubyApi.convertToRubyString(_sql).getUnicodeValue();
313
+ int maxrows = RubyNumeric.fix2int(_maxRows);
314
+
315
+ return executeQuery(context, sql, maxrows);
316
+ }
317
+
318
+ protected IRubyObject executeQuery(final ThreadContext context, final String query, final int maxRows) {
319
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
320
+ public Object call(Connection c) throws SQLException {
321
+ Statement stmt = null;
322
+ try {
323
+ DatabaseMetaData metadata = c.getMetaData();
324
+ stmt = c.createStatement();
325
+ stmt.setMaxRows(maxRows);
326
+ return unmarshalResult(context, metadata, stmt.executeQuery(query), false);
327
+ } catch (SQLException sqe) {
328
+ if (context.getRuntime().isDebug()) {
329
+ System.out.println("Error SQL: " + query);
330
+ }
331
+ throw sqe;
332
+ } finally {
333
+ close(stmt);
334
+ }
335
+ }
336
+ });
337
+ }
338
+
339
+ @JRubyMethod(name = "execute_update", required = 1)
340
+ public IRubyObject execute_update(final ThreadContext context, final IRubyObject sql)
341
+ throws SQLException {
342
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
343
+ public Object call(Connection c) throws SQLException {
344
+ Statement stmt = null;
345
+ String update = rubyApi.convertToRubyString(sql).getUnicodeValue();
346
+ try {
347
+ stmt = c.createStatement();
348
+ return context.getRuntime().newFixnum((long)stmt.executeUpdate(update));
349
+ } catch (SQLException sqe) {
350
+ if (context.getRuntime().isDebug()) {
351
+ System.out.println("Error SQL: " + update);
352
+ }
353
+ throw sqe;
354
+ } finally {
355
+ close(stmt);
356
+ }
357
+ }
358
+ });
359
+ }
360
+
361
+ @JRubyMethod(name = "indexes")
362
+ public IRubyObject indexes(ThreadContext context, IRubyObject tableName, IRubyObject name, IRubyObject schemaName) {
363
+ return indexes(context, toStringOrNull(tableName), toStringOrNull(name), toStringOrNull(schemaName));
364
+ }
365
+
366
+ private static final int INDEX_TABLE_NAME = 3;
367
+ private static final int INDEX_NON_UNIQUE = 4;
368
+ private static final int INDEX_NAME = 6;
369
+ private static final int INDEX_COLUMN_NAME = 9;
370
+
371
+ /**
372
+ * Default JDBC introspection for index metadata on the JdbcConnection.
373
+ *
374
+ * JDBC index metadata is denormalized (multiple rows may be returned for
375
+ * one index, one row per column in the index), so a simple block-based
376
+ * filter like that used for tables doesn't really work here. Callers
377
+ * should filter the return from this method instead.
378
+ */
379
+ protected IRubyObject indexes(final ThreadContext context, final String tableNameArg, final String name, final String schemaNameArg) {
380
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
381
+ public Object call(Connection c) throws SQLException {
382
+ Ruby runtime = context.getRuntime();
383
+ DatabaseMetaData metadata = c.getMetaData();
384
+ String tableName = caseConvertIdentifierForJdbc(metadata, tableNameArg);
385
+ String schemaName = caseConvertIdentifierForJdbc(metadata, schemaNameArg);
386
+
387
+ ResultSet resultSet = null;
388
+ List indexes = new ArrayList();
389
+ try {
390
+ resultSet = metadata.getIndexInfo(null, schemaName, tableName, false, false);
391
+ List primaryKeys = primaryKeys(context, tableName);
392
+ String currentIndex = null;
393
+ RubyModule indexDefinitionClass = getConnectionAdapters(runtime).getClass("IndexDefinition");
394
+
395
+ while (resultSet.next()) {
396
+ String indexName = resultSet.getString(INDEX_NAME);
397
+
398
+ if (indexName == null) continue;
399
+
400
+ indexName = caseConvertIdentifierForRails(metadata, indexName);
401
+
402
+ RubyString columnName = RubyString.newUnicodeString(runtime, caseConvertIdentifierForRails(metadata, resultSet.getString(INDEX_COLUMN_NAME)));
403
+
404
+ if (primaryKeys.contains(columnName)) continue;
405
+
406
+ // We are working on a new index
407
+ if (!indexName.equals(currentIndex)) {
408
+ currentIndex = indexName;
409
+
410
+ tableName = caseConvertIdentifierForRails(metadata, resultSet.getString(INDEX_TABLE_NAME));
411
+ boolean nonUnique = resultSet.getBoolean(INDEX_NON_UNIQUE);
412
+
413
+ IRubyObject indexDefinition = indexDefinitionClass.callMethod(context, "new",
414
+ new IRubyObject[] {
415
+ RubyString.newUnicodeString(runtime, tableName),
416
+ RubyString.newUnicodeString(runtime, indexName),
417
+ runtime.newBoolean(!nonUnique),
418
+ runtime.newArray()
419
+ });
420
+
421
+ // empty list for column names, we'll add to that in just a bit
422
+ indexes.add(indexDefinition);
423
+ }
424
+
425
+ // One or more columns can be associated with an index
426
+ IRubyObject lastIndex = (IRubyObject) indexes.get(indexes.size() - 1);
427
+
428
+ if (lastIndex != null) {
429
+ lastIndex.callMethod(context, "columns").callMethod(context, "<<", columnName);
430
+ }
431
+ }
432
+
433
+ return runtime.newArray(indexes);
434
+ } finally {
435
+ close(resultSet);
436
+ }
437
+ }
438
+ });
439
+ }
440
+
441
+ @JRubyMethod(name = "insert?", required = 1, meta = true, frame = false)
442
+ public static IRubyObject insert_p(ThreadContext context, IRubyObject recv, IRubyObject _sql) {
443
+ ByteList sql = rubyApi.convertToRubyString(_sql).getByteList();
444
+
445
+ return context.getRuntime().newBoolean(startsWithNoCaseCmp(sql, INSERT));
446
+ }
447
+
448
+ /*
449
+ * sql, values, types, name = nil, pk = nil, id_value = nil, sequence_name = nil
450
+ */
451
+ @JRubyMethod(name = "insert_bind", required = 3, rest = true)
452
+ public IRubyObject insert_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException {
453
+ final Ruby runtime = context.getRuntime();
454
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
455
+ public Object call(Connection c) throws SQLException {
456
+ PreparedStatement ps = null;
457
+ try {
458
+ ps = c.prepareStatement(rubyApi.convertToRubyString(args[0]).toString(), Statement.RETURN_GENERATED_KEYS);
459
+ setValuesOnPS(ps, context, args[1], args[2]);
460
+ ps.executeUpdate();
461
+ return unmarshal_id_result(runtime, ps.getGeneratedKeys());
462
+ } finally {
463
+ close(ps);
464
+ }
465
+ }
466
+ });
467
+ }
468
+
469
+ @JRubyMethod(name = "native_database_types", frame = false)
470
+ public IRubyObject native_database_types() {
471
+ return getInstanceVariable("@native_database_types");
472
+ }
473
+
474
+
475
+ @JRubyMethod(name = "primary_keys", required = 1)
476
+ public IRubyObject primary_keys(ThreadContext context, IRubyObject tableName) throws SQLException {
477
+ return context.getRuntime().newArray(primaryKeys(context, tableName.toString()));
478
+ }
479
+
480
+ protected List primaryKeys(final ThreadContext context, final String tableNameArg) {
481
+ return (List) withConnectionAndRetry(context, new SQLBlock() {
482
+ public Object call(Connection c) throws SQLException {
483
+ Ruby runtime = context.getRuntime();
484
+ DatabaseMetaData metadata = c.getMetaData();
485
+ String tableName = caseConvertIdentifierForJdbc(metadata, tableNameArg);
486
+ ResultSet resultSet = null;
487
+ List keyNames = new ArrayList();
488
+ try {
489
+ resultSet = metadata.getPrimaryKeys(null, null, tableName);
490
+
491
+ while (resultSet.next()) {
492
+ keyNames.add(RubyString.newUnicodeString(runtime,
493
+ caseConvertIdentifierForRails(metadata, resultSet.getString(4))));
494
+ }
495
+ } finally {
496
+ close(resultSet);
497
+ }
498
+
499
+ return keyNames;
500
+ }
501
+ });
502
+ }
503
+
504
+ @JRubyMethod(name = "reconnect!")
505
+ public IRubyObject reconnect() {
506
+ return setConnection(getConnectionFactory().newConnection());
507
+ }
508
+
509
+
510
+ @JRubyMethod(name = "rollback")
511
+ public IRubyObject rollback(ThreadContext context) throws SQLException {
512
+ final Ruby runtime = context.getRuntime();
513
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
514
+ public Object call(Connection c) throws SQLException {
515
+ Connection connection = getConnection(true);
516
+
517
+ if (!connection.getAutoCommit()) {
518
+ try {
519
+ connection.rollback();
520
+ } finally {
521
+ connection.setAutoCommit(true);
522
+ }
523
+ }
524
+
525
+ return runtime.getNil();
526
+ }
527
+ });
528
+ }
529
+
530
+ @JRubyMethod(name = "select?", required = 1, meta = true, frame = false)
531
+ public static IRubyObject select_p(ThreadContext context, IRubyObject recv, IRubyObject _sql) {
532
+ ByteList sql = rubyApi.convertToRubyString(_sql).getByteList();
533
+
534
+ return context.getRuntime().newBoolean(startsWithNoCaseCmp(sql, SELECT) ||
535
+ startsWithNoCaseCmp(sql, SHOW) || startsWithNoCaseCmp(sql, CALL));
536
+ }
537
+
538
+ @JRubyMethod(name = "set_native_database_types")
539
+ public IRubyObject set_native_database_types(ThreadContext context) throws SQLException, IOException {
540
+ Ruby runtime = context.getRuntime();
541
+ DatabaseMetaData metadata = getConnection(true).getMetaData();
542
+ IRubyObject types = unmarshalResult(context, metadata, metadata.getTypeInfo(), true);
543
+ IRubyObject typeConverter = getConnectionAdapters(runtime).getConstant("JdbcTypeConverter");
544
+ IRubyObject value = rubyApi.callMethod(rubyApi.callMethod(typeConverter, "new", types), "choose_best_types");
545
+ setInstanceVariable("@native_types", value);
546
+
547
+ return runtime.getNil();
548
+ }
549
+
550
+ @JRubyMethod(name = "tables")
551
+ public IRubyObject tables(ThreadContext context) {
552
+ return tables(context, null, null, null, TABLE_TYPE);
553
+ }
554
+
555
+ @JRubyMethod(name = "tables")
556
+ public IRubyObject tables(ThreadContext context, IRubyObject catalog) {
557
+ return tables(context, toStringOrNull(catalog), null, null, TABLE_TYPE);
558
+ }
559
+
560
+ @JRubyMethod(name = "tables")
561
+ public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern) {
562
+ return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), null, TABLE_TYPE);
563
+ }
564
+
565
+ @JRubyMethod(name = "tables")
566
+ public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern, IRubyObject tablePattern) {
567
+ return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), toStringOrNull(tablePattern), TABLE_TYPE);
568
+ }
569
+
570
+ @JRubyMethod(name = "tables", required = 4, rest = true)
571
+ public IRubyObject tables(ThreadContext context, IRubyObject[] args) {
572
+ return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), getTypes(args[3]));
573
+ }
574
+
575
+ protected IRubyObject tables(ThreadContext context, String catalog, String schemaPattern, String tablePattern, String[] types) {
576
+ return (IRubyObject) withConnectionAndRetry(context, tableLookupBlock(context.getRuntime(), catalog, schemaPattern, tablePattern, types, false));
577
+ }
578
+
579
+ /*
580
+ * sql, values, types, name = nil
581
+ */
582
+ @JRubyMethod(name = "update_bind", required = 3, rest = true)
583
+ public IRubyObject update_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException {
584
+ final Ruby runtime = context.getRuntime();
585
+ Arity.checkArgumentCount(runtime, args, 3, 4);
586
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
587
+ public Object call(Connection c) throws SQLException {
588
+ PreparedStatement ps = null;
589
+ try {
590
+ ps = c.prepareStatement(rubyApi.convertToRubyString(args[0]).toString());
591
+ setValuesOnPS(ps, context, args[1], args[2]);
592
+ ps.executeUpdate();
593
+ } finally {
594
+ close(ps);
595
+ }
596
+ return runtime.getNil();
597
+ }
598
+ });
599
+ }
600
+
601
+ @JRubyMethod(name = "with_connection_retry_guard", frame = true)
602
+ public IRubyObject with_connection_retry_guard(final ThreadContext context, final Block block) {
603
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
604
+ public Object call(Connection c) throws SQLException {
605
+ return block.call(context, new IRubyObject[] { wrappedConnection(c) });
606
+ }
607
+ });
608
+ }
609
+
610
+ /*
611
+ * (is binary?, colname, tablename, primary key, id, value)
612
+ */
613
+ @JRubyMethod(name = "write_large_object", required = 6)
614
+ public IRubyObject write_large_object(ThreadContext context, final IRubyObject[] args)
615
+ throws SQLException, IOException {
616
+ final Ruby runtime = context.getRuntime();
617
+ return (IRubyObject) withConnectionAndRetry(context, new SQLBlock() {
618
+ public Object call(Connection c) throws SQLException {
619
+ String sql = "UPDATE " + rubyApi.convertToRubyString(args[2])
620
+ + " SET " + rubyApi.convertToRubyString(args[1])
621
+ + " = ? WHERE " + rubyApi.convertToRubyString(args[3])
622
+ + "=" + rubyApi.convertToRubyString(args[4]);
623
+ PreparedStatement ps = null;
624
+ try {
625
+ ps = c.prepareStatement(sql);
626
+ if (args[0].isTrue()) { // binary
627
+ ByteList outp = rubyApi.convertToRubyString(args[5]).getByteList();
628
+ ps.setBinaryStream(1, new ByteArrayInputStream(outp.bytes,
629
+ outp.begin, outp.realSize), outp.realSize);
630
+ } else { // clob
631
+ String ss = rubyApi.convertToRubyString(args[5]).getUnicodeValue();
632
+ ps.setCharacterStream(1, new StringReader(ss), ss.length());
633
+ }
634
+ ps.executeUpdate();
635
+ } finally {
636
+ close(ps);
637
+ }
638
+ return runtime.getNil();
639
+ }
640
+ });
641
+ }
642
+
643
+ /**
644
+ * Convert an identifier coming back from the database to a case which Rails is expecting.
645
+ *
646
+ * Assumption: Rails identifiers will be quoted for mixed or will stay mixed
647
+ * as identifier names in Rails itself. Otherwise, they expect identifiers to
648
+ * be lower-case. Databases which store identifiers uppercase should be made
649
+ * lower-case.
650
+ *
651
+ * Assumption 2: It is always safe to convert all upper case names since it appears that
652
+ * some adapters do not report StoresUpper/Lower/Mixed correctly (am I right postgres/mysql?).
653
+ */
654
+ public static String caseConvertIdentifierForRails(DatabaseMetaData metadata, String value)
655
+ throws SQLException {
656
+ if (value == null) return null;
657
+
658
+ return metadata.storesUpperCaseIdentifiers() ? value.toLowerCase() : value;
659
+ }
660
+
661
+ /**
662
+ * Convert an identifier destined for a method which cares about the databases internal
663
+ * storage case. Methods like DatabaseMetaData.getPrimaryKeys() needs the table name to match
664
+ * the internal storage name. Arbtrary queries and the like DO NOT need to do this.
665
+ */
666
+ public static String caseConvertIdentifierForJdbc(DatabaseMetaData metadata, String value)
667
+ throws SQLException {
668
+ if (value == null) return null;
669
+ boolean isPostgres = metadata.getDatabaseProductName().equals("PostgreSQL");
670
+
671
+ if (metadata.storesUpperCaseIdentifiers()) {
672
+ return value.toUpperCase();
673
+ } else if (metadata.storesLowerCaseIdentifiers() && ! isPostgres) {
674
+ return value.toLowerCase();
675
+ }
676
+
677
+ return value;
678
+ }
679
+
680
+ // helpers
681
+ protected static void close(Connection connection) {
682
+ if (connection != null) {
683
+ try {
684
+ connection.close();
685
+ } catch(Exception e) {}
686
+ }
687
+ }
688
+
689
+ public static void close(ResultSet resultSet) {
690
+ if (resultSet != null) {
691
+ try {
692
+ resultSet.close();
693
+ } catch(Exception e) {}
694
+ }
695
+ }
696
+
697
+ public static void close(Statement statement) {
698
+ if (statement != null) {
699
+ try {
700
+ statement.close();
701
+ } catch(Exception e) {}
702
+ }
703
+ }
704
+
705
+ protected IRubyObject config_value(ThreadContext context, String key) {
706
+ IRubyObject config_hash = getInstanceVariable("@config");
707
+
708
+ return config_hash.callMethod(context, "[]", context.getRuntime().newSymbol(key));
709
+ }
710
+
711
+ private static String toStringOrNull(IRubyObject arg) {
712
+ return arg.isNil() ? null : arg.toString();
713
+ }
714
+
715
+ protected IRubyObject doubleToRuby(Ruby runtime, ResultSet resultSet, double doubleValue)
716
+ throws SQLException, IOException {
717
+ if (doubleValue == 0 && resultSet.wasNull()) return runtime.getNil();
718
+ return runtime.newFloat(doubleValue);
719
+ }
720
+
721
+ protected Connection getConnection() {
722
+ return getConnection(false);
723
+ }
724
+
725
+ protected Connection getConnection(boolean error) {
726
+ Connection conn = (Connection) dataGetStruct();
727
+ if(error && conn == null) {
728
+ RubyClass err = getRuntime().getModule("ActiveRecord").getClass("ConnectionNotEstablished");
729
+ throw new RaiseException(getRuntime(), err, "no connection available", false);
730
+ }
731
+ return conn;
732
+ }
733
+
734
+ protected IRubyObject getAdapter(ThreadContext context) {
735
+ return callMethod(context, "adapter");
736
+ }
737
+
738
+ protected IRubyObject getJdbcColumnClass(ThreadContext context) {
739
+ return getAdapter(context).callMethod(context, "jdbc_column_class");
740
+ }
741
+
742
+ protected JdbcConnectionFactory getConnectionFactory() throws RaiseException {
743
+ IRubyObject connection_factory = getInstanceVariable("@connection_factory");
744
+ JdbcConnectionFactory factory = null;
745
+ try {
746
+ factory = (JdbcConnectionFactory) JavaEmbedUtils.rubyToJava(
747
+ connection_factory.getRuntime(), connection_factory, JdbcConnectionFactory.class);
748
+ } catch (Exception e) {
749
+ factory = null;
750
+ }
751
+ if (factory == null) {
752
+ throw getRuntime().newRuntimeError("@connection_factory not set properly");
753
+ }
754
+ return factory;
755
+ }
756
+
757
+ private static String[] getTypes(IRubyObject typeArg) {
758
+ if (!(typeArg instanceof RubyArray)) return new String[] { typeArg.toString() };
759
+
760
+ IRubyObject[] arr = rubyApi.convertToJavaArray(typeArg);
761
+ String[] types = new String[arr.length];
762
+ for (int i = 0; i < types.length; i++) {
763
+ types[i] = arr[i].toString();
764
+ }
765
+
766
+ return types;
767
+ }
768
+
769
+ private static int getTypeValueFor(Ruby runtime, IRubyObject type) throws SQLException {
770
+ // How could this ever yield anything useful?
771
+ if (!(type instanceof RubySymbol)) type = rubyApi.callMethod(type, "class");
772
+
773
+ // Assumption; If this is a symbol then it will be backed by an interned string. (enebo)
774
+ String internedValue = type.asJavaString();
775
+
776
+ if(internedValue == "string") {
777
+ return Types.VARCHAR;
778
+ } else if(internedValue == "text") {
779
+ return Types.CLOB;
780
+ } else if(internedValue == "integer") {
781
+ return Types.INTEGER;
782
+ } else if(internedValue == "decimal") {
783
+ return Types.DECIMAL;
784
+ } else if(internedValue == "float") {
785
+ return Types.FLOAT;
786
+ } else if(internedValue == "datetime") {
787
+ return Types.TIMESTAMP;
788
+ } else if(internedValue == "timestamp") {
789
+ return Types.TIMESTAMP;
790
+ } else if(internedValue == "time") {
791
+ return Types.TIME;
792
+ } else if(internedValue == "date") {
793
+ return Types.DATE;
794
+ } else if(internedValue == "binary") {
795
+ return Types.BLOB;
796
+ } else if(internedValue == "boolean") {
797
+ return Types.BOOLEAN;
798
+ } else {
799
+ return -1;
800
+ }
801
+ }
802
+
803
+ private boolean isConnectionBroken(ThreadContext context, Connection c) {
804
+ try {
805
+ IRubyObject alive = config_value(context, "connection_alive_sql");
806
+ if (select_p(context, this, alive).isTrue()) {
807
+ String connectionSQL = rubyApi.convertToRubyString(alive).toString();
808
+ Statement s = c.createStatement();
809
+ try {
810
+ s.execute(connectionSQL);
811
+ } finally {
812
+ close(s);
813
+ }
814
+ return false;
815
+ } else {
816
+ return !c.isClosed();
817
+ }
818
+ } catch (Exception sx) {
819
+ return true;
820
+ }
821
+ }
822
+
823
+ protected IRubyObject integerToRuby(Ruby runtime, ResultSet resultSet, long longValue)
824
+ throws SQLException {
825
+ if (longValue == 0 && resultSet.wasNull()) return runtime.getNil();
826
+
827
+ return runtime.newFixnum(longValue);
828
+ }
829
+
830
+ protected IRubyObject bigIntegerToRuby(Ruby runtime, ResultSet resultSet, String bigint) throws SQLException {
831
+ if (bigint == null && resultSet.wasNull()) return runtime.getNil();
832
+
833
+ return RubyBignum.bignorm(runtime, new BigInteger(bigint));
834
+ }
835
+
836
+ protected IRubyObject jdbcToRuby(Ruby runtime, int column, int type, ResultSet resultSet)
837
+ throws SQLException {
838
+ try {
839
+ switch (type) {
840
+ case Types.BINARY:
841
+ case Types.BLOB:
842
+ case Types.LONGVARBINARY:
843
+ case Types.VARBINARY:
844
+ case Types.LONGVARCHAR:
845
+ return streamToRuby(runtime, resultSet, resultSet.getBinaryStream(column));
846
+ case Types.CLOB:
847
+ return readerToRuby(runtime, resultSet, resultSet.getCharacterStream(column));
848
+ case Types.TIMESTAMP:
849
+ return timestampToRuby(runtime, resultSet, resultSet.getTimestamp(column));
850
+ case Types.INTEGER:
851
+ case Types.SMALLINT:
852
+ case Types.TINYINT:
853
+ return integerToRuby(runtime, resultSet, resultSet.getLong(column));
854
+ case Types.REAL:
855
+ return doubleToRuby(runtime, resultSet, resultSet.getDouble(column));
856
+ case Types.BIGINT:
857
+ return bigIntegerToRuby(runtime, resultSet, resultSet.getString(column));
858
+ default:
859
+ return stringToRuby(runtime, resultSet, resultSet.getString(column));
860
+ }
861
+ } catch (IOException ioe) {
862
+ throw (SQLException) new SQLException(ioe.getMessage()).initCause(ioe);
863
+ }
864
+ }
865
+
866
+ protected void populateFromResultSet(ThreadContext context, Ruby runtime, List results,
867
+ ResultSet resultSet, ColumnData[] columns) throws SQLException {
868
+ int columnCount = columns.length;
869
+
870
+ while (resultSet.next()) {
871
+ RubyHash row = RubyHash.newHash(runtime);
872
+
873
+ for (int i = 0; i < columnCount; i++) {
874
+ row.op_aset(context, columns[i].name, jdbcToRuby(runtime, columns[i].index, columns[i].type, resultSet));
875
+ }
876
+
877
+ results.add(row);
878
+ }
879
+ }
880
+
881
+
882
+ protected IRubyObject readerToRuby(Ruby runtime, ResultSet resultSet, Reader reader)
883
+ throws SQLException, IOException {
884
+ if (reader == null && resultSet.wasNull()) return runtime.getNil();
885
+
886
+ StringBuffer str = new StringBuffer(2048);
887
+ try {
888
+ char[] buf = new char[2048];
889
+
890
+ for (int n = reader.read(buf); n != -1; n = reader.read(buf)) {
891
+ str.append(buf, 0, n);
892
+ }
893
+ } finally {
894
+ reader.close();
895
+ }
896
+
897
+ return RubyString.newUnicodeString(runtime, str.toString());
898
+ }
899
+
900
+ private IRubyObject setConnection(Connection c) {
901
+ close(getConnection()); // Close previously open connection if there is one
902
+
903
+ IRubyObject rubyconn = c != null ? wrappedConnection(c) : getRuntime().getNil();
904
+ setInstanceVariable("@connection", rubyconn);
905
+ dataWrapStruct(c);
906
+ return this;
907
+ }
908
+
909
+ private final static DateFormat FORMAT = new SimpleDateFormat("%y-%M-%d %H:%m:%s");
910
+
911
+ private static void setValue(PreparedStatement ps, int index, ThreadContext context,
912
+ IRubyObject value, IRubyObject type) throws SQLException {
913
+ final int tp = getTypeValueFor(context.getRuntime(), type);
914
+ if(value.isNil()) {
915
+ ps.setNull(index, tp);
916
+ return;
917
+ }
918
+
919
+ switch(tp) {
920
+ case Types.VARCHAR:
921
+ case Types.CLOB:
922
+ ps.setString(index, RubyString.objAsString(context, value).toString());
923
+ break;
924
+ case Types.INTEGER:
925
+ ps.setLong(index, RubyNumeric.fix2long(value));
926
+ break;
927
+ case Types.FLOAT:
928
+ ps.setDouble(index, ((RubyNumeric)value).getDoubleValue());
929
+ break;
930
+ case Types.TIMESTAMP:
931
+ case Types.TIME:
932
+ case Types.DATE:
933
+ if(!(value instanceof RubyTime)) {
934
+ try {
935
+ Date dd = FORMAT.parse(RubyString.objAsString(context, value).toString());
936
+ ps.setTimestamp(index, new java.sql.Timestamp(dd.getTime()), Calendar.getInstance());
937
+ } catch(Exception e) {
938
+ ps.setString(index, RubyString.objAsString(context, value).toString());
939
+ }
940
+ } else {
941
+ RubyTime rubyTime = (RubyTime) value;
942
+ java.util.Date date = rubyTime.getJavaDate();
943
+ long millis = date.getTime();
944
+ long micros = rubyTime.microseconds() - millis / 1000;
945
+ java.sql.Timestamp ts = new java.sql.Timestamp(millis);
946
+ java.util.Calendar cal = Calendar.getInstance();
947
+ cal.setTime(date);
948
+ ts.setNanos((int)(micros * 1000));
949
+ ps.setTimestamp(index, ts, cal);
950
+ }
951
+ break;
952
+ case Types.BOOLEAN:
953
+ ps.setBoolean(index, value.isTrue());
954
+ break;
955
+ default: throw new RuntimeException("type " + type + " not supported in _bind yet");
956
+ }
957
+ }
958
+
959
+ private static void setValuesOnPS(PreparedStatement ps, ThreadContext context,
960
+ IRubyObject valuesArg, IRubyObject typesArg) throws SQLException {
961
+ RubyArray values = (RubyArray) valuesArg;
962
+ RubyArray types = (RubyArray) typesArg;
963
+
964
+ for(int i=0, j=values.getLength(); i<j; i++) {
965
+ setValue(ps, i+1, context, values.eltInternal(i), types.eltInternal(i));
966
+ }
967
+ }
968
+
969
+ protected IRubyObject streamToRuby(Ruby runtime, ResultSet resultSet, InputStream is)
970
+ throws SQLException, IOException {
971
+ if (is == null && resultSet.wasNull()) return runtime.getNil();
972
+
973
+ ByteList str = new ByteList(2048);
974
+ try {
975
+ byte[] buf = new byte[2048];
976
+
977
+ for (int n = is.read(buf); n != -1; n = is.read(buf)) {
978
+ str.append(buf, 0, n);
979
+ }
980
+ } finally {
981
+ is.close();
982
+ }
983
+
984
+ return runtime.newString(str);
985
+ }
986
+
987
+ protected IRubyObject stringToRuby(Ruby runtime, ResultSet resultSet, String string)
988
+ throws SQLException, IOException {
989
+ if (string == null && resultSet.wasNull()) return runtime.getNil();
990
+
991
+ return RubyString.newUnicodeString(runtime, string);
992
+ }
993
+
994
+ private static final int TABLE_NAME = 3;
995
+
996
+ protected SQLBlock tableLookupBlock(final Ruby runtime,
997
+ final String catalog, final String schemapat,
998
+ final String tablepat, final String[] types, final boolean downCase) {
999
+ return new SQLBlock() {
1000
+ public Object call(Connection c) throws SQLException {
1001
+ ResultSet rs = null;
1002
+ try {
1003
+ DatabaseMetaData metadata = c.getMetaData();
1004
+ String clzName = metadata.getClass().getName().toLowerCase();
1005
+ boolean isOracle = clzName.indexOf("oracle") != -1 || clzName.indexOf("oci") != -1;
1006
+ boolean isDerby = clzName.indexOf("derby") != 1;
1007
+
1008
+ String realschema = schemapat;
1009
+ String realtablepat = tablepat;
1010
+
1011
+ if (isDerby && realschema != null && realschema.equals("")) realschema = null; // Derby doesn't like empty-string schema name
1012
+ if (realtablepat != null) realtablepat = caseConvertIdentifierForJdbc(metadata, realtablepat);
1013
+ if (realschema != null) realschema = caseConvertIdentifierForJdbc(metadata, realschema);
1014
+
1015
+ rs = metadata.getTables(catalog, realschema, realtablepat, types);
1016
+ List arr = new ArrayList();
1017
+ while (rs.next()) {
1018
+ String name;
1019
+
1020
+ if (downCase) {
1021
+ name = rs.getString(TABLE_NAME).toLowerCase();
1022
+ } else {
1023
+ name = caseConvertIdentifierForRails(metadata, rs.getString(TABLE_NAME));
1024
+ }
1025
+ // Handle stupid Oracle 10g RecycleBin feature
1026
+ if (!isOracle || !name.startsWith("bin$")) {
1027
+ arr.add(RubyString.newUnicodeString(runtime, name));
1028
+ }
1029
+ }
1030
+ return runtime.newArray(arr);
1031
+ } finally {
1032
+ close(rs);
1033
+ }
1034
+ }
1035
+ };
1036
+ }
1037
+
1038
+ protected IRubyObject timestampToRuby(Ruby runtime, ResultSet resultSet, Timestamp time)
1039
+ throws SQLException {
1040
+ if (time == null && resultSet.wasNull()) return runtime.getNil();
1041
+
1042
+ String str = time.toString();
1043
+ if (str.endsWith(" 00:00:00.0")) {
1044
+ str = str.substring(0, str.length() - (" 00:00:00.0".length()));
1045
+ }
1046
+ if (str.endsWith(".0")) {
1047
+ str = str.substring(0, str.length() - (".0".length()));
1048
+ }
1049
+
1050
+ return RubyString.newUnicodeString(runtime, str);
1051
+ }
1052
+
1053
+ protected static final int COLUMN_NAME = 4;
1054
+ protected static final int DATA_TYPE = 5;
1055
+ protected static final int TYPE_NAME = 6;
1056
+ protected static final int COLUMN_SIZE = 7;
1057
+ protected static final int DECIMAL_DIGITS = 9;
1058
+ protected static final int COLUMN_DEF = 13;
1059
+ protected static final int IS_NULLABLE = 18;
1060
+
1061
+ protected int intFromResultSet(ResultSet resultSet, int column) throws SQLException {
1062
+ int precision = resultSet.getInt(column);
1063
+
1064
+ return precision == 0 && resultSet.wasNull() ? -1 : precision;
1065
+ }
1066
+
1067
+ /**
1068
+ * Create a string which represents a sql type usable by Rails from the resultSet column
1069
+ * metadata object.
1070
+ */
1071
+ protected String typeFromResultSet(ResultSet resultSet) throws SQLException {
1072
+ int precision = intFromResultSet(resultSet, COLUMN_SIZE);
1073
+ int scale = intFromResultSet(resultSet, DECIMAL_DIGITS);
1074
+
1075
+ String type = resultSet.getString(TYPE_NAME);
1076
+ if (precision > 0) {
1077
+ type += "(" + precision;
1078
+ if(scale > 0) type += "," + scale;
1079
+ type += ")";
1080
+ }
1081
+
1082
+ return type;
1083
+ }
1084
+
1085
+ private IRubyObject defaultValueFromResultSet(Ruby runtime, ResultSet resultSet)
1086
+ throws SQLException {
1087
+ String defaultValue = resultSet.getString(COLUMN_DEF);
1088
+
1089
+ return defaultValue == null ? runtime.getNil() : RubyString.newUnicodeString(runtime, defaultValue);
1090
+ }
1091
+
1092
+ private IRubyObject unmarshal_columns(ThreadContext context, DatabaseMetaData metadata,
1093
+ ResultSet rs, ResultSet pkeys) throws SQLException {
1094
+ try {
1095
+ Ruby runtime = context.getRuntime();
1096
+ List columns = new ArrayList();
1097
+ List pkeyNames = new ArrayList();
1098
+ String clzName = metadata.getClass().getName().toLowerCase();
1099
+
1100
+ RubyHash types = (RubyHash) native_database_types();
1101
+ IRubyObject jdbcCol = getJdbcColumnClass(context);
1102
+
1103
+ while (pkeys.next()) {
1104
+ pkeyNames.add(pkeys.getString(COLUMN_NAME));
1105
+ }
1106
+
1107
+ while (rs.next()) {
1108
+ String colName = rs.getString(COLUMN_NAME);
1109
+ IRubyObject column = jdbcCol.callMethod(context, "new",
1110
+ new IRubyObject[] {
1111
+ getInstanceVariable("@config"),
1112
+ RubyString.newUnicodeString(runtime,
1113
+ caseConvertIdentifierForRails(metadata, colName)),
1114
+ defaultValueFromResultSet(runtime, rs),
1115
+ RubyString.newUnicodeString(runtime, typeFromResultSet(rs)),
1116
+ runtime.newBoolean(!rs.getString(IS_NULLABLE).trim().equals("NO"))
1117
+ });
1118
+ columns.add(column);
1119
+
1120
+ if (pkeyNames.contains(colName)) {
1121
+ column.callMethod(context, "primary=", runtime.getTrue());
1122
+ }
1123
+ }
1124
+ return runtime.newArray(columns);
1125
+ } finally {
1126
+ close(rs);
1127
+ }
1128
+ }
1129
+
1130
+
1131
+ public static IRubyObject unmarshal_id_result(Ruby runtime, ResultSet rs) throws SQLException {
1132
+ try {
1133
+ if (rs.next() && rs.getMetaData().getColumnCount() > 0) {
1134
+ return runtime.newFixnum(rs.getLong(1));
1135
+ }
1136
+ return runtime.getNil();
1137
+ } finally {
1138
+ close(rs);
1139
+ }
1140
+ }
1141
+
1142
+ protected IRubyObject unmarshalResults(ThreadContext context, DatabaseMetaData metadata,
1143
+ Statement stmt, boolean downCase) throws SQLException {
1144
+ Ruby runtime = context.getRuntime();
1145
+ List<IRubyObject> sets = new ArrayList<IRubyObject>();
1146
+
1147
+ while (true) {
1148
+ sets.add(unmarshalResult(context, metadata, stmt.getResultSet(), downCase));
1149
+ if (!stmt.getMoreResults()) {
1150
+ break;
1151
+ }
1152
+ }
1153
+
1154
+ if (sets.size() > 1) {
1155
+ return runtime.newArray(sets);
1156
+ } else {
1157
+ return sets.get(0);
1158
+ }
1159
+ }
1160
+
1161
+ /**
1162
+ * Converts a jdbc resultset into an array (rows) of hashes (row) that AR expects.
1163
+ *
1164
+ * @param downCase should column names only be in lower case?
1165
+ */
1166
+ protected IRubyObject unmarshalResult(ThreadContext context, DatabaseMetaData metadata,
1167
+ ResultSet resultSet, boolean downCase) throws SQLException {
1168
+ Ruby runtime = context.getRuntime();
1169
+ List results = new ArrayList();
1170
+
1171
+ try {
1172
+ ColumnData[] columns = ColumnData.setup(runtime, metadata, resultSet.getMetaData(), downCase);
1173
+
1174
+ populateFromResultSet(context, runtime, results, resultSet, columns);
1175
+ } finally {
1176
+ close(resultSet);
1177
+ }
1178
+
1179
+ return runtime.newArray(results);
1180
+ }
1181
+
1182
+ protected Object withConnectionAndRetry(ThreadContext context, SQLBlock block) {
1183
+ int tries = 1;
1184
+ int i = 0;
1185
+ Throwable toWrap = null;
1186
+ boolean autoCommit = false;
1187
+ while (i < tries) {
1188
+ Connection c = getConnection(true);
1189
+ try {
1190
+ autoCommit = c.getAutoCommit();
1191
+ return block.call(c);
1192
+ } catch (Exception e) {
1193
+ toWrap = e;
1194
+ while (toWrap.getCause() != null && toWrap.getCause() != toWrap) {
1195
+ toWrap = toWrap.getCause();
1196
+ }
1197
+
1198
+ if (context.getRuntime().isDebug()) {
1199
+ toWrap.printStackTrace(System.out);
1200
+ }
1201
+
1202
+ i++;
1203
+ if (autoCommit) {
1204
+ if (i == 1) {
1205
+ tries = (int) rubyApi.convertToRubyInteger(config_value(context, "retry_count")).getLongValue();
1206
+ if (tries <= 0) {
1207
+ tries = 1;
1208
+ }
1209
+ }
1210
+ if (isConnectionBroken(context, c)) {
1211
+ reconnect();
1212
+ } else {
1213
+ throw wrap(context, toWrap);
1214
+ }
1215
+ }
1216
+ }
1217
+ }
1218
+ throw wrap(context, toWrap);
1219
+ }
1220
+
1221
+ protected RuntimeException wrap(ThreadContext context, Throwable exception) {
1222
+ Ruby runtime = context.getRuntime();
1223
+ RaiseException arError = new RaiseException(runtime, runtime.getModule("ActiveRecord").getClass("JDBCError"),
1224
+ exception.getMessage(), true);
1225
+ arError.initCause(exception);
1226
+ if (exception instanceof SQLException) {
1227
+ RuntimeHelpers.invoke(context, arError.getException(),
1228
+ "errno=", runtime.newFixnum(((SQLException) exception).getErrorCode()));
1229
+ RuntimeHelpers.invoke(context, arError.getException(),
1230
+ "sql_exception=", JavaEmbedUtils.javaToRuby(runtime, exception));
1231
+ }
1232
+ return (RuntimeException) arError;
1233
+ }
1234
+
1235
+ private IRubyObject wrappedConnection(Connection c) {
1236
+ return Java.java_to_ruby(this, JavaObject.wrap(getRuntime(), c), Block.NULL_BLOCK);
1237
+ }
1238
+
1239
+ /**
1240
+ * Some databases support schemas and others do not.
1241
+ * For ones which do this method should return true, aiding in decisions regarding schema vs database determination.
1242
+ */
1243
+ protected boolean databaseSupportsSchemas() {
1244
+ return false;
1245
+ }
1246
+
1247
+ private static int whitespace(int start, ByteList bl) {
1248
+ int end = bl.begin + bl.realSize;
1249
+
1250
+ for (int i = start; i < end; i++) {
1251
+ if (!Character.isWhitespace(bl.bytes[i])) return i;
1252
+ }
1253
+
1254
+ return end;
1255
+ }
1256
+
1257
+ private static byte[] CALL = new byte[]{'c', 'a', 'l', 'l'};
1258
+ private static byte[] INSERT = new byte[] {'i', 'n', 's', 'e', 'r', 't'};
1259
+ private static byte[] SELECT = new byte[] {'s', 'e', 'l', 'e', 'c', 't'};
1260
+ private static byte[] SHOW = new byte[] {'s', 'h', 'o', 'w'};
1261
+
1262
+ private static boolean startsWithNoCaseCmp(ByteList bytelist, byte[] compare) {
1263
+ int p = whitespace(bytelist.begin, bytelist);
1264
+
1265
+ // What the hell is this for?
1266
+ if (bytelist.bytes[p] == '(') p = whitespace(p, bytelist);
1267
+
1268
+ for (int i = 0; i < bytelist.realSize && i < compare.length; i++) {
1269
+ if (Character.toLowerCase(bytelist.bytes[p + i]) != compare[i]) return false;
1270
+ }
1271
+
1272
+ return true;
1273
+ }
1274
+
1275
+ public static class ColumnData {
1276
+ public IRubyObject name;
1277
+ public int index;
1278
+ public int type;
1279
+
1280
+ public ColumnData(IRubyObject name, int type, int idx) {
1281
+ this.name = name;
1282
+ this.type = type;
1283
+ this.index = idx;
1284
+ }
1285
+
1286
+ public static ColumnData[] setup(Ruby runtime, DatabaseMetaData databaseMetadata,
1287
+ ResultSetMetaData metadata, boolean downCase) throws SQLException {
1288
+ int columnsCount = metadata.getColumnCount();
1289
+ ColumnData[] columns = new ColumnData[columnsCount];
1290
+
1291
+ for (int i = 1; i <= columnsCount; i++) { // metadata is one-based
1292
+ String name;
1293
+ if (downCase) {
1294
+ name = metadata.getColumnLabel(i).toLowerCase();
1295
+ } else {
1296
+ name = RubyJdbcConnection.caseConvertIdentifierForRails(databaseMetadata, metadata.getColumnLabel(i));
1297
+ }
1298
+
1299
+ columns[i - 1] = new ColumnData(RubyString.newUnicodeString(runtime, name), metadata.getColumnType(i), i);
1300
+ }
1301
+
1302
+ return columns;
1303
+ }
1304
+ }
1305
+ }