Class: ActiveRecord::ConnectionAdapters::OracleEnhancedJDBCConnection

Inherits:
OracleEnhancedConnection show all
Defined in:
lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb

Overview

JDBC database interface for JRuby

Defined Under Namespace

Classes: Cursor

Instance Attribute Summary collapse

Attributes inherited from OracleEnhancedConnection

#raw_connection

Instance Method Summary collapse

Methods inherited from OracleEnhancedConnection

create, #describe, #oracle_downcase, #select_one, #select_value, #select_values

Constructor Details

#initialize(config) ⇒ OracleEnhancedJDBCConnection

Returns a new instance of OracleEnhancedJDBCConnection.



52
53
54
55
56
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 52

def initialize(config)
  @active = true
  @config = config
  new_connection(@config)
end

Instance Attribute Details

#activeObject Also known as: active?

:nodoc:



45
46
47
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 45

def active
  @active
end

#auto_retryObject Also known as: auto_retry?

Returns the value of attribute auto_retry.



48
49
50
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 48

def auto_retry
  @auto_retry
end

Instance Method Details

#autocommit=(value) ⇒ Object



170
171
172
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 170

def autocommit=(value)
  @raw_connection.setAutoCommit(value)
end

#autocommit?Boolean

Returns:

  • (Boolean)


166
167
168
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 166

def autocommit?
  @raw_connection.getAutoCommit
end

#commitObject



158
159
160
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 158

def commit
  @raw_connection.commit
end

#error_code(exception) ⇒ Object

Return NativeException / java.sql.SQLException error code



481
482
483
484
485
486
487
488
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 481

def error_code(exception)
  case exception
  when NativeException
    exception.cause.getErrorCode
  else
    nil
  end
end

#exec(sql) ⇒ Object



220
221
222
223
224
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 220

def exec(sql)
  with_retry do
    exec_no_retry(sql)
  end
end

#exec_no_retry(sql) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 226

def exec_no_retry(sql)
  case sql
  when /\A\s*(UPDATE|INSERT|DELETE)/i
    s = @raw_connection.prepareStatement(sql)
    s.executeUpdate
  # it is safer for CREATE and DROP statements not to use PreparedStatement
  # as it does not allow creation of triggers with :NEW in their definition
  when /\A\s*(CREATE|DROP)/i
    s = @raw_connection.createStatement()
    # this disables SQL92 syntax processing of {...} which can result in statement execution errors
    # if sql contains {...} in strings or comments
    s.setEscapeProcessing(false)
    s.execute(sql)
    true
  else
    s = @raw_connection.prepareStatement(sql)
    s.execute
    true
  end
ensure
  s.close rescue nil
end

#exec_with_returning(sql) ⇒ Object

execute sql with RETURNING … INTO :insert_id and return :insert_id value



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 255

def exec_with_returning(sql)
  with_retry do
    begin
      # it will always be INSERT statement

      # TODO: need to investigate why PreparedStatement is giving strange exception "Protocol violation"
      # s = @raw_connection.prepareStatement(sql)
      # s.registerReturnParameter(1, ::Java::oracle.jdbc.OracleTypes::NUMBER)
      # count = s.executeUpdate
      # if count > 0
      #   rs = s.getReturnResultSet
      #   if rs.next
      #     # Assuming that primary key will not be larger as long max value
      #     insert_id = rs.getLong(1)
      #     rs.wasNull ? nil : insert_id
      #   else
      #     nil
      #   end
      # else
      #   nil
      # end
      
      # Workaround with CallableStatement
      s = @raw_connection.prepareCall("BEGIN #{sql}; END;")
      s.registerOutParameter(1, java.sql.Types::BIGINT)
      s.execute
      insert_id = s.getLong(1)
      s.wasNull ? nil : insert_id
    ensure
      # rs.close rescue nil
      s.close rescue nil
    end
  end
end

#get_ruby_value_from_result_set(rset, i, type_name, get_lob_value = true) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 490

def get_ruby_value_from_result_set(rset, i, type_name, get_lob_value = true)
  case type_name
  when :NUMBER
    d = rset.getNUMBER(i)
    if d.nil?
      nil
    elsif d.isInt
      Integer(d.stringValue)
    else
      BigDecimal.new(d.stringValue)
    end
  when :VARCHAR2, :CHAR, :LONG, :NVARCHAR2, :NCHAR
    rset.getString(i)
  when :DATE
    if dt = rset.getDATE(i)
      d = dt.dateValue
      t = dt.timeValue
      if OracleEnhancedAdapter.emulate_dates && t.hours == 0 && t.minutes == 0 && t.seconds == 0
        Date.new(d.year + 1900, d.month + 1, d.date)
      else
        Time.send(Base.default_timezone, d.year + 1900, d.month + 1, d.date, t.hours, t.minutes, t.seconds)
      end
    else
      nil
    end
  when :TIMESTAMP, :TIMESTAMPTZ, :TIMESTAMPLTZ, :"TIMESTAMP WITH TIME ZONE", :"TIMESTAMP WITH LOCAL TIME ZONE"
    ts = rset.getTimestamp(i)
    ts && Time.send(Base.default_timezone, ts.year + 1900, ts.month + 1, ts.date, ts.hours, ts.minutes, ts.seconds,
      ts.nanos / 1000)
  when :CLOB
    get_lob_value ? lob_to_ruby_value(rset.getClob(i)) : rset.getClob(i)
  when :BLOB
    get_lob_value ? lob_to_ruby_value(rset.getBlob(i)) : rset.getBlob(i)
  when :RAW
    raw_value = rset.getRAW(i)
    raw_value && raw_value.getBytes.to_a.pack('C*')
  else
    nil
  end
end

#logoffObject



146
147
148
149
150
151
152
153
154
155
156
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 146

def logoff
  @active = false
  if defined?(@pooled_connection)
    @pooled_connection.close
  else
    @raw_connection.close
  end
  true
rescue
  false
end

#new_connection(config) ⇒ Object

modified method to support JNDI connections



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 59

def new_connection(config)
  username = nil

  if config[:jndi]
    jndi = config[:jndi].to_s
    ctx = javax.naming.InitialContext.new
    ds = nil

    # tomcat needs first lookup method, oc4j (and maybe other application servers) need second method
    begin
      env = ctx.lookup('java:/comp/env')
      ds = env.lookup(jndi)
    rescue
      ds = ctx.lookup(jndi)
    end

    # check if datasource supports pooled connections, otherwise use default
    if ds.respond_to?(:pooled_connection)
      @raw_connection = ds.pooled_connection
    else
      @raw_connection = ds.connection
    end

    # get Oracle JDBC connection when using DBCP in Tomcat or jBoss
    if @raw_connection.respond_to?(:getInnermostDelegate)
      @pooled_connection = @raw_connection
      @raw_connection = @raw_connection.innermost_delegate
    elsif @raw_connection.respond_to?(:getUnderlyingConnection)
      @pooled_connection = @raw_connection
      @raw_connection = @raw_connection.underlying_connection            
    end

    config[:driver] ||= @raw_connection..connection.java_class.name
    username = @raw_connection..user_name
  else
    # to_s needed if username, password or database is specified as number in database.yml file
    username = config[:username] && config[:username].to_s
    password = config[:password] && config[:password].to_s
    database = config[:database] && config[:database].to_s
    host, port = config[:host], config[:port]
    privilege = config[:privilege] && config[:privilege].to_s

    # connection using TNS alias
    if database && !host && !config[:url] && ENV['TNS_ADMIN']
      url = "jdbc:oracle:thin:@#{database || 'XE'}"
    else
      url = config[:url] || "jdbc:oracle:thin:@#{host || 'localhost'}:#{port || 1521}:#{database || 'XE'}"
    end

    prefetch_rows = config[:prefetch_rows] || 100
    # get session time_zone from configuration or from TZ environment variable
    time_zone = config[:time_zone] || ENV['TZ'] || java.util.TimeZone.default.getID

    properties = java.util.Properties.new
    properties.put("user", username)
    properties.put("password", password)
    properties.put("defaultRowPrefetch", "#{prefetch_rows}") if prefetch_rows
    properties.put("internal_logon", privilege) if privilege

    @raw_connection = java.sql.DriverManager.getConnection(url, properties)

    # Set session time zone to current time zone
    @raw_connection.setSessionTimeZone(time_zone)

    # Set default number of rows to prefetch
    # @raw_connection.setDefaultRowPrefetch(prefetch_rows) if prefetch_rows
  end

  cursor_sharing = config[:cursor_sharing] || 'force'
  exec "alter session set cursor_sharing = #{cursor_sharing}"

  # Initialize NLS parameters
  OracleEnhancedAdapter::DEFAULT_NLS_PARAMETERS.each do |key, default_value|
    value = config[key] || ENV[key.to_s.upcase] || default_value
    if value
      exec "alter session set #{key} = '#{value}'"
    end
  end

  self.autocommit = true

  # default schema owner
  @owner = username.upcase unless username.nil?

  @raw_connection
end

#pingObject

Checks connection, returns true if active. Note that ping actively checks the connection, while #active? simply returns the last known state.



177
178
179
180
181
182
183
184
185
186
187
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 177

def ping
  exec_no_retry("select 1 from dual")
  @active = true
rescue NativeException => e
  @active = false
  if e.message =~ /^java\.sql\.SQL(Recoverable)?Exception/
    raise OracleEnhancedConnectionException, e.message
  else
    raise
  end
end

#prepare(sql) ⇒ Object



290
291
292
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 290

def prepare(sql)
  Cursor.new(self, @raw_connection.prepareStatement(sql))
end

#reset!Object

Resets connection, by logging off and creating a new connection.



190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 190

def reset!
  logoff rescue nil
  begin
    new_connection(@config)
    @active = true
  rescue NativeException => e
    @active = false
    if e.message =~ /^java\.sql\.SQL(Recoverable)?Exception/
      raise OracleEnhancedConnectionException, e.message
    else
      raise
    end
  end
end

#returning_clause(quoted_pk) ⇒ Object



249
250
251
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 249

def returning_clause(quoted_pk)
  " RETURNING #{quoted_pk} INTO ?"
end

#rollbackObject



162
163
164
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 162

def rollback
  @raw_connection.rollback
end

#select(sql, name = nil, return_column_names = false) ⇒ Object



431
432
433
434
435
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 431

def select(sql, name = nil, return_column_names = false)
  with_retry do
    select_no_retry(sql, name, return_column_names)
  end
end

#select_no_retry(sql, name = nil, return_column_names = false) ⇒ Object



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 437

def select_no_retry(sql, name = nil, return_column_names = false)
  stmt = @raw_connection.prepareStatement(sql)
  rset = stmt.executeQuery

  # Reuse the same hash for all rows
  column_hash = {}

   = rset.
  column_count = .getColumnCount

  cols_types_index = (1..column_count).map do |i|
    col_name = oracle_downcase(.getColumnName(i))
    next if col_name == 'raw_rnum_'
    column_hash[col_name] = nil
    [col_name, .getColumnTypeName(i).to_sym, i]
  end
  cols_types_index.delete(nil)

  rows = []
  get_lob_value = !(name == 'Writable Large Object')

  while rset.next
    hash = column_hash.dup
    cols_types_index.each do |col, column_type, i|
      hash[col] = get_ruby_value_from_result_set(rset, i, column_type, get_lob_value)
    end
    rows << hash
  end

  return_column_names ? [rows, cols_types_index.map(&:first)] : rows
ensure
  rset.close rescue nil
  stmt.close rescue nil
end

#with_retry(&block) ⇒ Object

mark connection as dead if connection lost



206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 206

def with_retry(&block)
  should_retry = auto_retry? && autocommit?
  begin
    yield if block_given?
  rescue NativeException => e
    raise unless e.message =~ /^java\.sql\.SQL(Recoverable)?Exception: (Closed Connection|Io exception:|No more data to read from socket|IO Error:)/
    @active = false
    raise unless should_retry
    should_retry = false
    reset! rescue nil
    retry
  end
end

#write_lob(lob, value, is_binary = false) ⇒ Object



472
473
474
475
476
477
478
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 472

def write_lob(lob, value, is_binary = false)
  if is_binary
    lob.setBytes(1, value.to_java_bytes)
  else
    lob.setString(1,value)
  end
end