rsim-activerecord-oracle_enhanced-adapter 1.1.9.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/History.txt ADDED
@@ -0,0 +1,89 @@
1
+ == 1.1.9 2009-01-02
2
+
3
+ * Enhancements
4
+ * Added support for table and column comments in migrations
5
+ * Added support for specifying sequence start values
6
+ * Added :privilege option (e.g. :SYSDBA) to ActiveRecord::Base.establish_connection
7
+ * Bug fixes:
8
+ * Do not mark empty decimals, strings and texts (stored as NULL in database) as changed when reassigning them (starting from Rails 2.1)
9
+ * Create booleans as VARCHAR2(1) columns if emulate_booleans_from_strings is true
10
+
11
+ == 1.1.8 2008-10-10
12
+
13
+ * Bug fixes:
14
+ * Fixed storing of serialized LOB columns
15
+ * Prevent from SQL injection in :limit and :offset
16
+ * Order by LOB columns (by replacing column with function which returns first 100 characters of LOB)
17
+ * Sequence creation for tables with non-default primary key in create_table block
18
+ * Do count distinct workaround only when composite_primary_keys gem is used
19
+ (otherwise count distinct did not work with ActiveRecord 2.1.1)
20
+ * Fixed rake db:test:clone_structure task
21
+ (see http://rsim.lighthouseapp.com/projects/11468/tickets/11-rake-dbtestclone_structure-fails-in-117)
22
+ * Fixed bug when ActiveRecord::Base.allow_concurrency = true
23
+ (see http://dev.rubyonrails.org/ticket/11134)
24
+
25
+ == 1.1.7 2008-08-20
26
+
27
+ * Bug fixes:
28
+ * Fixed that adapter works without ruby-plsql gem (in this case just custom create/update/delete methods are not available)
29
+
30
+ == 1.1.6 2008-08-19
31
+
32
+ * Enhancements:
33
+ * Added support for set_date_columns and set_datetime_columns
34
+ * Added support for set_boolean_columns
35
+ * Added support for schema prefix in set_table_name (removed table name quoting)
36
+ * Added support for NVARCHAR2 column type
37
+ * Bug fixes:
38
+ * Do not call write_lobs callback when custom create or update methods are defined
39
+
40
+ == 1.1.5 2008-07-27
41
+
42
+ * Bug fixes:
43
+ * Fixed that write_lobs callback works with partial_updates enabled (added additional record lock before writing BLOB data to database)
44
+ * Enhancements:
45
+ * Changed SQL SELECT in indexes method so that it will execute faster on some large data dictionaries
46
+ * Support for other date and time formats when assigning string to :date or :datetime column
47
+
48
+ == 1.1.4 2008-07-14
49
+
50
+ * Enhancements:
51
+ * Date/Time quoting changes to support composite_primary_keys
52
+ * Added additional methods that are used by composite_primary_keys
53
+
54
+ == 1.1.3 2008-07-10
55
+
56
+ * Enhancements:
57
+ * Added support for custom create, update and delete methods when working with legacy databases where
58
+ PL/SQL API should be used for create, update and delete operations
59
+
60
+ == 1.1.2 2008-07-08
61
+
62
+ * Bug fixes:
63
+ * Fixed after_save callback addition for session store in ActiveRecord version 2.0.2
64
+ * Changed date column name recognition - now should match regex /(^|_)date(_|$)/i
65
+ (previously "updated_at" was recognized as :date column and not as :datetime)
66
+
67
+ == 1.1.1 2008-06-28
68
+
69
+ * Enhancements:
70
+ * Added ignore_table_columns option
71
+ * Added support for TIMESTAMP columns (without fractional seconds)
72
+ * NLS_DATE_FORMAT and NLS_TIMESTAMP_FORMAT independent DATE and TIMESTAMP columns support
73
+ * Bug fixes:
74
+ * Checks if CGI::Session::ActiveRecordStore::Session does not have enhanced_write_lobs callback before adding it
75
+ (Rails 2.0 does not add this callback, Rails 2.1 does)
76
+
77
+ == 1.1.0 2008-05-05
78
+
79
+ * Forked from original activerecord-oracle-adapter-1.0.0.9216
80
+ * Renamed oracle adapter to oracle_enhanced adapter
81
+ * Added "enhanced" to method and class definitions so that oracle_enhanced and original oracle adapter
82
+ could be used simultaniously
83
+ * Added Rails rake tasks as a copy from original oracle tasks
84
+ * Enhancements:
85
+ * Improved perfomance of schema dump methods when used on large data dictionaries
86
+ * Added LOB writing callback for sessions stored in database
87
+ * Added emulate_dates_by_column_name option
88
+ * Added emulate_integers_by_column_name option
89
+ * Added emulate_booleans_from_strings option
data/License.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 Graham Jenkins, Michael Schoen, Raimonds Simanovskis
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Manifest.txt ADDED
@@ -0,0 +1,20 @@
1
+ History.txt
2
+ License.txt
3
+ README.txt
4
+ lib/active_record/connection_adapters/emulation/oracle_adapter.rb
5
+ lib/active_record/connection_adapters/oracle_enhanced.rake
6
+ lib/active_record/connection_adapters/oracle_enhanced_adapter.rb
7
+ lib/active_record/connection_adapters/oracle_enhanced_cpk.rb
8
+ lib/active_record/connection_adapters/oracle_enhanced_dirty.rb
9
+ lib/active_record/connection_adapters/oracle_enhanced_procedures.rb
10
+ lib/active_record/connection_adapters/oracle_enhanced_reserved_words.rb
11
+ lib/active_record/connection_adapters/oracle_enhanced_tasks.rb
12
+ lib/active_record/connection_adapters/oracle_enhanced_version.rb
13
+ spec/active_record/connection_adapters/oracle_enhanced_adapter_spec.rb
14
+ spec/active_record/connection_adapters/oracle_enhanced_cpk_spec.rb
15
+ spec/active_record/connection_adapters/oracle_enhanced_data_types_spec.rb
16
+ spec/active_record/connection_adapters/oracle_enhanced_dirty_spec.rb
17
+ spec/active_record/connection_adapters/oracle_enhanced_emulate_oracle_adapter_spec.rb
18
+ spec/active_record/connection_adapters/oracle_enhanced_procedures_spec.rb
19
+ spec/spec.opts
20
+ spec/spec_helper.rb
data/README.txt ADDED
@@ -0,0 +1,51 @@
1
+ = activerecord-oracle_enhanced-adapter
2
+
3
+ * http://rubyforge.org/projects/oracle-enhanced/
4
+
5
+ == DESCRIPTION:
6
+
7
+ Oracle "enhanced" ActiveRecord adapter contains useful additional methods for working with new and legacy Oracle databases
8
+ from Rails which are extracted from current real projects' monkey patches of original Oracle adapter.
9
+
10
+ See http://github.com/rsim/oracle-enhanced/wikis for more information.
11
+
12
+ For questions and feature discussion please use http://groups.google.com/group/oracle-enhanced
13
+
14
+ Blog posts about oracle-enahnced can be found at http://blog.rayapps.com/category/oracle-enhanced
15
+
16
+ Bugs and enhancement requests can be reported at http://rsim.lighthouseapp.com/projects/11468-oracle-enhanced
17
+
18
+ == REQUIREMENTS:
19
+
20
+ * Works (has been tested) with ActiveRecord version 2.0, 2.1 and 2.2 (these are the same as Rails versions)
21
+ * Requires ruby-oci8 library to connect to Oracle
22
+ * Requires ruby-plsql gem to support custom create, update and delete methods (but can be used without ruby-plsql if this functionality is not needed)
23
+
24
+ == INSTALL:
25
+
26
+ * sudo gem install activerecord-oracle_enhanced-adapter
27
+
28
+ == LICENSE:
29
+
30
+ (The MIT License)
31
+
32
+ Copyright (c) 2009 Graham Jenkins, Michael Schoen, Raimonds Simanovskis
33
+
34
+ Permission is hereby granted, free of charge, to any person obtaining
35
+ a copy of this software and associated documentation files (the
36
+ 'Software'), to deal in the Software without restriction, including
37
+ without limitation the rights to use, copy, modify, merge, publish,
38
+ distribute, sublicense, and/or sell copies of the Software, and to
39
+ permit persons to whom the Software is furnished to do so, subject to
40
+ the following conditions:
41
+
42
+ The above copyright notice and this permission notice shall be
43
+ included in all copies or substantial portions of the Software.
44
+
45
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
46
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
47
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
48
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
49
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
50
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
51
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,5 @@
1
+ class ActiveRecord::ConnectionAdapters::OracleAdapter < ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter
2
+ def adapter_name
3
+ 'Oracle'
4
+ end
5
+ end
@@ -0,0 +1,44 @@
1
+ # RSI: implementation idea taken from JDBC adapter
2
+ def redefine_task(*args, &block)
3
+ task_name = Hash === args.first ? args.first.keys[0] : args.first
4
+ existing_task = Rake.application.lookup task_name
5
+ if existing_task
6
+ class << existing_task; public :instance_variable_set; end
7
+ existing_task.instance_variable_set "@prerequisites", FileList[]
8
+ existing_task.instance_variable_set "@actions", []
9
+ end
10
+ task(*args, &block)
11
+ end
12
+
13
+ namespace :db do
14
+
15
+ namespace :structure do
16
+ redefine_task :dump => :environment do
17
+ abcs = ActiveRecord::Base.configurations
18
+ ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
19
+ File.open("db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
20
+ if ActiveRecord::Base.connection.supports_migrations?
21
+ File.open("db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
22
+ end
23
+ end
24
+ end
25
+
26
+ namespace :test do
27
+ redefine_task :clone_structure => [ "db:structure:dump", "db:test:purge" ] do
28
+ abcs = ActiveRecord::Base.configurations
29
+ ActiveRecord::Base.establish_connection(:test)
30
+ IO.readlines("db/#{RAILS_ENV}_structure.sql").join.split("\n\n").each do |ddl|
31
+ ActiveRecord::Base.connection.execute(ddl.chop)
32
+ end
33
+ end
34
+
35
+ redefine_task :purge => :environment do
36
+ abcs = ActiveRecord::Base.configurations
37
+ ActiveRecord::Base.establish_connection(:test)
38
+ ActiveRecord::Base.connection.structure_drop.split("\n\n").each do |ddl|
39
+ ActiveRecord::Base.connection.execute(ddl.chop)
40
+ end
41
+ end
42
+
43
+ end
44
+ end
@@ -0,0 +1,931 @@
1
+ # oracle_enhanced_adapter.rb -- ActiveRecord adapter for Oracle 8i, 9i, 10g, 11g
2
+ #
3
+ # Authors or original oracle_adapter: Graham Jenkins, Michael Schoen
4
+ #
5
+ # Current maintainer: Raimonds Simanovskis (http://blog.rayapps.com)
6
+ #
7
+ #########################################################################
8
+ #
9
+ # See History.txt for changes added to original oracle_adapter.rb
10
+ #
11
+ #########################################################################
12
+ #
13
+ # From original oracle_adapter.rb:
14
+ #
15
+ # Implementation notes:
16
+ # 1. Redefines (safely) a method in ActiveRecord to make it possible to
17
+ # implement an autonumbering solution for Oracle.
18
+ # 2. The OCI8 driver is patched to properly handle values for LONG and
19
+ # TIMESTAMP columns. The driver-author has indicated that a future
20
+ # release of the driver will obviate this patch.
21
+ # 3. LOB support is implemented through an after_save callback.
22
+ # 4. Oracle does not offer native LIMIT and OFFSET options; this
23
+ # functionality is mimiced through the use of nested selects.
24
+ # See http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:127412348064
25
+ #
26
+ # Do what you want with this code, at your own peril, but if any
27
+ # significant portion of my code remains then please acknowledge my
28
+ # contribution.
29
+ # portions Copyright 2005 Graham Jenkins
30
+
31
+ require 'active_record/connection_adapters/abstract_adapter'
32
+
33
+ require 'active_record/connection_adapters/oracle_enhanced_connection'
34
+
35
+ module ActiveRecord
36
+ class Base
37
+ def self.oracle_enhanced_connection(config)
38
+ if config[:emulate_oracle_adapter] == true
39
+ # allows the enhanced adapter to look like the OracleAdapter. Useful to pick up
40
+ # conditionals in the rails activerecord test suite
41
+ require 'active_record/connection_adapters/emulation/oracle_adapter'
42
+ ConnectionAdapters::OracleAdapter.new(
43
+ ConnectionAdapters::OracleEnhancedConnection.create(config), logger)
44
+ else
45
+ ConnectionAdapters::OracleEnhancedAdapter.new(
46
+ ConnectionAdapters::OracleEnhancedConnection.create(config), logger)
47
+ end
48
+ end
49
+
50
+ # RSI: specify table columns which should be ifnored
51
+ def self.ignore_table_columns(*args)
52
+ connection.ignore_table_columns(table_name,*args)
53
+ end
54
+
55
+ # RSI: specify which table columns should be treated as date (without time)
56
+ def self.set_date_columns(*args)
57
+ connection.set_type_for_columns(table_name,:date,*args)
58
+ end
59
+
60
+ # RSI: specify which table columns should be treated as datetime
61
+ def self.set_datetime_columns(*args)
62
+ connection.set_type_for_columns(table_name,:datetime,*args)
63
+ end
64
+
65
+ # RSI: specify which table columns should be treated as booleans
66
+ def self.set_boolean_columns(*args)
67
+ connection.set_type_for_columns(table_name,:boolean,*args)
68
+ end
69
+
70
+ # After setting large objects to empty, select the OCI8::LOB
71
+ # and write back the data.
72
+ after_save :enhanced_write_lobs
73
+ def enhanced_write_lobs #:nodoc:
74
+ if connection.is_a?(ConnectionAdapters::OracleEnhancedAdapter) &&
75
+ !(self.class.custom_create_method || self.class.custom_update_method)
76
+ connection.write_lobs(self.class.table_name, self.class, attributes)
77
+ end
78
+ end
79
+ private :enhanced_write_lobs
80
+
81
+ class << self
82
+ # RSI: patch ORDER BY to work with LOBs
83
+ def add_order_with_lobs!(sql, order, scope = :auto)
84
+ if connection.is_a?(ConnectionAdapters::OracleEnhancedAdapter)
85
+ order = connection.lob_order_by_expression(self, order) if order
86
+
87
+ orig_scope = scope
88
+ scope = scope(:find) if :auto == scope
89
+ if scope
90
+ new_scope_order = connection.lob_order_by_expression(self, scope[:order])
91
+ if new_scope_order != scope[:order]
92
+ scope = scope.merge(:order => new_scope_order)
93
+ else
94
+ scope = orig_scope
95
+ end
96
+ end
97
+ end
98
+ add_order_without_lobs!(sql, order, scope = :auto)
99
+ end
100
+ private :add_order_with_lobs!
101
+ alias_method :add_order_without_lobs!, :add_order!
102
+ alias_method :add_order!, :add_order_with_lobs!
103
+ end
104
+
105
+ # RSI: get table comment from schema definition
106
+ def self.table_comment
107
+ connection.table_comment(self.table_name)
108
+ end
109
+ end
110
+
111
+
112
+ module ConnectionAdapters #:nodoc:
113
+ class OracleEnhancedColumn < Column #:nodoc:
114
+
115
+ attr_reader :table_name, :forced_column_type
116
+
117
+ def initialize(name, default, sql_type = nil, null = true, table_name = nil, forced_column_type = nil)
118
+ @table_name = table_name
119
+ @forced_column_type = forced_column_type
120
+ super(name, default, sql_type, null)
121
+ end
122
+
123
+ def type_cast(value)
124
+ return guess_date_or_time(value) if type == :datetime && OracleEnhancedAdapter.emulate_dates
125
+ super
126
+ end
127
+
128
+ # convert something to a boolean
129
+ # RSI: added y as boolean value
130
+ def self.value_to_boolean(value)
131
+ if value == true || value == false
132
+ value
133
+ else
134
+ %w(true t 1 y +).include?(value.to_s.downcase)
135
+ end
136
+ end
137
+
138
+ # RSI: convert Time value to Date for :date columns
139
+ def self.string_to_date(string)
140
+ return string.to_date if string.is_a?(Time)
141
+ super
142
+ end
143
+
144
+ # RSI: convert Date value to Time for :datetime columns
145
+ def self.string_to_time(string)
146
+ return string.to_time if string.is_a?(Date) && !OracleEnhancedAdapter.emulate_dates
147
+ super
148
+ end
149
+
150
+ # RSI: get column comment from schema definition
151
+ # will work only if using default ActiveRecord connection
152
+ def comment
153
+ ActiveRecord::Base.connection.column_comment(@table_name, name)
154
+ end
155
+
156
+ private
157
+ def simplified_type(field_type)
158
+ return :boolean if OracleEnhancedAdapter.emulate_booleans && field_type == 'NUMBER(1)'
159
+ return :boolean if OracleEnhancedAdapter.emulate_booleans_from_strings &&
160
+ (forced_column_type == :boolean ||
161
+ OracleEnhancedAdapter.is_boolean_column?(name, field_type, table_name))
162
+
163
+ case field_type
164
+ when /date/i
165
+ forced_column_type ||
166
+ (:date if OracleEnhancedAdapter.emulate_dates_by_column_name && OracleEnhancedAdapter.is_date_column?(name, table_name)) ||
167
+ :datetime
168
+ when /timestamp/i then :timestamp
169
+ when /time/i then :datetime
170
+ when /decimal|numeric|number/i
171
+ return :integer if extract_scale(field_type) == 0
172
+ # RSI: if column name is ID or ends with _ID
173
+ return :integer if OracleEnhancedAdapter.emulate_integers_by_column_name && OracleEnhancedAdapter.is_integer_column?(name, table_name)
174
+ :decimal
175
+ else super
176
+ end
177
+ end
178
+
179
+ def guess_date_or_time(value)
180
+ value.respond_to?(:hour) && (value.hour == 0 and value.min == 0 and value.sec == 0) ?
181
+ Date.new(value.year, value.month, value.day) : value
182
+ end
183
+
184
+ class <<self
185
+ protected
186
+
187
+ def fallback_string_to_date(string)
188
+ if OracleEnhancedAdapter.string_to_date_format || OracleEnhancedAdapter.string_to_time_format
189
+ return (string_to_date_or_time_using_format(string).to_date rescue super)
190
+ end
191
+ super
192
+ end
193
+
194
+ def fallback_string_to_time(string)
195
+ if OracleEnhancedAdapter.string_to_time_format || OracleEnhancedAdapter.string_to_date_format
196
+ return (string_to_date_or_time_using_format(string).to_time rescue super)
197
+ end
198
+ super
199
+ end
200
+
201
+ def string_to_date_or_time_using_format(string)
202
+ if OracleEnhancedAdapter.string_to_time_format && dt=Date._strptime(string, OracleEnhancedAdapter.string_to_time_format)
203
+ return Time.mktime(*dt.values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday))
204
+ end
205
+ DateTime.strptime(string, OracleEnhancedAdapter.string_to_date_format)
206
+ end
207
+
208
+ end
209
+ end
210
+
211
+
212
+ # This is an Oracle/OCI adapter for the ActiveRecord persistence
213
+ # framework. It relies upon the OCI8 driver, which works with Oracle 8i
214
+ # and above. Most recent development has been on Debian Linux against
215
+ # a 10g database, ActiveRecord 1.12.1 and OCI8 0.1.13.
216
+ # See: http://rubyforge.org/projects/ruby-oci8/
217
+ #
218
+ # Usage notes:
219
+ # * Key generation assumes a "${table_name}_seq" sequence is available
220
+ # for all tables; the sequence name can be changed using
221
+ # ActiveRecord::Base.set_sequence_name. When using Migrations, these
222
+ # sequences are created automatically.
223
+ # * Oracle uses DATE or TIMESTAMP datatypes for both dates and times.
224
+ # Consequently some hacks are employed to map data back to Date or Time
225
+ # in Ruby. If the column_name ends in _time it's created as a Ruby Time.
226
+ # Else if the hours/minutes/seconds are 0, I make it a Ruby Date. Else
227
+ # it's a Ruby Time. This is a bit nasty - but if you use Duck Typing
228
+ # you'll probably not care very much. In 9i and up it's tempting to
229
+ # map DATE to Date and TIMESTAMP to Time, but too many databases use
230
+ # DATE for both. Timezones and sub-second precision on timestamps are
231
+ # not supported.
232
+ # * Default values that are functions (such as "SYSDATE") are not
233
+ # supported. This is a restriction of the way ActiveRecord supports
234
+ # default values.
235
+ # * Support for Oracle8 is limited by Rails' use of ANSI join syntax, which
236
+ # is supported in Oracle9i and later. You will need to use #finder_sql for
237
+ # has_and_belongs_to_many associations to run against Oracle8.
238
+ #
239
+ # Required parameters:
240
+ #
241
+ # * <tt>:username</tt>
242
+ # * <tt>:password</tt>
243
+ # * <tt>:database</tt>
244
+ class OracleEnhancedAdapter < AbstractAdapter
245
+
246
+ @@emulate_booleans = true
247
+ cattr_accessor :emulate_booleans
248
+
249
+ @@emulate_dates = false
250
+ cattr_accessor :emulate_dates
251
+
252
+ # RSI: set to true if columns with DATE in their name should be emulated as date
253
+ @@emulate_dates_by_column_name = false
254
+ cattr_accessor :emulate_dates_by_column_name
255
+ def self.is_date_column?(name, table_name = nil)
256
+ name =~ /(^|_)date(_|$)/i
257
+ end
258
+ # RSI: instance method uses at first check if column type defined at class level
259
+ def is_date_column?(name, table_name = nil)
260
+ case get_type_for_column(table_name, name)
261
+ when nil
262
+ self.class.is_date_column?(name, table_name)
263
+ when :date
264
+ true
265
+ else
266
+ false
267
+ end
268
+ end
269
+
270
+ # RSI: set to true if NUMBER columns with ID at the end of their name should be emulated as integers
271
+ @@emulate_integers_by_column_name = false
272
+ cattr_accessor :emulate_integers_by_column_name
273
+ def self.is_integer_column?(name, table_name = nil)
274
+ name =~ /(^|_)id$/i
275
+ end
276
+
277
+ # RSI: set to true if CHAR(1), VARCHAR2(1) columns or VARCHAR2 columns with FLAG or YN at the end of their name
278
+ # should be emulated as booleans
279
+ @@emulate_booleans_from_strings = false
280
+ cattr_accessor :emulate_booleans_from_strings
281
+ def self.is_boolean_column?(name, field_type, table_name = nil)
282
+ return true if ["CHAR(1)","VARCHAR2(1)"].include?(field_type)
283
+ field_type =~ /^VARCHAR2/ && (name =~ /_flag$/i || name =~ /_yn$/i)
284
+ end
285
+ def self.boolean_to_string(bool)
286
+ bool ? "Y" : "N"
287
+ end
288
+
289
+ # RSI: use to set NLS specific date formats which will be used when assigning string to :date and :datetime columns
290
+ @@string_to_date_format = @@string_to_time_format = nil
291
+ cattr_accessor :string_to_date_format, :string_to_time_format
292
+
293
+ def adapter_name #:nodoc:
294
+ 'OracleEnhanced'
295
+ end
296
+
297
+ def supports_migrations? #:nodoc:
298
+ true
299
+ end
300
+
301
+ def native_database_types #:nodoc:
302
+ {
303
+ :primary_key => "NUMBER(38) NOT NULL PRIMARY KEY",
304
+ :string => { :name => "VARCHAR2", :limit => 255 },
305
+ :text => { :name => "CLOB" },
306
+ :integer => { :name => "NUMBER", :limit => 38 },
307
+ :float => { :name => "NUMBER" },
308
+ :decimal => { :name => "DECIMAL" },
309
+ :datetime => { :name => "DATE" },
310
+ # RSI: changed to native TIMESTAMP type
311
+ # :timestamp => { :name => "DATE" },
312
+ :timestamp => { :name => "TIMESTAMP" },
313
+ :time => { :name => "DATE" },
314
+ :date => { :name => "DATE" },
315
+ :binary => { :name => "BLOB" },
316
+ # RSI: if emulate_booleans_from_strings then store booleans in VARCHAR2
317
+ :boolean => emulate_booleans_from_strings ?
318
+ { :name => "VARCHAR2", :limit => 1 } : { :name => "NUMBER", :limit => 1 }
319
+ }
320
+ end
321
+
322
+ def table_alias_length
323
+ 30
324
+ end
325
+
326
+ # Returns an array of arrays containing the field values.
327
+ # Order is the same as that returned by #columns.
328
+ def select_rows(sql, name = nil)
329
+ result = select(sql, name)
330
+ result.map{ |v| v.values}
331
+ end
332
+
333
+ # QUOTING ==================================================
334
+ #
335
+ # see: abstract/quoting.rb
336
+
337
+ # camelCase column names need to be quoted; not that anyone using Oracle
338
+ # would really do this, but handling this case means we pass the test...
339
+ def quote_column_name(name) #:nodoc:
340
+ name.to_s =~ /[A-Z]/ ? "\"#{name}\"" : quote_oracle_reserved_words(name)
341
+ end
342
+
343
+ # unescaped table name should start with letter and
344
+ # contain letters, digits, _, $ or #
345
+ # can be prefixed with schema name
346
+ def self.valid_table_name?(name)
347
+ name.to_s =~ /^([A-Z_0-9]+\.)?[A-Z][A-Z_0-9\$#]*$/i ? true : false
348
+ end
349
+
350
+ # abstract_adapter calls quote_column_name from quote_table_name, so prevent that
351
+ def quote_table_name(name)
352
+ if self.class.valid_table_name?(name)
353
+ name
354
+ else
355
+ "\"#{name}\""
356
+ end
357
+ end
358
+
359
+ def quote_string(s) #:nodoc:
360
+ s.gsub(/'/, "''")
361
+ end
362
+
363
+ def quote(value, column = nil) #:nodoc:
364
+ if value && column
365
+ case column.type
366
+ when :text, :binary
367
+ %Q{empty_#{ column.sql_type.downcase rescue 'blob' }()}
368
+ # RSI: TIMESTAMP support
369
+ when :timestamp
370
+ quote_timestamp_with_to_timestamp(value)
371
+ # RSI: NLS_DATE_FORMAT independent DATE support
372
+ when :date, :time, :datetime
373
+ quote_date_with_to_date(value)
374
+ else
375
+ super
376
+ end
377
+ elsif value.acts_like?(:date)
378
+ quote_date_with_to_date(value)
379
+ elsif value.acts_like?(:time)
380
+ value.to_i == value.to_f ? quote_date_with_to_date(value) : quote_timestamp_with_to_timestamp(value)
381
+ else
382
+ super
383
+ end
384
+ end
385
+
386
+ def quoted_true
387
+ return "'#{self.class.boolean_to_string(true)}'" if emulate_booleans_from_strings
388
+ "1"
389
+ end
390
+
391
+ def quoted_false
392
+ return "'#{self.class.boolean_to_string(false)}'" if emulate_booleans_from_strings
393
+ "0"
394
+ end
395
+
396
+ # RSI: should support that composite_primary_keys gem will pass date as string
397
+ def quote_date_with_to_date(value)
398
+ value = value.to_s(:db) if value.acts_like?(:date) || value.acts_like?(:time)
399
+ "TO_DATE('#{value}','YYYY-MM-DD HH24:MI:SS')"
400
+ end
401
+
402
+ def quote_timestamp_with_to_timestamp(value)
403
+ # add up to 9 digits of fractional seconds to inserted time
404
+ value = "#{value.to_s(:db)}.#{("%.6f"%value.to_f).split('.')[1]}" if value.acts_like?(:time)
405
+ "TO_TIMESTAMP('#{value}','YYYY-MM-DD HH24:MI:SS.FF6')"
406
+ end
407
+
408
+ # CONNECTION MANAGEMENT ====================================
409
+ #
410
+
411
+ # If SQL statement fails due to lost connection then reconnect
412
+ # and retry SQL statement if autocommit mode is enabled.
413
+ # By default this functionality is disabled.
414
+ @auto_retry = false
415
+ attr_reader :auto_retry
416
+ def auto_retry=(value)
417
+ @auto_retry = value
418
+ @connection.auto_retry = value if @connection
419
+ end
420
+
421
+ def raw_connection
422
+ @connection.raw_connection
423
+ end
424
+
425
+ # Returns true if the connection is active.
426
+ def active?
427
+ # Pings the connection to check if it's still good. Note that an
428
+ # #active? method is also available, but that simply returns the
429
+ # last known state, which isn't good enough if the connection has
430
+ # gone stale since the last use.
431
+ @connection.ping
432
+ rescue OracleEnhancedConnectionException
433
+ false
434
+ end
435
+
436
+ # Reconnects to the database.
437
+ def reconnect!
438
+ @connection.reset!
439
+ rescue OracleEnhancedConnectionException => e
440
+ @logger.warn "#{adapter_name} automatic reconnection failed: #{e.message}"
441
+ end
442
+
443
+ # Disconnects from the database.
444
+ def disconnect!
445
+ @connection.logoff rescue nil
446
+ end
447
+
448
+
449
+ # DATABASE STATEMENTS ======================================
450
+ #
451
+ # see: abstract/database_statements.rb
452
+
453
+ def execute(sql, name = nil) #:nodoc:
454
+ log(sql, name) { @connection.exec sql }
455
+ end
456
+
457
+ # Returns the next sequence value from a sequence generator. Not generally
458
+ # called directly; used by ActiveRecord to get the next primary key value
459
+ # when inserting a new database record (see #prefetch_primary_key?).
460
+ def next_sequence_value(sequence_name)
461
+ select_one("select #{sequence_name}.nextval id from dual")['id']
462
+ end
463
+
464
+ def begin_db_transaction #:nodoc:
465
+ @connection.autocommit = false
466
+ end
467
+
468
+ def commit_db_transaction #:nodoc:
469
+ @connection.commit
470
+ ensure
471
+ @connection.autocommit = true
472
+ end
473
+
474
+ def rollback_db_transaction #:nodoc:
475
+ @connection.rollback
476
+ ensure
477
+ @connection.autocommit = true
478
+ end
479
+
480
+ def add_limit_offset!(sql, options) #:nodoc:
481
+ # RSI: added to_i for limit and offset to protect from SQL injection
482
+ offset = (options[:offset] || 0).to_i
483
+
484
+ if limit = options[:limit]
485
+ limit = limit.to_i
486
+ sql.replace "select * from (select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_ where rownum <= #{offset+limit}) where raw_rnum_ > #{offset}"
487
+ elsif offset > 0
488
+ sql.replace "select * from (select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_) where raw_rnum_ > #{offset}"
489
+ end
490
+ end
491
+
492
+ # Returns true for Oracle adapter (since Oracle requires primary key
493
+ # values to be pre-fetched before insert). See also #next_sequence_value.
494
+ def prefetch_primary_key?(table_name = nil)
495
+ true
496
+ end
497
+
498
+ def default_sequence_name(table, column) #:nodoc:
499
+ quote_table_name("#{table}_seq")
500
+ end
501
+
502
+
503
+ # Inserts the given fixture into the table. Overridden to properly handle lobs.
504
+ def insert_fixture(fixture, table_name)
505
+ super
506
+
507
+ klass = fixture.class_name.constantize rescue nil
508
+ if klass.respond_to?(:ancestors) && klass.ancestors.include?(ActiveRecord::Base)
509
+ write_lobs(table_name, klass, fixture)
510
+ end
511
+ end
512
+
513
+ # Writes LOB values from attributes, as indicated by the LOB columns of klass.
514
+ def write_lobs(table_name, klass, attributes)
515
+ id = quote(attributes[klass.primary_key])
516
+ klass.columns.select { |col| col.sql_type =~ /LOB$/i }.each do |col|
517
+ value = attributes[col.name]
518
+ # RSI: changed sequence of next two lines - should check if value is nil before converting to yaml
519
+ next if value.nil? || (value == '')
520
+ value = value.to_yaml if col.text? && klass.serialized_attributes[col.name]
521
+ uncached do
522
+ lob = select_one("SELECT #{col.name} FROM #{table_name} WHERE #{klass.primary_key} = #{id} FOR UPDATE",
523
+ 'Writable Large Object')[col.name]
524
+ @connection.write_lob(lob, value, col.type == :binary)
525
+ end
526
+ end
527
+ end
528
+
529
+ # RSI: change LOB column for ORDER BY clause
530
+ # just first 100 characters are taken for ordering
531
+ def lob_order_by_expression(klass, order)
532
+ return order if order.nil?
533
+ changed = false
534
+ new_order = order.to_s.strip.split(/, */).map do |order_by_col|
535
+ column_name, asc_desc = order_by_col.split(/ +/)
536
+ if column = klass.columns.detect { |col| col.name == column_name && col.sql_type =~ /LOB$/i}
537
+ changed = true
538
+ "DBMS_LOB.SUBSTR(#{column_name},100,1) #{asc_desc}"
539
+ else
540
+ order_by_col
541
+ end
542
+ end.join(', ')
543
+ changed ? new_order : order
544
+ end
545
+
546
+ # SCHEMA STATEMENTS ========================================
547
+ #
548
+ # see: abstract/schema_statements.rb
549
+
550
+ def current_database #:nodoc:
551
+ select_one("select sys_context('userenv','db_name') db from dual")["db"]
552
+ end
553
+
554
+ # RSI: changed select from user_tables to all_tables - much faster in large data dictionaries
555
+ def tables(name = nil) #:nodoc:
556
+ select_all("select lower(table_name) name from all_tables where owner = sys_context('userenv','session_user')").map {|t| t['name']}
557
+ end
558
+
559
+ def indexes(table_name, name = nil) #:nodoc:
560
+ result = select_all(<<-SQL, name)
561
+ SELECT lower(i.index_name) as index_name, i.uniqueness, lower(c.column_name) as column_name
562
+ FROM all_indexes i, user_ind_columns c
563
+ WHERE i.table_name = '#{table_name.to_s.upcase}'
564
+ AND c.index_name = i.index_name
565
+ AND i.index_name NOT IN (SELECT uc.index_name FROM user_constraints uc WHERE uc.constraint_type = 'P')
566
+ AND i.owner = sys_context('userenv','session_user')
567
+ ORDER BY i.index_name, c.column_position
568
+ SQL
569
+
570
+ current_index = nil
571
+ indexes = []
572
+
573
+ result.each do |row|
574
+ if current_index != row['index_name']
575
+ indexes << IndexDefinition.new(table_name, row['index_name'], row['uniqueness'] == "UNIQUE", [])
576
+ current_index = row['index_name']
577
+ end
578
+
579
+ indexes.last.columns << row['column_name']
580
+ end
581
+
582
+ indexes
583
+ end
584
+
585
+ # RSI: set ignored columns for table
586
+ def ignore_table_columns(table_name, *args)
587
+ @ignore_table_columns ||= {}
588
+ @ignore_table_columns[table_name] ||= []
589
+ @ignore_table_columns[table_name] += args.map{|a| a.to_s.downcase}
590
+ @ignore_table_columns[table_name].uniq!
591
+ end
592
+
593
+ def ignored_table_columns(table_name)
594
+ @ignore_table_columns ||= {}
595
+ @ignore_table_columns[table_name]
596
+ end
597
+
598
+ # RSI: set explicit type for specified table columns
599
+ def set_type_for_columns(table_name, column_type, *args)
600
+ @table_column_type ||= {}
601
+ @table_column_type[table_name] ||= {}
602
+ args.each do |col|
603
+ @table_column_type[table_name][col.to_s.downcase] = column_type
604
+ end
605
+ end
606
+
607
+ def get_type_for_column(table_name, column_name)
608
+ @table_column_type && @table_column_type[table_name] && @table_column_type[table_name][column_name.to_s.downcase]
609
+ end
610
+
611
+ def clear_types_for_columns
612
+ @table_column_type = nil
613
+ end
614
+
615
+ def columns(table_name, name = nil) #:nodoc:
616
+ # RSI: get ignored_columns by original table name
617
+ ignored_columns = ignored_table_columns(table_name)
618
+
619
+ (owner, desc_table_name) = @connection.describe(table_name)
620
+
621
+ table_cols = <<-SQL
622
+ select column_name as name, data_type as sql_type, data_default, nullable,
623
+ decode(data_type, 'NUMBER', data_precision,
624
+ 'FLOAT', data_precision,
625
+ 'VARCHAR2', data_length,
626
+ 'CHAR', data_length,
627
+ null) as limit,
628
+ decode(data_type, 'NUMBER', data_scale, null) as scale
629
+ from all_tab_columns
630
+ where owner = '#{owner}'
631
+ and table_name = '#{desc_table_name}'
632
+ order by column_id
633
+ SQL
634
+
635
+ # RSI: added deletion of ignored columns
636
+ select_all(table_cols, name).delete_if do |row|
637
+ ignored_columns && ignored_columns.include?(row['name'].downcase)
638
+ end.map do |row|
639
+ limit, scale = row['limit'], row['scale']
640
+ if limit || scale
641
+ row['sql_type'] << "(#{(limit || 38).to_i}" + ((scale = scale.to_i) > 0 ? ",#{scale})" : ")")
642
+ end
643
+
644
+ # clean up odd default spacing from Oracle
645
+ if row['data_default']
646
+ row['data_default'].sub!(/^(.*?)\s*$/, '\1')
647
+ row['data_default'].sub!(/^'(.*)'$/, '\1')
648
+ row['data_default'] = nil if row['data_default'] =~ /^(null|empty_[bc]lob\(\))$/i
649
+ end
650
+
651
+ OracleEnhancedColumn.new(oracle_downcase(row['name']),
652
+ row['data_default'],
653
+ row['sql_type'],
654
+ row['nullable'] == 'Y',
655
+ # RSI: pass table name for table specific column definitions
656
+ table_name,
657
+ # RSI: pass column type if specified in class definition
658
+ get_type_for_column(table_name, oracle_downcase(row['name'])))
659
+ end
660
+ end
661
+
662
+ # RSI: default sequence start with value
663
+ @@default_sequence_start_value = 10000
664
+ cattr_accessor :default_sequence_start_value
665
+
666
+ def create_table(name, options = {}, &block) #:nodoc:
667
+ create_sequence = options[:id] != false
668
+ column_comments = {}
669
+ super(name, options) do |t|
670
+ # store that primary key was defined in create_table block
671
+ unless create_sequence
672
+ class <<t
673
+ attr_accessor :create_sequence
674
+ def primary_key(*args)
675
+ self.create_sequence = true
676
+ super(*args)
677
+ end
678
+ end
679
+ end
680
+
681
+ # store column comments
682
+ class <<t
683
+ attr_accessor :column_comments
684
+ def column(name, type, options = {})
685
+ if options[:comment]
686
+ self.column_comments ||= {}
687
+ self.column_comments[name] = options[:comment]
688
+ end
689
+ super(name, type, options)
690
+ end
691
+ end
692
+
693
+ result = block.call(t)
694
+ create_sequence = create_sequence || t.create_sequence
695
+ column_comments = t.column_comments if t.column_comments
696
+ end
697
+
698
+ seq_name = options[:sequence_name] || quote_table_name("#{name}_seq")
699
+ seq_start_value = options[:sequence_start_value] || default_sequence_start_value
700
+ execute "CREATE SEQUENCE #{seq_name} START WITH #{seq_start_value}" if create_sequence
701
+
702
+ add_table_comment name, options[:comment]
703
+ column_comments.each do |column_name, comment|
704
+ add_comment name, column_name, comment
705
+ end
706
+
707
+ end
708
+
709
+ def rename_table(name, new_name) #:nodoc:
710
+ execute "RENAME #{name} TO #{new_name}"
711
+ execute "RENAME #{name}_seq TO #{new_name}_seq" rescue nil
712
+ end
713
+
714
+ def drop_table(name, options = {}) #:nodoc:
715
+ super(name)
716
+ seq_name = options[:sequence_name] || quote_table_name("#{name}_seq")
717
+ execute "DROP SEQUENCE #{seq_name}" rescue nil
718
+ end
719
+
720
+ def remove_index(table_name, options = {}) #:nodoc:
721
+ execute "DROP INDEX #{index_name(table_name, options)}"
722
+ end
723
+
724
+ def change_column_default(table_name, column_name, default) #:nodoc:
725
+ execute "ALTER TABLE #{table_name} MODIFY #{quote_column_name(column_name)} DEFAULT #{quote(default)}"
726
+ end
727
+
728
+ def change_column(table_name, column_name, type, options = {}) #:nodoc:
729
+ change_column_sql = "ALTER TABLE #{table_name} MODIFY #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
730
+ add_column_options!(change_column_sql, options)
731
+ execute(change_column_sql)
732
+ end
733
+
734
+ def rename_column(table_name, column_name, new_column_name) #:nodoc:
735
+ execute "ALTER TABLE #{table_name} RENAME COLUMN #{quote_column_name(column_name)} to #{quote_column_name(new_column_name)}"
736
+ end
737
+
738
+ def remove_column(table_name, column_name) #:nodoc:
739
+ execute "ALTER TABLE #{table_name} DROP COLUMN #{quote_column_name(column_name)}"
740
+ end
741
+
742
+ # RSI: table and column comments
743
+ def add_comment(table_name, column_name, comment)
744
+ return if comment.blank?
745
+ execute "COMMENT ON COLUMN #{quote_table_name(table_name)}.#{column_name} IS '#{comment}'"
746
+ end
747
+
748
+ def add_table_comment(table_name, comment)
749
+ return if comment.blank?
750
+ execute "COMMENT ON TABLE #{quote_table_name(table_name)} IS '#{comment}'"
751
+ end
752
+
753
+ def table_comment(table_name)
754
+ (owner, table_name) = @connection.describe(table_name)
755
+ select_value <<-SQL
756
+ SELECT comments FROM all_tab_comments
757
+ WHERE owner = '#{owner}'
758
+ AND table_name = '#{table_name}'
759
+ SQL
760
+ end
761
+
762
+ def column_comment(table_name, column_name)
763
+ (owner, table_name) = @connection.describe(table_name)
764
+ select_value <<-SQL
765
+ SELECT comments FROM all_col_comments
766
+ WHERE owner = '#{owner}'
767
+ AND table_name = '#{table_name}'
768
+ AND column_name = '#{column_name.upcase}'
769
+ SQL
770
+ end
771
+
772
+ # Find a table's primary key and sequence.
773
+ # *Note*: Only primary key is implemented - sequence will be nil.
774
+ def pk_and_sequence_for(table_name)
775
+ (owner, table_name) = @connection.describe(table_name)
776
+
777
+ # RSI: changed select from all_constraints to user_constraints - much faster in large data dictionaries
778
+ pks = select_values(<<-SQL, 'Primary Key')
779
+ select cc.column_name
780
+ from user_constraints c, all_cons_columns cc
781
+ where c.owner = '#{owner}'
782
+ and c.table_name = '#{table_name}'
783
+ and c.constraint_type = 'P'
784
+ and cc.owner = c.owner
785
+ and cc.constraint_name = c.constraint_name
786
+ SQL
787
+
788
+ # only support single column keys
789
+ pks.size == 1 ? [oracle_downcase(pks.first), nil] : nil
790
+ end
791
+
792
+ def structure_dump #:nodoc:
793
+ s = select_all("select sequence_name from user_sequences").inject("") do |structure, seq|
794
+ structure << "create sequence #{seq.to_a.first.last};\n\n"
795
+ end
796
+
797
+ # RSI: changed select from user_tables to all_tables - much faster in large data dictionaries
798
+ select_all("select table_name from all_tables where owner = sys_context('userenv','session_user')").inject(s) do |structure, table|
799
+ ddl = "create table #{table.to_a.first.last} (\n "
800
+ cols = select_all(%Q{
801
+ select column_name, data_type, data_length, char_used, char_length, data_precision, data_scale, data_default, nullable
802
+ from user_tab_columns
803
+ where table_name = '#{table.to_a.first.last}'
804
+ order by column_id
805
+ }).map do |row|
806
+ col = "#{row['column_name'].downcase} #{row['data_type'].downcase}"
807
+ if row['data_type'] =='NUMBER' and !row['data_precision'].nil?
808
+ col << "(#{row['data_precision'].to_i}"
809
+ col << ",#{row['data_scale'].to_i}" if !row['data_scale'].nil?
810
+ col << ')'
811
+ elsif row['data_type'].include?('CHAR')
812
+ length = row['char_used'] == 'C' ? row['char_length'].to_i : row['data_length'].to_i
813
+ col << "(#{length})"
814
+ end
815
+ col << " default #{row['data_default']}" if !row['data_default'].nil?
816
+ col << ' not null' if row['nullable'] == 'N'
817
+ col
818
+ end
819
+ ddl << cols.join(",\n ")
820
+ ddl << ");\n\n"
821
+ structure << ddl
822
+ end
823
+ end
824
+
825
+ def structure_drop #:nodoc:
826
+ s = select_all("select sequence_name from user_sequences").inject("") do |drop, seq|
827
+ drop << "drop sequence #{seq.to_a.first.last};\n\n"
828
+ end
829
+
830
+ # RSI: changed select from user_tables to all_tables - much faster in large data dictionaries
831
+ select_all("select table_name from all_tables where owner = sys_context('userenv','session_user')").inject(s) do |drop, table|
832
+ drop << "drop table #{table.to_a.first.last} cascade constraints;\n\n"
833
+ end
834
+ end
835
+
836
+ def add_column_options!(sql, options) #:nodoc:
837
+ # handle case of defaults for CLOB columns, which would otherwise get "quoted" incorrectly
838
+ if options_include_default?(options) && (column = options[:column]) && column.type == :text
839
+ sql << " DEFAULT #{quote(options.delete(:default))}"
840
+ end
841
+ super
842
+ end
843
+
844
+ # SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
845
+ #
846
+ # Oracle requires the ORDER BY columns to be in the SELECT list for DISTINCT
847
+ # queries. However, with those columns included in the SELECT DISTINCT list, you
848
+ # won't actually get a distinct list of the column you want (presuming the column
849
+ # has duplicates with multiple values for the ordered-by columns. So we use the
850
+ # FIRST_VALUE function to get a single (first) value for each column, effectively
851
+ # making every row the same.
852
+ #
853
+ # distinct("posts.id", "posts.created_at desc")
854
+ def distinct(columns, order_by)
855
+ return "DISTINCT #{columns}" if order_by.blank?
856
+
857
+ # construct a valid DISTINCT clause, ie. one that includes the ORDER BY columns, using
858
+ # FIRST_VALUE such that the inclusion of these columns doesn't invalidate the DISTINCT
859
+ order_columns = order_by.split(',').map { |s| s.strip }.reject(&:blank?)
860
+ order_columns = order_columns.zip((0...order_columns.size).to_a).map do |c, i|
861
+ "FIRST_VALUE(#{c.split.first}) OVER (PARTITION BY #{columns} ORDER BY #{c}) AS alias_#{i}__"
862
+ end
863
+ sql = "DISTINCT #{columns}, "
864
+ sql << order_columns * ", "
865
+ end
866
+
867
+ # ORDER BY clause for the passed order option.
868
+ #
869
+ # Uses column aliases as defined by #distinct.
870
+ def add_order_by_for_association_limiting!(sql, options)
871
+ return sql if options[:order].blank?
872
+
873
+ order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?)
874
+ order.map! {|s| $1 if s =~ / (.*)/}
875
+ order = order.zip((0...order.size).to_a).map { |s,i| "alias_#{i}__ #{s}" }.join(', ')
876
+
877
+ sql << " ORDER BY #{order}"
878
+ end
879
+
880
+ private
881
+
882
+ def select(sql, name = nil)
883
+ log(sql, name) do
884
+ @connection.select(sql, name)
885
+ end
886
+ end
887
+
888
+ def oracle_downcase(column_name)
889
+ @connection.oracle_downcase(column_name)
890
+ end
891
+
892
+ end
893
+ end
894
+ end
895
+
896
+ # RSI: Added LOB writing callback for sessions stored in database
897
+ # Otherwise it is not working as Session class is defined before OracleAdapter is loaded in Rails 2.0
898
+ if defined?(CGI::Session::ActiveRecordStore::Session)
899
+ if !CGI::Session::ActiveRecordStore::Session.respond_to?(:after_save_callback_chain) ||
900
+ CGI::Session::ActiveRecordStore::Session.after_save_callback_chain.detect{|cb| cb.method == :enhanced_write_lobs}.nil?
901
+ class CGI::Session::ActiveRecordStore::Session
902
+ after_save :enhanced_write_lobs
903
+ end
904
+ end
905
+ end
906
+
907
+ # RSI: load custom create, update, delete methods functionality
908
+ # rescue LoadError if ruby-plsql gem cannot be loaded
909
+ begin
910
+ require 'active_record/connection_adapters/oracle_enhanced_procedures'
911
+ rescue LoadError
912
+ if defined?(RAILS_DEFAULT_LOGGER)
913
+ RAILS_DEFAULT_LOGGER.info "INFO: ActiveRecord oracle_enhanced adapter could not load ruby-plsql gem. "+
914
+ "Custom create, update and delete methods will not be available."
915
+ end
916
+ end
917
+
918
+ # RSI: load additional methods for composite_primary_keys support
919
+ require 'active_record/connection_adapters/oracle_enhanced_cpk'
920
+
921
+ # RSI: load patch for dirty tracking methods
922
+ require 'active_record/connection_adapters/oracle_enhanced_dirty'
923
+
924
+ # RSI: load rake tasks definitions
925
+ begin
926
+ require 'active_record/connection_adapters/oracle_enhanced_tasks'
927
+ rescue LoadError
928
+ end if defined?(RAILS_ROOT)
929
+
930
+ # handles quoting of oracle reserved words
931
+ require 'active_record/connection_adapters/oracle_enhanced_reserved_words'