0
-# oracle_adapter.rb -- ActiveRecord adapter for Oracle 8i, 9i, 10g
0
-# Original author: Graham Jenkins
0
-# Current maintainer: Michael Schoen <schoenm@earthlink.net>
0
-#########################################################################
0
-# Implementation notes:
0
-# 1. Redefines (safely) a method in ActiveRecord to make it possible to
0
-# implement an autonumbering solution for Oracle.
0
-# 2. The OCI8 driver is patched to properly handle values for LONG and
0
-# TIMESTAMP columns. The driver-author has indicated that a future
0
-# release of the driver will obviate this patch.
0
-# 3. LOB support is implemented through an after_save callback.
0
-# 4. Oracle does not offer native LIMIT and OFFSET options; this
0
-# functionality is mimiced through the use of nested selects.
0
-# See http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:127412348064
0
-# Do what you want with this code, at your own peril, but if any
0
-# significant portion of my code remains then please acknowledge my
0
-# portions Copyright 2005 Graham Jenkins
0
-require 'active_record/connection_adapters/abstract_adapter'
0
- require_library_or_gem 'oci8' unless self.class.const_defined? :OCI8
0
- def self.oracle_connection(config) #:nodoc:
0
- # Use OCI8AutoRecover instead of normal OCI8 driver.
0
- ConnectionAdapters::OracleAdapter.new OCI8AutoRecover.new(config), logger
0
- # for backwards-compatibility
0
- def self.oci_connection(config) #:nodoc:
0
- config[:database] = config[:host]
0
- self.oracle_connection(config)
0
- # After setting large objects to empty, select the OCI8::LOB
0
- # and write back the data.
0
- after_save :write_lobs
0
- def write_lobs #:nodoc:
0
- if connection.is_a?(ConnectionAdapters::OracleAdapter)
0
- connection.write_lobs(self.class.table_name, self.class, attributes)
0
- module ConnectionAdapters #:nodoc:
0
- class OracleColumn < Column #:nodoc:
0
- return guess_date_or_time(value) if type == :datetime && OracleAdapter.emulate_dates
0
- def simplified_type(field_type)
0
- return :boolean if OracleAdapter.emulate_booleans && field_type == 'NUMBER(1)'
0
- when /date|time/i then :datetime
0
- def guess_date_or_time(value)
0
- (value.hour == 0 and value.min == 0 and value.sec == 0) ?
0
- Date.new(value.year, value.month, value.day) : value
0
- # This is an Oracle/OCI adapter for the ActiveRecord persistence
0
- # framework. It relies upon the OCI8 driver, which works with Oracle 8i
0
- # and above. Most recent development has been on Debian Linux against
0
- # a 10g database, ActiveRecord 1.12.1 and OCI8 0.1.13.
0
- # See: http://rubyforge.org/projects/ruby-oci8/
0
- # * Key generation assumes a "${table_name}_seq" sequence is available
0
- # for all tables; the sequence name can be changed using
0
- # ActiveRecord::Base.set_sequence_name. When using Migrations, these
0
- # sequences are created automatically.
0
- # * Oracle uses DATE or TIMESTAMP datatypes for both dates and times.
0
- # Consequently some hacks are employed to map data back to Date or Time
0
- # in Ruby. If the column_name ends in _time it's created as a Ruby Time.
0
- # Else if the hours/minutes/seconds are 0, I make it a Ruby Date. Else
0
- # it's a Ruby Time. This is a bit nasty - but if you use Duck Typing
0
- # you'll probably not care very much. In 9i and up it's tempting to
0
- # map DATE to Date and TIMESTAMP to Time, but too many databases use
0
- # DATE for both. Timezones and sub-second precision on timestamps are
0
- # * Default values that are functions (such as "SYSDATE") are not
0
- # supported. This is a restriction of the way ActiveRecord supports
0
- # * Support for Oracle8 is limited by Rails' use of ANSI join syntax, which
0
- # is supported in Oracle9i and later. You will need to use #finder_sql for
0
- # has_and_belongs_to_many associations to run against Oracle8.
0
- # Required parameters:
0
- # * <tt>:username</tt>
0
- # * <tt>:password</tt>
0
- # * <tt>:database</tt>
0
- class OracleAdapter < AbstractAdapter
0
- @@emulate_booleans = true
0
- cattr_accessor :emulate_booleans
0
- @@emulate_dates = false
0
- cattr_accessor :emulate_dates
0
- def adapter_name #:nodoc:
0
- def supports_migrations? #:nodoc:
0
- def native_database_types #:nodoc:
0
- :primary_key => "NUMBER(38) NOT NULL PRIMARY KEY",
0
- :string => { :name => "VARCHAR2", :limit => 255 },
0
- :text => { :name => "CLOB" },
0
- :integer => { :name => "NUMBER", :limit => 38 },
0
- :float => { :name => "NUMBER" },
0
- :decimal => { :name => "DECIMAL" },
0
- :datetime => { :name => "DATE" },
0
- :timestamp => { :name => "DATE" },
0
- :time => { :name => "DATE" },
0
- :date => { :name => "DATE" },
0
- :binary => { :name => "BLOB" },
0
- :boolean => { :name => "NUMBER", :limit => 1 }
0
- def table_alias_length
0
- # QUOTING ==================================================
0
- # see: abstract/quoting.rb
0
- # camelCase column names need to be quoted; not that anyone using Oracle
0
- # would really do this, but handling this case means we pass the test...
0
- def quote_column_name(name) #:nodoc:
0
- name.to_s =~ /[A-Z]/ ? "\"#{name}\"" : name
0
- def quote_string(s) #:nodoc:
0
- def quote(value, column = nil) #:nodoc:
0
- if value && column && [:text, :binary].include?(column.type)
0
- %Q{empty_#{ column.sql_type.downcase rescue 'blob' }()}
0
- # CONNECTION MANAGEMENT ====================================
0
- # Returns true if the connection is active.
0
- # Pings the connection to check if it's still good. Note that an
0
- # #active? method is also available, but that simply returns the
0
- # last known state, which isn't good enough if the connection has
0
- # gone stale since the last use.
0
- # Reconnects to the database.
0
- rescue OCIException => e
0
- @logger.warn "#{adapter_name} automatic reconnection failed: #{e.message}"
0
- # Disconnects from the database.
0
- @connection.logoff rescue nil
0
- @connection.active = false
0
- # DATABASE STATEMENTS ======================================
0
- # see: abstract/database_statements.rb
0
- def execute(sql, name = nil) #:nodoc:
0
- log(sql, name) { @connection.exec sql }
0
- # Returns the next sequence value from a sequence generator. Not generally
0
- # called directly; used by ActiveRecord to get the next primary key value
0
- # when inserting a new database record (see #prefetch_primary_key?).
0
- def next_sequence_value(sequence_name)
0
- @connection.exec("select #{sequence_name}.nextval id from dual") { |r| id = r[0].to_i }
0
- def begin_db_transaction #:nodoc:
0
- @connection.autocommit = false
0
- def commit_db_transaction #:nodoc:
0
- @connection.autocommit = true
0
- def rollback_db_transaction #:nodoc:
0
- @connection.autocommit = true
0
- def add_limit_offset!(sql, options) #:nodoc:
0
- offset = options[:offset] || 0
0
- if limit = options[:limit]
0
- sql.replace "select * from (select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_ where rownum <= #{offset+limit}) where raw_rnum_ > #{offset}"
0
- sql.replace "select * from (select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_) where raw_rnum_ > #{offset}"
0
- # Returns true for Oracle adapter (since Oracle requires primary key
0
- # values to be pre-fetched before insert). See also #next_sequence_value.
0
- def prefetch_primary_key?(table_name = nil)
0
- def default_sequence_name(table, column) #:nodoc:
0
- # Inserts the given fixture into the table. Overridden to properly handle lobs.
0
- def insert_fixture(fixture, table_name)
0
- klass = fixture.class_name.constantize rescue nil
0
- if klass.respond_to?(:ancestors) && klass.ancestors.include?(ActiveRecord::Base)
0
- write_lobs(table_name, klass, fixture)
0
- # Writes LOB values from attributes, as indicated by the LOB columns of klass.
0
- def write_lobs(table_name, klass, attributes)
0
- id = quote(attributes[klass.primary_key])
0
- klass.columns.select { |col| col.sql_type =~ /LOB$/i }.each do |col|
0
- value = attributes[col.name]
0
- value = value.to_yaml if col.text? && klass.serialized_attributes[col.name]
0
- next if value.nil? || (value == '')
0
- lob = select_one("SELECT #{col.name} FROM #{table_name} WHERE #{klass.primary_key} = #{id}",
0
- 'Writable Large Object')[col.name]
0
- # SCHEMA STATEMENTS ========================================
0
- # see: abstract/schema_statements.rb
0
- def current_database #:nodoc:
0
- select_one("select sys_context('userenv','db_name') db from dual")["db"]
0
- def tables(name = nil) #:nodoc:
0
- select_all("select lower(table_name) from user_tables").inject([]) do | tabs, t |
0
- tabs << t.to_a.first.last
0
- def indexes(table_name, name = nil) #:nodoc:
0
- result = select_all(<<-SQL, name)
0
- SELECT lower(i.index_name) as index_name, i.uniqueness, lower(c.column_name) as column_name
0
- FROM user_indexes i, user_ind_columns c
0
- WHERE i.table_name = '#{table_name.to_s.upcase}'
0
- AND c.index_name = i.index_name
0
- AND i.index_name NOT IN (SELECT uc.index_name FROM user_constraints uc WHERE uc.constraint_type = 'P')
0
- ORDER BY i.index_name, c.column_position
0
- if current_index != row['index_name']
0
- indexes << IndexDefinition.new(table_name, row['index_name'], row['uniqueness'] == "UNIQUE", [])
0
- current_index = row['index_name']
0
- indexes.last.columns << row['column_name']
0
- def columns(table_name, name = nil) #:nodoc:
0
- (owner, table_name) = @connection.describe(table_name)
0
- select column_name as name, data_type as sql_type, data_default, nullable,
0
- decode(data_type, 'NUMBER', data_precision,
0
- 'FLOAT', data_precision,
0
- 'VARCHAR2', data_length,
0
- decode(data_type, 'NUMBER', data_scale, null) as scale
0
- where owner = '#{owner}'
0
- and table_name = '#{table_name}'
0
- select_all(table_cols, name).map do |row|
0
- limit, scale = row['limit'], row['scale']
0
- row['sql_type'] << "(#{(limit || 38).to_i}" + ((scale = scale.to_i) > 0 ? ",#{scale})" : ")")
0
- # clean up odd default spacing from Oracle
0
- if row['data_default']
0
- row['data_default'].sub!(/^(.*?)\s*$/, '\1')
0
- row['data_default'].sub!(/^'(.*)'$/, '\1')
0
- row['data_default'] = nil if row['data_default'] =~ /^(null|empty_[bc]lob\(\))$/i
0
- OracleColumn.new(oracle_downcase(row['name']),
0
- row['nullable'] == 'Y')
0
- def create_table(name, options = {}) #:nodoc:
0
- seq_name = options[:sequence_name] || "#{name}_seq"
0
- execute "CREATE SEQUENCE #{seq_name} START WITH 10000" unless options[:id] == false
0
- def rename_table(name, new_name) #:nodoc:
0
- execute "RENAME #{name} TO #{new_name}"
0
- execute "RENAME #{name}_seq TO #{new_name}_seq" rescue nil
0
- def drop_table(name, options = {}) #:nodoc:
0
- seq_name = options[:sequence_name] || "#{name}_seq"
0
- execute "DROP SEQUENCE #{seq_name}" rescue nil
0
- def remove_index(table_name, options = {}) #:nodoc:
0
- execute "DROP INDEX #{index_name(table_name, options)}"
0
- def change_column_default(table_name, column_name, default) #:nodoc:
0
- execute "ALTER TABLE #{table_name} MODIFY #{quote_column_name(column_name)} DEFAULT #{quote(default)}"
0
- def change_column(table_name, column_name, type, options = {}) #:nodoc:
0
- change_column_sql = "ALTER TABLE #{table_name} MODIFY #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
0
- add_column_options!(change_column_sql, options)
0
- execute(change_column_sql)
0
- def rename_column(table_name, column_name, new_column_name) #:nodoc:
0
- execute "ALTER TABLE #{table_name} RENAME COLUMN #{quote_column_name(column_name)} to #{quote_column_name(new_column_name)}"
0
- def remove_column(table_name, column_name) #:nodoc:
0
- execute "ALTER TABLE #{table_name} DROP COLUMN #{quote_column_name(column_name)}"
0
- # Find a table's primary key and sequence.
0
- # *Note*: Only primary key is implemented - sequence will be nil.
0
- def pk_and_sequence_for(table_name)
0
- (owner, table_name) = @connection.describe(table_name)
0
- pks = select_values(<<-SQL, 'Primary Key')
0
- from all_constraints c, all_cons_columns cc
0
- where c.owner = '#{owner}'
0
- and c.table_name = '#{table_name}'
0
- and c.constraint_type = 'P'
0
- and cc.owner = c.owner
0
- and cc.constraint_name = c.constraint_name
0
- # only support single column keys
0
- pks.size == 1 ? [oracle_downcase(pks.first), nil] : nil
0
- def structure_dump #:nodoc:
0
- s = select_all("select sequence_name from user_sequences").inject("") do |structure, seq|
0
- structure << "create sequence #{seq.to_a.first.last};\n\n"
0
- select_all("select table_name from user_tables").inject(s) do |structure, table|
0
- ddl = "create table #{table.to_a.first.last} (\n "
0
- select column_name, data_type, data_length, data_precision, data_scale, data_default, nullable
0
- where table_name = '#{table.to_a.first.last}'
0
- col = "#{row['column_name'].downcase} #{row['data_type'].downcase}"
0
- if row['data_type'] =='NUMBER' and !row['data_precision'].nil?
0
- col << "(#{row['data_precision'].to_i}"
0
- col << ",#{row['data_scale'].to_i}" if !row['data_scale'].nil?
0
- elsif row['data_type'].include?('CHAR')
0
- col << "(#{row['data_length'].to_i})"
0
- col << " default #{row['data_default']}" if !row['data_default'].nil?
0
- col << ' not null' if row['nullable'] == 'N'
0
- ddl << cols.join(",\n ")
0
- def structure_drop #:nodoc:
0
- s = select_all("select sequence_name from user_sequences").inject("") do |drop, seq|
0
- drop << "drop sequence #{seq.to_a.first.last};\n\n"
0
- select_all("select table_name from user_tables").inject(s) do |drop, table|
0
- drop << "drop table #{table.to_a.first.last} cascade constraints;\n\n"
0
- def add_column_options!(sql, options) #:nodoc:
0
- # handle case of defaults for CLOB columns, which would otherwise get "quoted" incorrectly
0
- if options_include_default?(options) && (column = options[:column]) && column.type == :text
0
- sql << " DEFAULT #{quote(options.delete(:default))}"
0
- # SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
0
- # Oracle requires the ORDER BY columns to be in the SELECT list for DISTINCT
0
- # queries. However, with those columns included in the SELECT DISTINCT list, you
0
- # won't actually get a distinct list of the column you want (presuming the column
0
- # has duplicates with multiple values for the ordered-by columns. So we use the
0
- # FIRST_VALUE function to get a single (first) value for each column, effectively
0
- # making every row the same.
0
- # distinct("posts.id", "posts.created_at desc")
0
- def distinct(columns, order_by)
0
- return "DISTINCT #{columns}" if order_by.blank?
0
- # construct a valid DISTINCT clause, ie. one that includes the ORDER BY columns, using
0
- # FIRST_VALUE such that the inclusion of these columns doesn't invalidate the DISTINCT
0
- order_columns = order_by.split(',').map { |s| s.strip }.reject(&:blank?)
0
- order_columns = order_columns.zip((0...order_columns.size).to_a).map do |c, i|
0
- "FIRST_VALUE(#{c.split.first}) OVER (PARTITION BY #{columns} ORDER BY #{c}) AS alias_#{i}__"
0
- sql = "DISTINCT #{columns}, "
0
- sql << order_columns * ", "
0
- # ORDER BY clause for the passed order option.
0
- # Uses column aliases as defined by #distinct.
0
- def add_order_by_for_association_limiting!(sql, options)
0
- return sql if options[:order].blank?
0
- order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?)
0
- order.map! {|s| $1 if s =~ / (.*)/}
0
- order = order.zip((0...order.size).to_a).map { |s,i| "alias_#{i}__ #{s}" }.join(', ')
0
- sql << " ORDER BY #{order}"
0
- def select(sql, name = nil)
0
- cursor = execute(sql, name)
0
- cols = cursor.get_col_names.map { |x| oracle_downcase(x) }
0
- while row = cursor.fetch
0
- cols.each_with_index do |col, i|
0
- name == 'Writable Large Object' ? row[i]: row[i].read
0
- if emulate_dates && (d.hour == 0 && d.minute == 0 && d.second == 0)
0
- # see string_to_time; Time overflowing to DateTime, respecting the default timezone
0
- time_array = [d.year, d.month, d.day, d.hour, d.minute, d.second]
0
- Time.send(Base.default_timezone, *time_array)
0
- zone_offset = if Base.default_timezone == :local then DateTime.now.offset else 0 end
0
- # Append zero calendar reform start to account for dates skipped by calendar reform
0
- DateTime.new(*time_array[0..5] << zone_offset << 0) rescue nil
0
- end unless col == 'raw_rnum_'
0
- cursor.close if cursor
0
- # Oracle column names by default are case-insensitive, but treated as upcase;
0
- # for neatness, we'll downcase within Rails. EXCEPT that folks CAN quote
0
- # their column names when creating Oracle tables, which makes then case-sensitive.
0
- # I don't know anybody who does this, but we'll handle the theoretical case of a
0
- # camelCase column name. I imagine other dbs handle this different, since there's a
0
- # unit test that's currently failing test_oci.
0
- def oracle_downcase(column_name)
0
- column_name =~ /[a-z]/ ? column_name : column_name.downcase
0
- # This OCI8 patch may not longer be required with the upcoming
0
- # release of version 0.2.
0
- alias :define_a_column_pre_ar :define_a_column
0
- def define_a_column(i)
0
- case do_ocicall(@ctx) { @parms[i - 1].attrGet(OCI_ATTR_DATA_TYPE) }
0
- when 8; @stmt.defineByPos(i, String, 65535) # Read LONG values
0
- when 187; @stmt.defineByPos(i, OraDate) # Read TIMESTAMP values
0
- if @parms[i - 1].attrGet(OCI_ATTR_TYPE_NAME) == 'XMLTYPE'
0
- @stmt.defineByPos(i, String, 65535)
0
- raise 'unsupported datatype'
0
- else define_a_column_pre_ar i
0
- # missing constant from oci8 < 0.1.14
0
- OCI_PTYPE_UNK = 0 unless defined?(OCI_PTYPE_UNK)
0
- # Uses the describeAny OCI call to find the target owner and table_name
0
- # indicated by +name+, parsing through synonynms as necessary. Returns
0
- # an array of [owner, table_name].
0
- @desc ||= @@env.alloc(OCIDescribe)
0
- @desc.attrSet(OCI_ATTR_DESC_PUBLIC, -1) if VERSION >= '0.1.14'
0
- @desc.describeAny(@svc, name.to_s, OCI_PTYPE_UNK) rescue raise %Q{"DESC #{name}" failed; does it exist?}
0
- info = @desc.attrGet(OCI_ATTR_PARAM)
0
- case info.attrGet(OCI_ATTR_PTYPE)
0
- when OCI_PTYPE_TABLE, OCI_PTYPE_VIEW
0
- owner = info.attrGet(OCI_ATTR_OBJ_SCHEMA)
0
- table_name = info.attrGet(OCI_ATTR_OBJ_NAME)
0
- schema = info.attrGet(OCI_ATTR_SCHEMA_NAME)
0
- name = info.attrGet(OCI_ATTR_NAME)
0
- describe(schema + '.' + name)
0
- else raise %Q{"DESC #{name}" failed; not a table or view.}
0
- # The OracleConnectionFactory factors out the code necessary to connect and
0
- # configure an Oracle/OCI connection.
0
- class OracleConnectionFactory #:nodoc:
0
- def new_connection(username, password, database, async, prefetch_rows, cursor_sharing)
0
- conn = OCI8.new username, password, database
0
- conn.exec %q{alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'}
0
- conn.exec %q{alter session set nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS'} rescue nil
0
- conn.autocommit = true
0
- conn.non_blocking = true if async
0
- conn.prefetch_rows = prefetch_rows
0
- conn.exec "alter session set cursor_sharing = #{cursor_sharing}" rescue nil
0
- # The OCI8AutoRecover class enhances the OCI8 driver with auto-recover and
0
- # reset functionality. If a call to #exec fails, and autocommit is turned on
0
- # (ie., we're not in the middle of a longer transaction), it will
0
- # automatically reconnect and try again. If autocommit is turned off,
0
- # this would be dangerous (as the earlier part of the implied transaction
0
- # may have failed silently if the connection died) -- so instead the
0
- # connection is marked as dead, to be reconnected on it's next use.
0
- class OCI8AutoRecover < DelegateClass(OCI8) #:nodoc:
0
- alias :active? :active
0
- cattr_accessor :auto_retry
0
- alias :auto_retry? :auto_retry
0
- def initialize(config, factory = OracleConnectionFactory.new)
0
- @username, @password, @database, = config[:username], config[:password], config[:database]