c3-activerecord-jdbc-adapter 1.1.3

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