kb-activerecord-jdbc-adapter 0.9.7.1-java

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