Class: ActiveRecord::ConnectionAdapters::IBM_DBAdapter

Inherits:
AbstractAdapter
  • Object
show all
Includes:
QueryCache
Defined in:
lib/active_record/connection_adapters/ibm_db_adapter.rb,
lib/active_record/connection_adapters/ibm_db_pstmt.rb

Overview

The IBM_DB Adapter requires the native Ruby driver (ibm_db) for IBM data servers (ibm_db.so). config the hash passed as an initializer argument content:

mandatory parameters

adapter:         'ibm_db'        // IBM_DB Adapter name
username:        'db2user'       // data server (database) user
password:        'secret'        // data server (database) password
database:        'ARUNIT'        // remote database name (or catalog entry alias)

optional (highly recommended for data server auditing and monitoring purposes)

schema:          'rails123'      // name space qualifier
account:         'tester'        // OS account (client workstation)
app_user:        'test11'        // authenticated application user
application:     'rtests'        // application name
workstation:     'plato'         // client workstation name

remote TCP/IP connection (required when no local database catalog entry available)

host:            'socrates'      // fully qualified hostname or IP address
port:            '50000'         // data server TCP/IP port number
security:        'SSL'           // optional parameter enabling SSL encryption -
                                 // - Available only from CLI version V95fp2 and above
authentication:  'SERVER'        // AUTHENTICATION type which the client uses - 
                                 // - to connect to the database server. By default value is SERVER
timeout:         10              // Specifies the time in seconds (0 - 32767) to wait for a reply from server -
                                 //- when trying to establish a connection before generating a timeout

Parameterized Queries Support

parameterized:  false            // Specifies if the prepared statement support of 
                                 //- the IBM_DB Adapter is to be turned on or off

When schema is not specified, the username value is used instead. The default setting of parameterized is false.

Defined Under Namespace

Classes: BindSubstitution

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from QueryCache

included, #prepared_select_with_query_cache

Constructor Details

#initialize(connection, ar3, logger, config, conn_options) ⇒ IBM_DBAdapter

Returns a new instance of IBM_DBAdapter.



750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 750

def initialize(connection, ar3, logger, config, conn_options)
  # Caching database connection configuration (+connect+ or +reconnect+ support)\
	@config = config
  @connection       = connection
		@isAr3            = ar3
  @conn_options     = conn_options
  @database         = config[:database]
  @username         = config[:username]
  @password         = config[:password]
  if config.has_key?(:host)
    @host           = config[:host]
    @port           = config[:port] || 50000 # default port
  end
  @schema           = config[:schema]
  @security         = config[:security] || nil
  @authentication   = config[:authentication] || nil
  @timeout          = config[:timeout] || 0  # default timeout value is 0

  @app_user = @account = @application = @workstation = nil
  # Caching database connection options (auditing and billing support)
  @app_user         = conn_options[:app_user]     if conn_options.has_key?(:app_user)
  @account          = conn_options[:account]      if conn_options.has_key?(:account)
  @application      = conn_options[:application]  if conn_options.has_key?(:application)
  @workstation      = conn_options[:workstation]  if conn_options.has_key?(:workstation)
  
  @sql                  = []
  @sql_parameter_values = [] #Used only if pstmt support is turned on

  @handle_lobs_triggered = false

  # Calls the parent class +ConnectionAdapters+' initializer
  # which sets @connection, @logger, @runtime and @last_verification
  super(@connection, logger, @config)

  if @connection
    server_info = IBM_DB.server_info( @connection )
    if( server_info )
      case server_info.DBMS_NAME
        when /DB2\//i             # DB2 for Linux, Unix and Windows (LUW)
          case server_info.DBMS_VER
            when /09.07/i          # DB2 Version 9.7 (Cobra)
              @servertype = IBM_DB2_LUW_COBRA.new(self, @isAr3)
            when /10./i #DB2 version 10.1 and above
              @servertype = IBM_DB2_LUW_COBRA.new(self, @isAr3)
            else                  # DB2 Version 9.5 or below
              @servertype = IBM_DB2_LUW.new(self, @isAr3)
          end
        when /DB2/i               # DB2 for zOS
          case server_info.DBMS_VER
            when /09/             # DB2 for zOS version 9 and version 10
              @servertype = IBM_DB2_ZOS.new(self, @isAr3)
            when /10/
              @servertype = IBM_DB2_ZOS.new(self, @isAr3)
            when /08/             # DB2 for zOS version 8
              @servertype = IBM_DB2_ZOS_8.new(self, @isAr3)
            else                  # DB2 for zOS version 7
              raise "Only DB2 z/OS version 8 and above are currently supported"
          end
        when /AS/i                # DB2 for i5 (iSeries)
          @servertype = IBM_DB2_I5.new(self, @isAr3)
        when /IDS/i               # Informix Dynamic Server
          @servertype = IBM_IDS.new(self, @isAr3)
        else
          log( "server_info", "Forcing servertype to LUW: DBMS name could not be retrieved. Check if your client version is of the right level")
          warn "Forcing servertype to LUW: DBMS name could not be retrieved. Check if your client version is of the right level"
          @servertype = IBM_DB2_LUW.new(self, @isAr3)
      end
    else
      error_msg = IBM_DB.getErrormsg( @connection, IBM_DB::DB_CONN )
      IBM_DB.close( @connection )
      raise "Cannot retrieve server information: #{error_msg}"
    end
  end

  # Executes the +set schema+ statement using the schema identifier provided
  @servertype.set_schema(@schema) if @schema && @schema != @username

  # Check for the start value for id (primary key column). By default it is 1
  if config.has_key?(:start_id)
    @start_id = config[:start_id]
  else
    @start_id = 1
  end

  #Check Arel version
  begin
    @arelVersion = Arel::VERSION.to_i
  rescue
    @arelVersion = 0
  end

  if(@arelVersion >=  3 )
    @visitor = Arel::Visitors::IBM_DB.new self
  end
		
  if(config.has_key?(:parameterized) && config[:parameterized] == true)			 
    @pstmt_support_on = true
    @prepared_statements = true
    @set_quoted_literal_replacement = IBM_DB::QUOTED_LITERAL_REPLACEMENT_OFF
  else		  
    @pstmt_support_on = false
    @prepared_statements = false
    @set_quoted_literal_replacement = IBM_DB::QUOTED_LITERAL_REPLACEMENT_ON
  end
end

Instance Attribute Details

#accountObject

Returns the value of attribute account.



738
739
740
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 738

def 
  @account
end

#app_userObject

Returns the value of attribute app_user.



738
739
740
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 738

def app_user
  @app_user
end

#applicationObject

Returns the value of attribute application.



738
739
740
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 738

def application
  @application
end

#connectionObject (readonly)

Returns the value of attribute connection.



736
737
738
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 736

def connection
  @connection
end

#handle_lobs_triggeredObject

Returns the value of attribute handle_lobs_triggered.



737
738
739
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 737

def handle_lobs_triggered
  @handle_lobs_triggered
end

#pstmt_support_onObject (readonly)

Returns the value of attribute pstmt_support_on.



739
740
741
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 739

def pstmt_support_on
  @pstmt_support_on
end

#schemaObject

Returns the value of attribute schema.



738
739
740
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 738

def schema
  @schema
end

#servertypeObject (readonly)

Returns the value of attribute servertype.



736
737
738
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 736

def servertype
  @servertype
end

#set_quoted_literal_replacementObject (readonly)

Returns the value of attribute set_quoted_literal_replacement.



739
740
741
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 739

def set_quoted_literal_replacement
  @set_quoted_literal_replacement
end

#sqlObject

Returns the value of attribute sql.



737
738
739
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 737

def sql
  @sql
end

#sql_parameter_valuesObject

Returns the value of attribute sql_parameter_values.



737
738
739
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 737

def sql_parameter_values
  @sql_parameter_values
end

#workstationObject

Returns the value of attribute workstation.



738
739
740
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 738

def workstation
  @workstation
end

Class Method Details

.visitor_for(pool) ⇒ Object



904
905
906
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 904

def self.visitor_for(pool)
  Arel::Visitors::IBM_DB.new(pool)
end

Instance Method Details

#active?Boolean

Tests the connection status

Returns:

  • (Boolean)


959
960
961
962
963
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 959

def active?
  IBM_DB.active @connection
  rescue
    false
end

#adapter_nameObject

Name of the adapter



742
743
744
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 742

def adapter_name
  'IBM_DB'
end

#add_limit_offset!(sql, options) ⇒ Object

Modifies a sql statement in order to implement a LIMIT and an OFFSET. A LIMIT defines the number of rows that should be fetched, while an OFFSET defines from what row the records must be fetched. IBM data servers implement a LIMIT in SQL statements through: FETCH FIRST n ROWS ONLY, where n is the number of rows required. The implementation of OFFSET is more elaborate, and requires the usage of subqueries and the ROW_NUMBER() command in order to add row numbering as an additional column to a copy of the existing table.

Examples

add_limit_offset!(‘SELECT * FROM staff’, => 10) generates: “SELECT * FROM staff FETCH FIRST 10 ROWS ONLY”

add_limit_offset!(‘SELECT * FROM staff’, => 10, :offset => 30) generates “SELECT O.* FROM (SELECT I.*, ROW_NUMBER() OVER () sys_rownum FROM (SELECT * FROM staff) AS I) AS O WHERE sys_row_num BETWEEN 31 AND 40”



1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1545

def add_limit_offset!(sql, options)
  limit = options[:limit]
  offset = options[:offset]

  # if the limit is zero
  if limit && limit == 0
    # Returns a query that will always generate zero records
    # (e.g. WHERE sys_row_num BETWEEN 1 and 0)
    if( @pstmt_support_on )
      sql = @servertype.query_offset_limit!(sql, 0, limit, options)
    else
      sql = @servertype.query_offset_limit(sql, 0, limit)
    end
  # If there is a non-zero limit
  else
    # If an offset is specified builds the query with offset and limit,
    # otherwise retrieves only the first +limit+ rows
    if( @pstmt_support_on )
      sql = @servertype.query_offset_limit!(sql, offset, limit, options)
    else
      sql = @servertype.query_offset_limit(sql, offset, limit)
    end
  end
  # Returns the sql query in any case
  sql
end

#alter_foreign_keys(tables, not_enforced) ⇒ Object



2379
2380
2381
2382
2383
2384
2385
2386
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2379

def alter_foreign_keys(tables, not_enforced)
     enforced = not_enforced ? 'NOT ENFORCED' : 'ENFORCED'
     tables.each do |table|
       foreign_keys(table).each do |fk|
         execute("ALTER TABLE #{@servertype.set_case(fk.from_table)} ALTER FOREIGN KEY #{@servertype.set_case(fk.name)} #{enforced}")			
       end
     end
end

#begin_db_transactionObject

Begins the transaction (and turns off auto-committing)



1499
1500
1501
1502
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1499

def begin_db_transaction
  # Turns off the auto-commit
  IBM_DB.autocommit(@connection, IBM_DB::SQL_AUTOCOMMIT_OFF)
end

#build_conn_str_for_dbopsObject



1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1748

def build_conn_str_for_dbops()
  connect_str = "DRIVER={IBM DB2 ODBC DRIVER};ATTACH=true;"
  if(!@host.nil?)
    connect_str << "HOSTNAME=#{@host};"
    connect_str << "PORT=#{@port};"
    connect_str << "PROTOCOL=TCPIP;"
  end
  connect_str << "UID=#{@username};PWD=#{@password};"
  return connect_str
end

#change_column(table_name, column_name, type, options = {}) ⇒ Object

Changes the column’s definition according to the new options. See TableDefinition#column for details of the options you can use.

Examples
change_column(:suppliers, :name, :string, :limit => 80)
change_column(:accounts, :description, :text)


2420
2421
2422
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2420

def change_column(table_name, column_name, type, options = {})
  @servertype.change_column(table_name, column_name, type, options)
end

#change_column_default(table_name, column_name, default) ⇒ Object

Sets a new default value for a column. This does not set the default value to NULL, instead, it needs DatabaseStatements#execute which can execute the appropriate SQL statement for setting the value.

Examples

change_column_default(:suppliers, :qualification, 'new')
change_column_default(:accounts, :authorized, 1)

Method overriden to satisfy IBM data servers syntax.



2451
2452
2453
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2451

def change_column_default(table_name, column_name, default)
  @servertype.change_column_default(table_name, column_name, default)
end

#change_column_null(table_name, column_name, null, default = nil) ⇒ Object

Changes the nullability value of a column



2456
2457
2458
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2456

def change_column_null(table_name, column_name, null, default = nil)
  @servertype.change_column_null(table_name, column_name, null, default)
end

#columns(table_name) ⇒ Object

Returns an array of Column objects for the table specified by table_name



2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2195

def columns(table_name)
# to_s required because it may be a symbol.
  table_name = @servertype.set_case(table_name.to_s)
				
  # Checks if a blank table name has been given.
  # If so it returns an empty array
  return [] if table_name.strip.empty?
  # +columns+ will contain the resulting array
  columns = []
  # Statement required to access all the columns information
  stmt = IBM_DB.columns( @connection, nil, 
                             @servertype.set_case(@schema), 
                             @servertype.set_case(table_name) )
  if(stmt)
    begin
      # Fetches all the columns and assigns them to col.
      # +col+ is an hash with keys/value pairs for a column
      while col = IBM_DB.fetch_assoc(stmt)
        column_name = col["column_name"].downcase
        # Assigns the column default value.
        column_default_value = col["column_def"]
        # If there is no default value, it assigns NIL
        column_default_value = nil if (column_default_value && column_default_value.upcase == 'NULL')
        # If default value is IDENTITY GENERATED BY DEFAULT (this value is retrieved in case of id columns)
        column_default_value = nil if (column_default_value && column_default_value.upcase =~ /IDENTITY GENERATED BY DEFAULT/i)
        # Removes single quotes from the default value
        column_default_value.gsub!(/^'(.*)'$/, '\1') unless column_default_value.nil?
        # Assigns the column type
        column_type = col["type_name"].downcase
        # Assigns the field length (size) for the column
			  
			  original_column_type = "#{column_type}"
			  
        column_length = col["column_size"]
        column_scale = col["decimal_digits"]
        # The initializer of the class Column, requires the +column_length+ to be declared 
        # between brackets after the datatype(e.g VARCHAR(50)) for :string and :text types. 
        # If it's a "for bit data" field it does a subsitution in place, if not
        # it appends the (column_length) string on the supported data types
        unless column_length.nil? || 
               column_length == '' || 
               column_type.sub!(/ \(\) for bit data/i,"(#{column_length}) FOR BIT DATA") || 
               !column_type =~ /char|lob|graphic/i
          if column_type =~ /decimal/i
            column_type << "(#{column_length},#{column_scale})"
          elsif column_type =~ /smallint|integer|double|date|time|timestamp|xml|bigint/i
            column_type << ""  # override native limits incompatible with table create
          else
            column_type << "(#{column_length})"
          end
        end
        # col["NULLABLE"] is 1 if the field is nullable, 0 if not.
        column_nullable = (col["nullable"] == 1) ? true : false
        # Make sure the hidden column (db2_generated_rowid_for_lobs) in DB2 z/OS isn't added to the list
        if !(column_name =~ /db2_generated_rowid_for_lobs/i)
          # Pushes into the array the *IBM_DBColumn* object, created by passing to the initializer
          # +column_name+, +default_value+, +column_type+ and +column_nullable+.
          #if(@arelVersion >=  6 )				
			
 #cast_type = lookup_cast_type(column_type)
				
				ruby_type = simplified_type2(column_type)
				precision = extract_precision(ruby_type)
				
				#type = type_map.lookup(column_type)
				sql_type = type_to_sql(column_type, column_length, precision, column_scale)
					  
				 = SqlTypeMetadata.new(					
					#sql_type: sql_type,
					sql_type: original_column_type,
					type: ruby_type,
					limit: column_length,
					precision: precision,
					scale: column_scale,
				)
				
				columns << Column.new(column_name, column_default_value, , column_nullable, table_name)
			
				#else
				#	columns << IBM_DBColumn.new(column_name, column_default_value, column_type, column_nullable)
				#end
        end
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve column metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of column metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure  # Free resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  else  # Handle driver execution errors
    error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve column metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during retrieval of columns metadata')
    end
  end
  # Returns the columns array
  return columns
end

#columns_for_distinct(columns, orders) ⇒ Object

:nodoc:



2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2433

def columns_for_distinct(columns, orders) #:nodoc:
  order_columns = orders.reject(&:blank?).map{ |s|
	  # Convert Arel node to string
	  s = s.to_sql unless s.is_a?(String)
	  # Remove any ASC/DESC modifiers
	  s.gsub(/\s+(?:ASC|DESC)\b/i, '')
	   .gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, '')
	}.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" }			
  [super, *order_columns].join(', ')
end

#commit_db_transactionObject

Commits the transaction and turns on auto-committing



1505
1506
1507
1508
1509
1510
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1505

def commit_db_transaction
  # Commits the transaction
  IBM_DB.commit @connection rescue nil
  # Turns on auto-committing
  IBM_DB.autocommit @connection, IBM_DB::SQL_AUTOCOMMIT_ON
end

#create_database(dbName, codeSet = nil, mode = nil) ⇒ Object



1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1782

def create_database(dbName, codeSet=nil, mode=nil)
  connect_str = build_conn_str_for_dbops()

  #Ensure connection is closed before trying to drop a database.
  #As a connect call would have been made by call seeing connection in active
  disconnect!

  begin
    createConn = IBM_DB.connect(connect_str, '', '')
  rescue StandardError => connect_err
    raise "Failed to connect to server due to: #{connect_err}"
  end

  if(IBM_DB.createDB(createConn,dbName,codeSet,mode))
    IBM_DB.close(createConn)
    return true
  else
    error = IBM_DB.getErrormsg(createConn, IBM_DB::DB_CONN)
    IBM_DB.close(createConn)
    raise "Could not create Database due to: #{error}"
  end
end

#create_table(name, options = {}) ⇒ Object

DATABASE STATEMENTS



1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1023

def create_table(name, options = {})
  @servertype.setup_for_lob_table
  #Table definition is complete only when a unique index is created on the primarykey column for DB2 V8 on zOS
  
  #create index on id column if options[:id] is nil or id ==true
  #else check if options[:primary_key]is not nil then create an unique index on that column
  if  !options[:id].nil? || !options[:primary_key].nil?
    if (!options[:id].nil? && options[:id] == true)
        @servertype.create_index_after_table(name,"id")
    elsif !options[:primary_key].nil?
        @servertype.create_index_after_table(name,options[:primary_key].to_s)
    end
  else
      @servertype.create_index_after_table(name,"id")
  end
    super(name, options)
end

#default_sequence_name(table, column) ⇒ Object

method add_limit_offset!



1572
1573
1574
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1572

def default_sequence_name(table, column) # :nodoc:
  "#{table}_#{column}_seq"
end

#disable_referential_integrityObject

:nodoc:



2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2366

def disable_referential_integrity #:nodoc:
    if supports_disable_referential_integrity?
      alter_foreign_keys(tables, true)
    end

    yield
  ensure
    if supports_disable_referential_integrity?
      alter_foreign_keys(tables, false)
    end
		
end

#disconnect!Object

Closes the current connection



1010
1011
1012
1013
1014
1015
1016
1017
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1010

def disconnect!
  # Attempts to close the connection. The methods will return:
  # * true if succesfull
  # * false if the connection is already closed
  # * nil if an error is raised
  return nil if @connection.nil? || @connection == false
  IBM_DB.close(@connection) rescue nil
end

#distinct(columns, order_by) ⇒ Object

Add distinct clause to the sql if there is no order by specified



2425
2426
2427
2428
2429
2430
2431
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2425

def distinct(columns, order_by)
  if order_by.nil?
    "DISTINCT #{columns}" 
  else
    "#{columns}"
  end
end

#drop_database(dbName) ⇒ Object



1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1759

def drop_database(dbName)
  connect_str = build_conn_str_for_dbops()

  #Ensure connection is closed before trying to drop a database. 
  #As a connect call would have been made by call seeing connection in active
  disconnect!

  begin
    dropConn = IBM_DB.connect(connect_str, '', '')
  rescue StandardError => connect_err
    raise "Failed to connect to server due to: #{connect_err}"
  end

  if(IBM_DB.dropDB(dropConn,dbName))
    IBM_DB.close(dropConn)
    return true
  else
    error = IBM_DB.getErrormsg(dropConn, IBM_DB::DB_CONN)
    IBM_DB.close(dropConn)
    raise "Could not drop Database due to: #{error}"
  end
end

#empty_insert_statement_value(pkey) ⇒ Object



1264
1265
1266
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1264

def empty_insert_statement_value(pkey)
  "(#{pkey}) VALUES (DEFAULT)"
end

#exec_insert(sql, name, binds, pk, sequence_name) ⇒ Object



1407
1408
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1407

def exec_insert(sql,name,binds,pk,sequence_name)
end

#exec_query(sql, name = 'SQL', binds = []) ⇒ Object

Executes sql statement in the context of this connection using binds as the bind substitutes. name is logged along with the executed sql statement.



1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1376

def exec_query(sql, name = 'SQL', binds = [])
  begin
    param_array = binds.map do |column,value|
      quote_value_for_pstmt(value, column)
    end

    stmt = prepare(sql, name)

     if( stmt )
       if(execute_prepared_stmt(stmt, param_array))
         return stmt
       end
     else
       return false
     end
  ensure
    @offset = @limit = nil
  end
end

#execute(sql, name = nil) ⇒ Object

Executes and logs sql commands and returns a IBM_DB.Statement object.



1398
1399
1400
1401
1402
1403
1404
1405
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1398

def execute(sql, name=nil)
  # Logs and execute the sql instructions.
  # The +log+ method is defined in the parent class +AbstractAdapter+
	#sql='INSERT INTO ar_internal_metadata (key, value, created_at, updated_at) VALUES ('10', '10', '10', '10')
  log(sql , name) do
    @servertype.execute(sql, name)
  end
end

#execute_prepared_stmt(pstmt, param_array = nil) ⇒ Object

Praveen Executes the prepared statement ReturnsTrue on success and False on Failure



1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1354

def execute_prepared_stmt(pstmt, param_array = nil)
  if !param_array.nil? && param_array.size < 1
    param_array = nil
  end

  if( !IBM_DB.execute(pstmt, param_array) )
    error_msg = IBM_DB.getErrormsg(pstmt, IBM_DB::DB_STMT)
    if !error_msg.empty?
      error_msg = "Statement execution failed: " + error_msg
    else
      error_msg = "Statement execution failed"
    end
    IBM_DB.free_stmt(pstmt) if pstmt
    raise StatementInvalid, error_msg
  else
    return true
  end
end

#extract_foreign_key_action(specifier) ⇒ Object

:nodoc:



2353
2354
2355
2356
2357
2358
2359
2360
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2353

def extract_foreign_key_action(specifier) # :nodoc:	      			
 case specifier
       when 0; :cascade
 when 1; :restrict
 when 2; :nullify
 when 3; :noaction		  
       end
end

#fetch_data(stmt) ⇒ Object

Calls the servertype select method to fetch the data



1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1108

def fetch_data(stmt)
  if(stmt)
    begin
      return @servertype.select(stmt)
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise StatementInvalid,"Failed to retrieve data: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during data retrieval"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure
    # Ensures to free the resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  end
end

#foreign_keys(table_name) ⇒ Object



2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2302

def foreign_keys(table_name)	  
    #fetch the foreign keys of the table using function foreign_keys        
		#PKTABLE_NAME::  fk_row[2] Name of the table containing the primary key.
		#PKCOLUMN_NAME:: fk_row[3] Name of the column containing the primary key.		
		#FKTABLE_NAME::  fk_row[6] Name of the table containing the foreign key.
		#FKCOLUMN_NAME:: fk_row[7] Name of the column containing the foreign key.		
		#FK_NAME:: 		 fk_row[11] The name of the foreign key.
			
		table_name = @servertype.set_case(table_name.to_s)
		foreignKeys = []
    stmt = IBM_DB.foreignkeys( @connection, nil, 
                               @servertype.set_case(@schema), 
                               @servertype.set_case(table_name), "FK_TABLE")								
		
    if(stmt)
      begin
        while ( fk_row = IBM_DB.fetch_array(stmt) )			  
          options = {
column: fk_row[7],
name: fk_row[11],
primary_key: fk_row[3],
 }			  			  			  
 options[:on_update] = extract_foreign_key_action(fk_row[9])	
 options[:on_delete] = extract_foreign_key_action(fk_row[10])
 foreignKeys << ForeignKeyDefinition.new(fk_row[6], table_name, options) 
        end			

      rescue StandardError => fetch_error # Handle driver fetch errors
        error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
        if error_msg && !error_msg.empty?
          raise "Failed to retrieve foreign key metadata during fetch: #{error_msg}"
        else
          error_msg = "An unexpected error occurred during retrieval of foreign key metadata"
          error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
          raise error_msg
        end
      ensure  # Free resources associated with the statement
        IBM_DB.free_stmt(stmt) if stmt
      end
    else  # Handle driver execution errors
      error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve foreign key metadata due to error: #{error_msg}"
      else
        raise StandardError.new('An unexpected error occurred during foreign key retrieval')		
      end		  
    end
#Returns the foreignKeys array
return foreignKeys
end

#get_limit_offset_clauses(limit, offset) ⇒ Object



1521
1522
1523
1524
1525
1526
1527
1528
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1521

def get_limit_offset_clauses(limit,offset)

  if limit && limit == 0
    clauses = @servertype.get_limit_offset_clauses(limit,0)
  else
    clauses = @servertype.get_limit_offset_clauses(limit, offset)
  end
end

#indexes(table_name, name = nil) ⇒ Object

Returns an array of non-primary key indexes for a specified table name



1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1992

def indexes(table_name, name = nil)
  # to_s required because +table_name+ may be a symbol.
  table_name = table_name.to_s
  # Checks if a blank table name has been given.
  # If so it returns an empty array of columns.
  return [] if table_name.strip.empty?

  indexes = []
  pk_index = nil
  index_schema = []
  
  #fetch the primary keys of the table using function primary_keys
  #TABLE_SCHEM:: pk_index[1]
  #TABLE_NAME:: pk_index[2]
  #COLUMN_NAME:: pk_index[3]
  #PK_NAME:: pk_index[5]
  stmt = IBM_DB.primary_keys( @connection, nil, 
                             @servertype.set_case(@schema), 
                             @servertype.set_case(table_name))
  if(stmt)
    begin
      while ( pk_index_row = IBM_DB.fetch_array(stmt) )
        if pk_index_row[5] 
          pk_index_name = pk_index_row[5].downcase
          pk_index_columns = [pk_index_row[3].downcase]           # COLUMN_NAME
          if pk_index 
            pk_index.columns = pk_index.columns + pk_index_columns
          else
            pk_index = IndexDefinition.new(table_name, pk_index_name, true, pk_index_columns)
          end
        end 
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve primarykey metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of primary key metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure  # Free resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  else  # Handle driver execution errors
    error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve primary key metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during primary key retrieval')
    end
  end

  # Query table statistics for all indexes on the table
  # "TABLE_NAME:   #{index_stats[2]}"
  # "NON_UNIQUE:   #{index_stats[3]}"
  # "INDEX_NAME:   #{index_stats[5]}"
  # "COLUMN_NAME:  #{index_stats[8]}"
  stmt = IBM_DB.statistics( @connection, nil, 
                            @servertype.set_case(@schema), 
                            @servertype.set_case(table_name), 1 )
  if(stmt)
    begin
      while ( index_stats = IBM_DB.fetch_array(stmt) )
        is_composite = false
        if index_stats[5]             # INDEX_NAME
          index_name = index_stats[5].downcase
          index_unique = (index_stats[3] == 0)
          index_columns = [index_stats[8].downcase]     # COLUMN_NAME
          index_qualifier = index_stats[4].downcase             #Index_Qualifier
          # Create an IndexDefinition object and add to the indexes array
          i = 0;
          indexes.each do |index|
            if index.name == index_name && index_schema[i] == index_qualifier
               #index.columns = index.columns + index_columns
               index.columns.concat index_columns
               is_composite = true
            end 
            i = i+1
          end
        
          unless is_composite 
            indexes << IndexDefinition.new(table_name, index_name, index_unique, index_columns)
            index_schema << index_qualifier
          end 
        end
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve index metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of index metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure  # Free resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  else  # Handle driver execution errors
    error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve index metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during index retrieval')
    end
  end
    
  # remove the primary key index entry.... should not be dumped by the dumper
    
  i = 0
  indexes.each do |index|
    if pk_index && index.columns == pk_index.columns
      indexes.delete_at(i)
    end
    i = i+1
  end 
  # Returns the indexes array
  return indexes
end

#insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) ⇒ Object



1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1290

def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds=[])
  if(@arelVersion <  6)
  sql, binds = [to_sql(arel), binds]
 else
  sql, binds = [to_sql(arel),binds] #sql_for_insert(to_sql(arel, binds), binds) #[to_sql(arel),binds]
 end

  #unless IBM_DBAdapter.respond_to?(:exec_insert)
  if binds.nil? || binds.empty?
    return insert_direct(sql, name, pk, id_value, sequence_name)
  end

  clear_query_cache if defined? clear_query_cache
    
		if stmt = exec_insert(sql, name, binds)
    begin
      @sql << sql
      return id_value || @servertype.last_generated_id(stmt)
    ensure
      IBM_DB.free_stmt(stmt) if stmt
    end
  end
end

#insert_direct(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) ⇒ Object

Perform an insert and returns the last ID generated. This can be the ID passed to the method or the one auto-generated by the database, and retrieved by the last_generated_id method.



1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1271

def insert_direct(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
  if @handle_lobs_triggered  #Ensure the array of sql is cleared if they have been handled in the callback
    @sql = []
    @handle_lobs_triggered = false
  end

  clear_query_cache if defined? clear_query_cache

  if stmt = execute(sql, name)
    begin
      @sql << sql
      return id_value || @servertype.last_generated_id(stmt)
      # Ensures to free the resources associated with the statement
    ensure
      IBM_DB.free_stmt(stmt) if stmt
    end
  end
end

#insert_fixture(fixture, table_name) ⇒ Object

inserts values from fixtures overridden to handle LOB’s fixture insertion, as, in normal inserts callbacks are triggered but during fixture insertion callbacks are not triggered hence only markers like @@@IBMBINARY@@@ will be inserted and are not updated to actual data



1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1203

def insert_fixture(fixture, table_name)
  if(fixture.respond_to?(:keys))
    insert_query = "INSERT INTO #{quote_table_name(table_name)} ( #{fixture.keys.join(', ')})"
  else
    insert_query = "INSERT INTO #{quote_table_name(table_name)} ( #{fixture.key_list})"
  end

  insert_values = []
  params = []
  if @servertype.instance_of? IBM_IDS
    super
    return
  end
  column_list = columns(table_name)
  fixture.each do |item|
    col = nil
    column_list.each do |column|
      if column.name.downcase == item.at(0).downcase
        col= column
        break
      end
    end
		  
    if item.at(1).nil? || 
        item.at(1) == {} || 			  
			  (item.at(1) == '' && !(col.sql_type.to_s =~ /text|clob/i))
          params << 'NULL'
				
		  elsif (!col.nil? &&  (col.sql_type.to_s =~ /blob|binary|clob|text|xml/i)  )			
      #  Add a '?' for the parameter or a NULL if the value is nil or empty 
      # (except for a CLOB field where '' can be a value)
       insert_values << quote_value_for_pstmt(item.at(1))
       params << '?'
    else
      insert_values << quote_value_for_pstmt(item.at(1),col)
      params << '?'
    end 
  end
    
  insert_query << " VALUES ("+ params.join(',') + ")"
  unless stmt = IBM_DB.prepare(@connection, insert_query)
     error_msg = IBM_DB.getErrormsg( @connection, IBM_DB::DB_CONN )
     if error_msg && !error_msg.empty?
       raise "Failed to prepare statement for fixtures insert due to : #{error_msg}"
     else
       raise StandardError.new('An unexpected error occurred during preparing SQL for fixture insert')
     end
  end
    
  #log_query(insert_query,'fixture insert')
  log(insert_query,'fixture insert') do
    unless IBM_DB.execute(stmt, insert_values)
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      IBM_DB.free_stmt(stmt) if stmt
      raise "Failed to insert due to: #{error_msg}"
    else
      IBM_DB.free_stmt(stmt) if stmt
    end
  end
end

#log_query(sql, name) ⇒ Object

:nodoc:



949
950
951
952
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 949

def log_query(sql, name) #:nodoc:
  # Used by handle_lobs
  log(sql,name){}
end

#native_database_typesObject

Returns a Hash of mappings from the abstract data types to the native database types



1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1718

def native_database_types
  {
    :primary_key => { :name => @servertype.primary_key_definition(@start_id)},
    :string      => { :name => "varchar", :limit => 255 },
    :text        => { :name => "clob" },
    :integer     => { :name => "integer" },
    :float       => { :name => "float" },
    :datetime    => { :name => "timestamp" },
    :timestamp   => { :name => "timestamp" },		  
    :time        => { :name => "time" },
    :date        => { :name => "date" },
    :binary      => { :name => "blob" },

    # IBM data servers don't have a native boolean type.
    # A boolean can be represented  by a smallint,
    # adopting the convention that False is 0 and True is 1
    :boolean     => { :name => "smallint"},
    :xml         => { :name => "xml"},
    :decimal     => { :name => "decimal" },
    :rowid       => { :name => "rowid" }, # rowid is a supported datatype on z/OS and i/5
    :serial      => { :name => "serial" }, # rowid is a supported datatype on Informix Dynamic Server
    :char        => { :name => "char" },
    :double      => { :name => @servertype.get_double_mapping },
    :decfloat    => { :name => "decfloat"},
    :graphic     => { :name => "graphic", :limit => 1},
    :vargraphic  => { :name => "vargraphic", :limit => 1},
    :bigint      => { :name => "bigint"}
  }
end

#prepare(sql, name = nil) ⇒ Object

Praveen Prepares and logs sql commands and returns a IBM_DB.Statement object.



1343
1344
1345
1346
1347
1348
1349
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1343

def prepare(sql,name = nil)
  # The +log+ method is defined in the parent class +AbstractAdapter+
  @prepared_sql = sql
  log(sql,name) do
    @servertype.prepare(sql, name)
  end
end

#prepared_insert(pstmt, param_array = nil, id_value = nil) ⇒ Object

Praveen Performs an insert using the prepared statement and returns the last ID generated. This can be the ID passed to the method or the one auto-generated by the database, and retrieved by the last_generated_id method.



1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1318

def prepared_insert(pstmt, param_array = nil, id_value = nil)
  if @handle_lobs_triggered  #Ensure the array of sql is cleared if they have been handled in the callback
    @sql                   = []
    @sql_parameter_values  = []
    @handle_lobs_triggered = false
  end

  clear_query_cache if defined? clear_query_cache

  begin
    if execute_prepared_stmt(pstmt, param_array)
      @sql << @prepared_sql
      @sql_parameter_values << param_array
      return id_value || @servertype.last_generated_id(pstmt)
    end
  rescue StandardError => insert_err
    raise insert_err
  ensure
    IBM_DB.free_stmt(pstmt) if pstmt
  end
end

#prepared_select(sql_param_hash, name = nil) ⇒ Object

Returns an array of hashes with the column names as keys and column values as values. sql is the select query, and name is an optional description for logging



1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1044

def prepared_select(sql_param_hash, name = nil)
  # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"}

  results = []
  # Invokes the method +prepare+ in order prepare the SQL
  # IBM_DB.Statement is returned from which the statement is executed and results fetched
  pstmt = prepare(sql_param_hash["sqlSegment"], name)
  if(execute_prepared_stmt(pstmt, sql_param_hash["paramArray"]))
    begin
      results = @servertype.select(pstmt)
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(pstmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise StatementInvalid,"Failed to retrieve data: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during data retrieval"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure
      # Ensures to free the resources associated with the statement
      IBM_DB.free_stmt(pstmt) if pstmt
    end
  end
  # The array of record hashes is returned
  results
end

#prepared_select_values(sql_param_hash, name = nil) ⇒ Object

Returns an array of hashes with the column names as keys and column values as values. sql is the select query, and name is an optional description for logging



1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1075

def prepared_select_values(sql_param_hash, name = nil)
  # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"}
  results = []
  # Invokes the method +prepare+ in order prepare the SQL
  # IBM_DB.Statement is returned from which the statement is executed and results fetched
  pstmt = prepare(sql_param_hash["sqlSegment"], name)
  if(execute_prepared_stmt(pstmt, sql_param_hash["paramArray"]))
    begin
      results = @servertype.select_rows(sql_param_hash["sqlSegment"], name, pstmt, results)
      if results
        return results.map { |v| v[0] }
      else
        nil
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(pstmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise StatementInvalid,"Failed to retrieve data: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during data retrieval"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure
      # Ensures to free the resources associated with the statement
      IBM_DB.free_stmt(pstmt) if pstmt
    end
  end
  # The array of record hashes is returned
  results
end

#prepared_update(pstmt, param_array = nil) ⇒ Object Also known as: prepared_delete

Praveen



1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1431

def prepared_update(pstmt, param_array = nil )
  if @handle_lobs_triggered  #Ensure the array of sql is cleared if they have been handled in the callback
    @sql                   = []
    @sql_parameter_values  = []
    @handle_lobs_triggered = false
  end

  clear_query_cache if defined? clear_query_cache

  begin
    if execute_prepared_stmt(pstmt, param_array)
      @sql << @prepared_sql
      @sql_parameter_values << param_array
      # Retrieves the number of affected rows
      IBM_DB.num_rows(pstmt)
      # Ensures to free the resources associated with the statement
		  end
  rescue StandardError => updt_err
    raise updt_err
  ensure
    IBM_DB.free_stmt(pstmt) if pstmt
  end
end

#primary_key(table_name) ⇒ Object

Returns the primary key of the mentioned table



1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1958

def primary_key(table_name)
  pk_name = nil
  stmt = IBM_DB.primary_keys( @connection, nil, 
                              @servertype.set_case(@schema), 
                              @servertype.set_case(table_name))
  if(stmt) 
    begin
      if ( pk_index_row = IBM_DB.fetch_array(stmt) )
        pk_name = pk_index_row[3].downcase
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg( stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve primarykey metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of primary key metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure  # Free resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  else
    error_msg = IBM_DB.getErrormsg( @connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve primary key metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during primary key retrieval')
    end
  end
  return pk_name
end

#quote_column_name(name) ⇒ Object



1708
1709
1710
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1708

def quote_column_name(name)
   @servertype.check_reserved_words(name)
end

#quote_value_for_pstmt(value, column = nil) ⇒ Object

def quoted_date(value) #:nodoc:

  if value.respond_to?(:usec)
    "#{super}.#{sprintf("%06d", value.usec)}"
  else
    super
  end
end


1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1592

def quote_value_for_pstmt(value, column=nil)

  return value.quoted_id if value.respond_to?(:quoted_id)

  case value
    when String, ActiveSupport::Multibyte::Chars then
      value = value.to_s
			if column && column.sql_type.to_s =~ /int|serial|float/i
        value = column.sql_type.to_s =~ /int|serial/i ? value.to_i : value.to_f
        value
      else
        value
      end
    when NilClass                 then nil
    when TrueClass                then 1
    when FalseClass               then 0
    when Float, Fixnum, Bignum    then value
    # BigDecimals need to be output in a non-normalized form and quoted.
    when BigDecimal               then value.to_s('F')
    when Numeric, Symbol          then value.to_s
    else
      if value.acts_like?(:date) || value.acts_like?(:time)
        quoted_date(value)
      else
        value.to_yaml
      end
  end
end

#quoted_falseObject



1704
1705
1706
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1704

def quoted_false
  "0"
end

#quoted_trueObject

true is represented by a smallint 1, false by 0, as no native boolean type exists in DB2. Numerics are not quoted in DB2.



1700
1701
1702
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1700

def quoted_true
  "1"
end

#reconnect!Object

Closes the current connection and opens a new one



1004
1005
1006
1007
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1004

def reconnect!
  disconnect!
  connect
end

#remove_column(table_name, column_name) ⇒ Object

Removes the column from the table definition.

Examples
remove_column(:suppliers, :qualification)


2411
2412
2413
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2411

def remove_column(table_name, column_name)
  @servertype.remove_column(table_name, column_name)
end

#remove_index(table_name, options = {}) ⇒ Object

Remove the given index from the table.

Remove the suppliers_name_index in the suppliers table (legacy support, use the second or third forms).

remove_index :suppliers, :name

Remove the index named accounts_branch_id in the accounts table.

remove_index :accounts, :column => :branch_id

Remove the index named by_branch_party in the accounts table.

remove_index :accounts, :name => :by_branch_party

You can remove an index on multiple columns by specifying the first column.

add_index :accounts, [:username, :password]
remove_index :accounts, :username

Overriden to use the IBM data servers SQL syntax.



2473
2474
2475
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2473

def remove_index(table_name, options = {})
 execute("DROP INDEX #{index_name(table_name, options)}")
end

#rename_column(table_name, column_name, new_column_name) ⇒ Object

Renames a column.

Example
rename_column(:suppliers, :description, :name)


2404
2405
2406
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2404

def rename_column(table_name, column_name, new_column_name)
  @servertype.rename_column(table_name, column_name, new_column_name)
end

#rename_table(name, new_name) ⇒ Object

Renames a table.

Example

rename_table(‘octopuses’, ‘octopi’) Overriden to satisfy IBM data servers syntax



2392
2393
2394
2395
2396
2397
2398
2399
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2392

def rename_table(name, new_name)
  # SQL rename table statement
  rename_table_sql = "RENAME TABLE #{name} TO #{new_name}"
  stmt = execute(rename_table_sql)
  # Ensures to free the resources associated with the statement
  ensure
    IBM_DB.free_stmt(stmt) if stmt
end

#rollback_db_transactionObject

Rolls back the transaction and turns on auto-committing. Must be done if the transaction block raises an exception or returns false



1514
1515
1516
1517
1518
1519
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1514

def rollback_db_transaction
  # ROLLBACK the transaction
  IBM_DB.rollback(@connection) rescue nil
  # Turns on auto-committing
  IBM_DB.autocommit @connection, IBM_DB::SQL_AUTOCOMMIT_ON
end

#select(sql, name = nil, binds = []) ⇒ Object



1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1128

def select(sql, name = nil, binds = [])
  # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"
  sql.gsub( /(=\s*NULL|IN\s*\(NULL\))/i, " IS NULL" )

  results = []

  if(binds.nil? || binds.empty?)
    stmt = execute(sql, name)
  else
    stmt = exec_query(sql, name, binds)
  end

  cols = IBM_DB.resultCols(stmt)

  if( stmt ) 
    results = fetch_data(stmt)
  end

  if(@isAr3)
    return results
  else
    return ActiveRecord::Result.new(cols, results)
  end
end

#select_rows(sql, name = nil, binds = []) ⇒ Object

Returns an array of arrays containing the field values. This is an implementation for the abstract method sql is the select query and name is an optional description for logging



1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1156

def select_rows(sql, name = nil,binds = [])
  # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"}
  sql.gsub( /(=\s*NULL|IN\s*\(NULL\))/i, " IS NULL" )
  
  results = []
  # Invokes the method +execute+ in order to log and execute the SQL
  # IBM_DB.Statement is returned from which results can be fetched
  if !binds.nil? && !binds.empty?
    param_array = binds.map do |column,value|
      quote_value_for_pstmt(value, column)
    end
    return prepared_select({"sqlSegment" => sql, "paramArray" => param_array})
  end

  stmt = execute(sql, name)
  if(stmt)
    begin
      results = @servertype.select_rows(sql, name, stmt, results)
    rescue StandardError => fetch_error  # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise StatementInvalid,"Failed to retrieve data: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during data retrieval"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure
      # Ensures to free the resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  end
  # The array of record hashes is returned
  results
end

#simplified_type(field_type) ⇒ Object

Mapping IBM data servers SQL datatypes to Ruby data types



2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2155

def simplified_type(field_type)
  case field_type
    # if +field_type+ contains 'for bit data' handle it as a binary
    when /for bit data/i
      :binary
    when /smallint/i
      :boolean
    when /int|serial/i
      :integer
    when /decimal|numeric|decfloat/i
      :decimal
    when /float|double|real/i
      :float
    when /timestamp|datetime/i
      :timestamp
    when /time/i
      :time
    when /date/i
      :date
    when /vargraphic/i
      :vargraphic
    when /graphic/i
      :graphic
    when /clob|text/i
      :text
    when /xml/i
      :xml
    when /blob|binary/i
      :binary
    when /char/i
      :string
    when /boolean/i
      :boolean
    when /rowid/i  # rowid is a supported datatype on z/OS and i/5
      :rowid
  end
end

#simplified_type2(field_type) ⇒ Object

Mapping IBM data servers SQL datatypes to Ruby data types



2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2115

def simplified_type2(field_type)
  case field_type
    # if +field_type+ contains 'for bit data' handle it as a binary
    when /for bit data/i
      "binary"
    when /smallint/i
      "boolean"
    when /int|serial/i
      "integer"
    when /decimal|numeric|decfloat/i
      "decimal"
    when /float|double|real/i
      "float"
    when /timestamp|datetime/i
      "timestamp"
    when /time/i
      "time"
    when /date/i
      "date"
    when /vargraphic/i
      "vargraphic"
    when /graphic/i
      "graphic"
    when /clob|text/i
      "text"
    when /xml/i
      "xml"
    when /blob|binary/i
      "binary"
    when /char/i
      "string"
    when /boolean/i
      "boolean"
    when /rowid/i  # rowid is a supported datatype on z/OS and i/5
      "rowid"
  end
end

#supports_datetime_with_precision?Boolean

Returns:

  • (Boolean)


938
939
940
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 938

def supports_datetime_with_precision?
	true
end

#supports_ddl_transactions?Boolean

This Adapter supports DDL transactions. This means CREATE TABLE and other DDL statements can be carried out as a transaction. That is the statements executed can be ROLLED BACK in case of any error during the process.

Returns:

  • (Boolean)


945
946
947
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 945

def supports_ddl_transactions?
  true
end

#supports_disable_referential_integrity?Boolean

:nodoc:

Returns:

  • (Boolean)


2362
2363
2364
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2362

def supports_disable_referential_integrity? #:nodoc:
      true
end

#supports_foreign_keys?Boolean

Returns:

  • (Boolean)


934
935
936
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 934

def supports_foreign_keys?
  true
end

#supports_migrations?Boolean

This adapter supports migrations. Current limitations: rename_column is not currently supported by the IBM data servers remove_column is not currently supported by the DB2 for zOS data server Tables containing columns of XML data type do not support remove_column

Returns:

  • (Boolean)


930
931
932
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 930

def supports_migrations?
  true
end

#table_alias_lengthObject

Returns the maximum length a table alias identifier can be. IBM data servers (cross-platform) table limit is 128 characters



1868
1869
1870
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1868

def table_alias_length
  128
end

#tables(name = nil) ⇒ Object

Retrieves table’s metadata for a specified shema name



1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1874

def tables(name = nil)
  # Initializes the tables array
  tables = []
  # Retrieve table's metadata through IBM_DB driver
  stmt = IBM_DB.tables(@connection, nil, 
                      @servertype.set_case(@schema))
  if(stmt)
    begin
      # Fetches all the records available
      while tab = IBM_DB.fetch_assoc(stmt)
        # Adds the lowercase table name to the array
        if(tab["table_type"]== 'TABLE')  #check, so that only tables are dumped,IBM_DB.tables also returns views,alias etc in the schema
          tables << tab["table_name"].downcase    
        end
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve table metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of table metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure
      IBM_DB.free_stmt(stmt)  if stmt # Free resources associated with the statement
    end
  else # Handle driver execution errors
    error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve tables metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during retrieval of table metadata')
    end
  end
  # Returns the tables array
  return tables
end

#to_sql(arel, binds = []) ⇒ Object



915
916
917
918
919
920
921
922
923
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 915

def to_sql(arel, binds = [])
			if arel.respond_to?(:ast)
 visitor.accept(arel.ast) do
quote(*binds.shift.reverse)
 end
			else
 arel
			end
end

#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object

IBM data servers do not support limits on certain data types (unlike MySQL) Limit is supported for the decimal, numeric, varchar, clob, blob, graphic, vargraphic data types.



1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1815

def type_to_sql(type, limit=nil, precision=nil, scale=nil )
  if type.to_sym == :decimal
    if limit.class == Hash
      if limit.has_key?("precision".to_sym)
        precision = limit[:precision]
      end
    end
    if limit.class == Hash
      if limit.has_key?("scale".to_sym)
        scale = limit[:scale]
      end
    end
    sql_segment = native_database_types[type.to_sym][:name].to_s
    if !precision.nil? && !scale.nil?
      sql_segment << "(#{precision},#{scale})"
      return sql_segment
    elsif scale.nil? && !precision.nil?
      sql_segment << "(#{precision})"
    else
      return sql_segment
    end
  end

  if type.to_sym == :decfloat
    sql_segment = native_database_types[type.to_sym][:name].to_s
    sql_segment << "(#{precision})" if !precision.nil?
    return sql_segment
  end

  if limit.class == Hash
    return super if limit.has_key?("limit".to_sym).nil?
  else
    return super if limit.nil?
  end

  # strip off limits on data types not supporting them
  if @servertype.limit_not_supported_types.include? type.to_sym
    return native_database_types[type.to_sym][:name].to_s
  elsif type.to_sym == :boolean
    return "smallint"
  else
    return super(type)
  end

end

#update(arel, name = nil, binds = []) ⇒ Object Also known as: delete



1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1459

def update(arel, name = nil, binds = [])
  if(@arelVersion <  6 )
  sql = to_sql(arel)
else
  sql = to_sql(arel,binds)
end

  # Make sure the WHERE clause handles NULL's correctly
  sqlarray = sql.split(/\s*WHERE\s*/)
  size = sqlarray.size
  if size > 1
    sql = sqlarray[0] + " WHERE "
    if size > 2
      1.upto size-2 do |index|
        sqlarray[index].gsub!( /(=\s*NULL|IN\s*\(NULL\))/i, " IS NULL" ) unless sqlarray[index].nil?
        sql = sql + sqlarray[index] + " WHERE "
      end
    end
    sqlarray[size-1].gsub!( /(=\s*NULL|IN\s*\(NULL\))/i, " IS NULL" ) unless sqlarray[size-1].nil?
    sql = sql + sqlarray[size-1]
  end

  clear_query_cache if defined? clear_query_cache

  if binds.nil? || binds.empty?
    update_direct(sql, name)
  else
    begin
      if stmt = exec_query(sql,name,binds)
        IBM_DB.num_rows(stmt)
      end
    ensure
      IBM_DB.free_stmt(stmt) if(stmt)
    end
  end
end

#update_direct(sql, name = nil) ⇒ Object

Executes an “UPDATE” SQL statement



1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1411

def update_direct(sql, name = nil)
  if @handle_lobs_triggered  #Ensure the array of sql is cleared if they have been handled in the callback
    @sql = []
    @handle_lobs_triggered = false
  end

  # Logs and execute the given sql query.
  if stmt = execute(sql, name)
    begin
      @sql << sql
      # Retrieves the number of affected rows
      IBM_DB.num_rows(stmt)
      # Ensures to free the resources associated with the statement
    ensure
      IBM_DB.free_stmt(stmt) if stmt
    end
  end
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


1808
1809
1810
1811
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1808

def valid_type?(type)		
  #!native_database_types[type].nil?
		native_database_types[type].nil?
end

#viewsObject

Retrieves views’s metadata for a specified shema name



1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1917

def views
  # Initializes the tables array
  tables = []
  # Retrieve view's metadata through IBM_DB driver
  stmt = IBM_DB.tables(@connection, nil, 
                      @servertype.set_case(@schema))
  if(stmt)
    begin
      # Fetches all the records available
      while tab = IBM_DB.fetch_assoc(stmt)
        # Adds the lowercase view's name to the array
        if(tab["table_type"]== 'V')  #check, so that only views are dumped,IBM_DB.tables also returns tables,alias etc in the schema
          tables << tab["table_name"].downcase    
        end
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve views metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of views metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure
      IBM_DB.free_stmt(stmt)  if stmt # Free resources associated with the statement
    end
  else # Handle driver execution errors
    error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve tables metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during retrieval of views metadata')
    end
  end
  # Returns the tables array
  return tables
end