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

Instance Attribute Summary collapse

Attributes inherited from OracleEnhancedConnection

#raw_connection

Instance Method Summary collapse

Methods inherited from OracleEnhancedConnection

create, #oracle_downcase

Constructor Details

#initialize(config) ⇒ OracleEnhancedJDBCConnection

Returns a new instance of OracleEnhancedJDBCConnection.



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

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

Instance Attribute Details

#activeObject Also known as: active?

:nodoc:



40
41
42
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 40

def active
  @active
end

#auto_retryObject Also known as: auto_retry?

Returns the value of attribute auto_retry.



43
44
45
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 43

def auto_retry
  @auto_retry
end

Instance Method Details

#autocommit=(value) ⇒ Object



111
112
113
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 111

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

#autocommit?Boolean

Returns:

  • (Boolean)


107
108
109
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 107

def autocommit?
  @raw_connection.getAutoCommit
end

#commitObject



99
100
101
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 99

def commit
  @raw_connection.commit
end

#describe(name) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 236

def describe(name)
  real_name = OracleEnhancedAdapter.valid_table_name?(name) ? name.to_s.upcase : name.to_s
  if real_name.include?('.')
    table_owner, table_name = real_name.split('.')
  else
    table_owner, table_name = @owner, real_name
  end
  sql = <<-SQL
    SELECT owner, table_name, 'TABLE' name_type
    FROM all_tables
    WHERE owner = '#{table_owner}'
      AND table_name = '#{table_name}'
    UNION ALL
    SELECT owner, view_name table_name, 'VIEW' name_type
    FROM all_views
    WHERE owner = '#{table_owner}'
      AND view_name = '#{table_name}'
    UNION ALL
    SELECT table_owner, table_name, 'SYNONYM' name_type
    FROM all_synonyms
    WHERE owner = '#{table_owner}'
      AND synonym_name = '#{table_name}'
    UNION ALL
    SELECT table_owner, table_name, 'SYNONYM' name_type
    FROM all_synonyms
    WHERE owner = 'PUBLIC'
      AND synonym_name = '#{real_name}'
  SQL
  if result = select_one(sql)
    case result['name_type']
    when 'SYNONYM'
      describe("#{result['owner']}.#{result['table_name']}")
    else
      [result['owner'], result['table_name']]
    end
  else
    raise OracleEnhancedConnectionException, %Q{"DESC #{name}" failed; does it exist?}
  end
end

#error_code(exception) ⇒ Object

Return NativeException / java.sql.SQLException error code



277
278
279
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 277

def error_code(exception)
  exception.cause.getErrorCode
end

#exec(sql) ⇒ Object



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

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

#exec_no_retry(sql) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 167

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()
    s.execute(sql)
    true
  else
    s = @raw_connection.prepareStatement(sql)
    s.execute
    true
  end
ensure
  s.close rescue nil
end

#logoffObject



91
92
93
94
95
96
97
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 91

def logoff
  @active = false
  @raw_connection.close
  true
rescue
  false
end

#new_connection(config) ⇒ Object



53
54
55
56
57
58
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
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 53

def new_connection(config)
  username, password, database = config[:username].to_s, config[:password].to_s, config[:database].to_s
  privilege = config[:privilege] && config[:privilege].to_s
  host, port = config[:host], config[:port]

  url = config[:url] || "jdbc:oracle:thin:@#{host || 'localhost'}:#{port || 1521}:#{database || 'XE'}"

  prefetch_rows = config[:prefetch_rows] || 100
  cursor_sharing = config[:cursor_sharing] || 'similar'
  # by default VARCHAR2 column size will be interpreted as max number of characters (and not bytes)
  nls_length_semantics = config[:nls_length_semantics] || 'CHAR'

  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)
  exec %q{alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'}
  exec %q{alter session set nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS'}
  exec "alter session set cursor_sharing = #{cursor_sharing}"
  exec "alter session set nls_length_semantics = '#{nls_length_semantics}'"
  self.autocommit = true
  
  # Set session time zone to current time zone
  @raw_connection.setSessionTimeZone(java.util.TimeZone.default.getID)
  
  # Set default number of rows to prefetch
  # @raw_connection.setDefaultRowPrefetch(prefetch_rows) if prefetch_rows
  
  # default schema owner
  @owner = username.upcase
  
  @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.



118
119
120
121
122
123
124
125
126
127
128
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 118

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

#reset!Object

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



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 131

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

#rollbackObject



103
104
105
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 103

def rollback
  @raw_connection.rollback
end

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



187
188
189
190
191
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 187

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



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 193

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



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

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

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



228
229
230
231
232
233
234
# File 'lib/active_record/connection_adapters/oracle_enhanced_jdbc_connection.rb', line 228

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