Class: ActiveRecord::ConnectionAdapters::OracleEnhanced::JDBCConnection
- Inherits:
-
Connection
- Object
- Connection
- ActiveRecord::ConnectionAdapters::OracleEnhanced::JDBCConnection
- Defined in:
- lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb
Overview
:nodoc:
Defined Under Namespace
Classes: Cursor
Instance Attribute Summary collapse
-
#active ⇒ Object
(also: #active?)
Returns the value of attribute active.
-
#auto_retry ⇒ Object
(also: #auto_retry?)
Returns the value of attribute auto_retry.
-
#session_time_zone ⇒ Object
readonly
Returns the value of attribute session_time_zone.
Attributes inherited from Connection
Instance Method Summary collapse
- #autocommit=(value) ⇒ Object
- #autocommit? ⇒ Boolean
- #commit ⇒ Object
- #database_version ⇒ Object
-
#describe(name) ⇒ Object
To allow private method called from ‘JDBCConnection`.
-
#error_code(exception) ⇒ Object
Return java.sql.SQLException error code.
- #exec(sql, *bindvars, allow_retry: false) ⇒ Object
- #exec_no_retry(sql) ⇒ Object
- #get_ruby_value_from_result_set(rset, i, type_name, get_lob_value = true) ⇒ Object
-
#initialize(config) ⇒ JDBCConnection
constructor
A new instance of JDBCConnection.
- #logoff ⇒ Object
-
#new_connection(config) ⇒ Object
modified method to support JNDI connections.
-
#ping ⇒ Object
Checks connection, returns true if active.
- #prepare(sql) ⇒ Object
-
#reset ⇒ Object
Resets connection, by logging off and creating a new connection.
- #reset! ⇒ Object
- #rollback ⇒ Object
- #select(sql, name = nil, return_column_names = false) ⇒ Object
- #select_no_retry(sql, name = nil, return_column_names = false) ⇒ Object
-
#with_retry(allow_retry: false, &block) ⇒ Object
mark connection as dead if connection lost.
- #write_lob(lob, value, is_binary = false) ⇒ Object
Methods inherited from Connection
Constructor Details
#initialize(config) ⇒ JDBCConnection
Returns a new instance of JDBCConnection.
66 67 68 69 70 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 66 def initialize(config) @active = true @config = config new_connection(@config) end |
Instance Attribute Details
#active ⇒ Object Also known as: active?
Returns the value of attribute active.
57 58 59 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 57 def active @active end |
#auto_retry ⇒ Object Also known as: auto_retry?
Returns the value of attribute auto_retry.
60 61 62 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 60 def auto_retry @auto_retry end |
#session_time_zone ⇒ Object (readonly)
Returns the value of attribute session_time_zone.
64 65 66 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 64 def session_time_zone @session_time_zone end |
Instance Method Details
#autocommit=(value) ⇒ Object
229 230 231 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 229 def autocommit=(value) @raw_connection.setAutoCommit(value) end |
#autocommit? ⇒ Boolean
225 226 227 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 225 def autocommit? @raw_connection.getAutoCommit end |
#commit ⇒ Object
217 218 219 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 217 def commit @raw_connection.commit end |
#database_version ⇒ Object
321 322 323 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 321 def database_version @database_version ||= (md = raw_connection.getMetaData) && [md.getDatabaseMajorVersion, md.getDatabaseMinorVersion] end |
#describe(name) ⇒ Object
To allow private method called from ‘JDBCConnection`
526 527 528 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 526 def describe(name) super end |
#error_code(exception) ⇒ Object
Return java.sql.SQLException error code
531 532 533 534 535 536 537 538 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 531 def error_code(exception) case exception when Java::JavaSql::SQLException exception.getErrorCode else nil end end |
#exec(sql, *bindvars, allow_retry: false) ⇒ Object
275 276 277 278 279 280 281 282 283 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 275 def exec(sql, *bindvars, allow_retry: false) # The signature mirrors the OCI implementation for polymorphic # callers, but the JDBC path here has no bindvar handling. Fail # loudly rather than silently dropping values on the floor. raise ArgumentError, "JDBC exec does not support bindvars" unless bindvars.empty? with_retry(allow_retry: allow_retry) do exec_no_retry(sql) end end |
#exec_no_retry(sql) ⇒ Object
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 285 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 |
#get_ruby_value_from_result_set(rset, i, type_name, get_lob_value = true) ⇒ Object
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 540 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(d.stringValue) end when :BINARY_FLOAT rset.getFloat(i) when :VARCHAR2, :LONG, :NVARCHAR2 rset.getString(i) when :CHAR, :NCHAR char_str = rset.getString(i) if !char_str.nil? char_str.rstrip end when :DATE if dt = rset.getDATE(i) d = dt.dateValue t = dt.timeValue Time.send(ActiveRecord.default_timezone, d.year + 1900, d.month + 1, d.date, t.hours, t.minutes, t.seconds) else nil end when :TIMESTAMP # Oracle JDBC getTimestamp for plain TIMESTAMP uses the JVM default timezone, # but we store values using the session timezone. Pass a matching Calendar so # the driver interprets the stored wall-clock value in the session timezone. tz_id = @session_time_zone || java.util.TimeZone.default.getID cal = java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone(tz_id)) ts = rset.getTimestamp(i, cal) if ts instant = ts.toInstant t = Time.at(instant.getEpochSecond, instant.getNano, :nanosecond) ActiveRecord.default_timezone == :utc ? t.utc : t.localtime end when :TIMESTAMPTZ, :TIMESTAMPLTZ, :"TIMESTAMP WITH TIME ZONE", :"TIMESTAMP WITH LOCAL TIME ZONE" # TIMESTAMPTZ/TIMESTAMPLTZ include timezone info so getTimestamp returns # the correct UTC epoch without needing a Calendar. ts = rset.getTimestamp(i) if ts instant = ts.toInstant t = Time.at(instant.getEpochSecond, instant.getNano, :nanosecond) ActiveRecord.default_timezone == :utc ? t.utc : t.localtime end when :CLOB get_lob_value ? lob_to_ruby_value(rset.getClob(i)) : rset.getClob(i) when :NCLOB 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 |
#logoff ⇒ Object
205 206 207 208 209 210 211 212 213 214 215 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 205 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
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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 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 73 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. end # Workaround FrozenError (can't modify frozen Hash): config = config.dup 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 || "XE" host, port = config[:host], config[:port] privilege = config[:privilege] && config[:privilege].to_s # connection using TNS alias, or connection-string from DATABASE_URL using_tns_alias = !host && !config[:url] && ENV["TNS_ADMIN"] if database && (using_tns_alias || host == "connection-string") url = "jdbc:oracle:thin:@#{database}" else unless database.match?(/^(:|\/)/) # assume database is a SID if no colon or slash are supplied (backward-compatibility) database = "/#{database}" end url = config[:url] || "jdbc:oracle:thin:@//#{host || 'localhost'}:#{port || 1521}#{database}" 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 raise "username not set" unless username raise "password not set" unless password properties.put("user", username) properties.put("password", password) properties.put("defaultRowPrefetch", "#{prefetch_rows}") if prefetch_rows properties.put("internal_logon", privilege) if privilege if config[:jdbc_connect_properties] # arbitrary additional properties for JDBC connection raise "jdbc_connect_properties should contain an associative array / hash" unless config[:jdbc_connect_properties].is_a? Hash config[:jdbc_connect_properties].each do |key, value| properties.put(key, value) end end begin @raw_connection = java.sql.DriverManager.getConnection(url, properties) rescue # bypass DriverManager to work in cases where ojdbc*.jar # is added to the load path at runtime and not on the # system classpath @raw_connection = ORACLE_DRIVER.connect(url, properties) end # Set session time zone to current time zone if ActiveRecord.default_timezone == :local @raw_connection.setSessionTimeZone(time_zone) @session_time_zone = time_zone elsif ActiveRecord.default_timezone == :utc @raw_connection.setSessionTimeZone("UTC") @session_time_zone = "UTC" end if config[:jdbc_statement_cache_size] raise "Integer value expected for :jdbc_statement_cache_size" unless config[:jdbc_statement_cache_size].instance_of? Integer @raw_connection.setImplicitCachingEnabled(true) @raw_connection.setStatementCacheSize(config[:jdbc_statement_cache_size]) end # 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}" if 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 OracleEnhancedAdapter::FIXED_NLS_PARAMETERS.each do |key, value| exec "alter session set #{key} = '#{value}'" end self.autocommit = true schema = config[:schema] && config[:schema].to_s if schema.blank? # default schema owner @owner = username.upcase unless username.nil? else exec "alter session set current_schema = #{schema}" @owner = schema end @raw_connection end |
#ping ⇒ Object
Checks connection, returns true if active. Note that ping actively checks the connection, while #active? simply returns the last known state.
236 237 238 239 240 241 242 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 236 def ping exec_no_retry("select 1 from dual") @active = true rescue Java::JavaSql::SQLException => e @active = false raise OracleEnhanced::ConnectionException, e. end |
#prepare(sql) ⇒ Object
308 309 310 311 312 313 314 315 316 317 318 319 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 308 def prepare(sql) # Use a plain Statement for DDL and PL/SQL blocks: PreparedStatement # interprets colons as bind-parameter markers which breaks trigger # definitions (:NEW/:OLD) and PL/SQL with named parameters. if /\A\s*(CREATE|DROP|BEGIN|DECLARE)/i.match?(sql) s = @raw_connection.createStatement() s.setEscapeProcessing(false) Cursor.new(self, s, sql) else Cursor.new(self, @raw_connection.prepareStatement(sql)) end end |
#reset ⇒ Object
Resets connection, by logging off and creating a new connection.
245 246 247 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 245 def reset reset! end |
#reset! ⇒ Object
249 250 251 252 253 254 255 256 257 258 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 249 def reset! logoff rescue nil begin new_connection(@config) @active = true rescue Java::JavaSql::SQLException => e @active = false raise OracleEnhanced::ConnectionException, e. end end |
#rollback ⇒ Object
221 222 223 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 221 def rollback @raw_connection.rollback end |
#select(sql, name = nil, return_column_names = false) ⇒ Object
476 477 478 479 480 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 476 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
482 483 484 485 486 487 488 489 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 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 482 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.getMetaData 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(allow_retry: false, &block) ⇒ Object
mark connection as dead if connection lost
261 262 263 264 265 266 267 268 269 270 271 272 273 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 261 def with_retry(allow_retry: false, &block) should_retry = (allow_retry || auto_retry?) && autocommit? begin yield if block_given? rescue Java::JavaSql::SQLException => e raise unless /^(Closed Connection|Io exception:|No more data to read from socket|IO Error:|ORA-03113:|ORA-03114:|ORA-17008:)/.match?(e.) @active = false raise unless should_retry should_retry = false reset! rescue nil retry end end |
#write_lob(lob, value, is_binary = false) ⇒ Object
517 518 519 520 521 522 523 |
# File 'lib/active_record/connection_adapters/oracle_enhanced/jdbc_connection.rb', line 517 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 |