activerecord-jdbc-adapter 0.9.3-java

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