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: AlterTable, SchemaDumper, StatementPool, TableDefinition, UniqueConstraintDefinition

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.



930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 930

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]
  @debug            = config[:debug]
  if config.has_key?(:host)
    @host           = config[:host]
    @port           = config[:port] || 50000 # default port
  end
  @schema = if config.has_key?(:schema)
              config[:schema]
            else
              config[:username]
            end
  @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 %r{DB2/}i # DB2 for Linux, Unix and Windows (LUW)
        @servertype = case server_info.DBMS_VER
                      when /09.07/i # DB2 Version 9.7 (Cobra)
                        IBM_DB2_LUW_COBRA.new(self, @isAr3)
                      when /10./i # DB2 version 10.1 and above
                        IBM_DB2_LUW_COBRA.new(self, @isAr3)
                      else # DB2 Version 9.5 or below
                        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 /11/
          @servertype = IBM_DB2_ZOS.new(self, @isAr3)
        when /12/
          @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
      @database_version = server_info.DBMS_VER
    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
  @start_id = if config.has_key?(:start_id)
                config[:start_id]
              else
                1
              end

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

  @visitor = Arel::Visitors::IBM_DB.new self if @arelVersion >= 3

  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.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def 
  @account
end

#app_userObject

Returns the value of attribute app_user.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def app_user
  @app_user
end

#applicationObject

Returns the value of attribute application.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def application
  @application
end

#connectionObject (readonly)

Returns the value of attribute connection.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def connection
  @connection
end

#handle_lobs_triggeredObject

Returns the value of attribute handle_lobs_triggered.



838
839
840
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 838

def handle_lobs_triggered
  @handle_lobs_triggered
end

#pstmt_support_onObject (readonly)

Returns the value of attribute pstmt_support_on.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def pstmt_support_on
  @pstmt_support_on
end

#schemaObject

Returns the value of attribute schema.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def schema
  @schema
end

#servertypeObject (readonly)

Returns the value of attribute servertype.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def servertype
  @servertype
end

#set_quoted_literal_replacementObject (readonly)

Returns the value of attribute set_quoted_literal_replacement.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def set_quoted_literal_replacement
  @set_quoted_literal_replacement
end

#sqlObject

Returns the value of attribute sql.



838
839
840
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 838

def sql
  @sql
end

#sql_parameter_valuesObject

Returns the value of attribute sql_parameter_values.



838
839
840
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 838

def sql_parameter_values
  @sql_parameter_values
end

#workstationObject

Returns the value of attribute workstation.



836
837
838
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 836

def workstation
  @workstation
end

Class Method Details

.visitor_for(pool) ⇒ Object



1114
1115
1116
1117
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1114

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

Instance Method Details

#active?Boolean

Tests the connection status

Returns:

  • (Boolean)


1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1221

def active?
  isActive = false
  puts_log "active? #{caller} #{Thread.current}"
  @lock.synchronize do
    puts_log "active? #{@connection}, #{caller}, #{Thread.current}"
    isActive = IBM_DB.active @connection
    puts_log "active? isActive = #{isActive}"
  end
  isActive
rescue StandardError => e
  puts_log "active? check failure #{e.message}, #{caller}, #{Thread.current}"
  false
end

#adapter_nameObject

Name of the adapter



841
842
843
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 841

def adapter_name
  'IBM_DB'
end

#add_column(table_name, column_name, type, **options) ⇒ Object

:nodoc:



2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2945

def add_column(table_name, column_name, type, **options) # :nodoc:
  puts_log 'add_column'
  clear_cache!
  puts_log "add_column info #{table_name}, #{column_name}, #{type}, #{options}"
  puts_log caller
  if (!type.nil? && type.to_s == 'primary_key') or (options.key?(:primary_key) and options[:primary_key] == true)
    if !type.nil? and type.to_s != 'primary_key'
      execute "ALTER TABLE #{table_name} ADD COLUMN #{column_name} #{type} NOT NULL DEFAULT 0"
    else
      execute "ALTER TABLE #{table_name} ADD COLUMN #{column_name} INTEGER NOT NULL DEFAULT 0"
    end
    execute "ALTER TABLE #{table_name} alter column #{column_name} drop default"
    execute "ALTER TABLE #{table_name} alter column #{column_name} set GENERATED BY DEFAULT AS IDENTITY (START WITH 1000)"
    execute "ALTER TABLE #{table_name} add primary key (#{column_name})"
  else
    super
  end
  change_column_comment(table_name, column_name, options[:comment]) if options.key?(:comment)
end

#add_foreign_keyList(fkey_list, table_name, column_name, new_column_name) ⇒ Object



3208
3209
3210
3211
3212
3213
3214
3215
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3208

def add_foreign_keyList(fkey_list, table_name, column_name, new_column_name)
  puts_log "add_foreign_keyList = #{table_name}, #{column_name}, #{fkey_list}"
  fkey_list.each do |fkey|
    if fkey.options[:column] == column_name
      add_foreign_key(table_name, strip_table_name_prefix_and_suffix(fkey.to_table), column: new_column_name)
    end
  end
end

#add_index(table_name, column_name, **options) ⇒ Object

:nodoc:



2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2971

def add_index(table_name, column_name, **options) # :nodoc:
  puts_log 'add_index'
  index, algorithm, if_not_exists = add_index_options(table_name, column_name, **options)

  return if if_not_exists && index_exists?(table_name, column_name, name: index.name)

  if_not_exists = false if if_not_exists
  create_index = CreateIndexDefinition.new(index, algorithm, if_not_exists)
  result = execute schema_creation.accept(create_index)

  execute "COMMENT ON INDEX #{quote_column_name(index.name)} IS #{quote(index.comment)}" if index.comment
  result
end

#add_reference(table_name, ref_name, **options) ⇒ Object Also known as: add_belongs_to

:nodoc:



3110
3111
3112
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3110

def add_reference(table_name, ref_name, **options) # :nodoc:
  super(table_name, ref_name, type: :integer, **options)
end

#add_timestamps(table_name, **options) ⇒ Object



2985
2986
2987
2988
2989
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2985

def add_timestamps(table_name, **options)
  puts_log "add_timestamps #{table_name}"
  fragments = add_timestamps_for_alter(table_name, **options)
  execute "ALTER TABLE #{quote_table_name(table_name)} #{fragments.join(' ')}"
end

#add_unique_constraint(table_name, column_name = nil, **options) ⇒ Object



3356
3357
3358
3359
3360
3361
3362
3363
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3356

def add_unique_constraint(table_name, column_name = nil, **options)
  puts_log "add_unique_constraint = #{table_name}, #{column_name}, #{options}"
  options = unique_constraint_options(table_name, column_name, options)
  at = create_alter_table(table_name)
  at.add_unique_constraint(column_name, options)

  execute schema_creation.accept(at)
end

#add_unique_constraint_byColumn(unique_indexes, new_column_name) ⇒ Object



3194
3195
3196
3197
3198
3199
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3194

def add_unique_constraint_byColumn(unique_indexes, new_column_name)
  puts_log "add_unique_constraint_byColumn = #{unique_indexes}"
  unique_indexes.each do |unq|
    add_unique_constraint(unq.table_name, new_column_name, name: unq.name)
  end
end

#alter_foreign_keys(tables, not_enforced) ⇒ Object



2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2903

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

#assert_valid_deferrable(deferrable) ⇒ Object

Raises:

  • (ArgumentError)


3454
3455
3456
3457
3458
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3454

def assert_valid_deferrable(deferrable)
  return if !deferrable || %i(immediate deferred).include?(deferrable)

  raise ArgumentError, "deferrable must be `:immediate` or `:deferred`, got: `#{deferrable.inspect}`"
end

#auto_commit_offObject



1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1954

def auto_commit_off
  puts_log 'auto_commit_off'
  IBM_DB.autocommit(@connection, IBM_DB::SQL_AUTOCOMMIT_OFF)
  ac = IBM_DB::autocommit @connection
  if ac != 0
    puts_log "Cannot set IBM_DB::AUTOCOMMIT_OFF"
  else
    puts_log "AUTOCOMMIT_OFF set"
  end
end

#auto_commit_onObject



1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1943

def auto_commit_on
  puts_log 'Inside auto_commit_on'
  IBM_DB.autocommit @connection, IBM_DB::SQL_AUTOCOMMIT_ON
  ac = IBM_DB::autocommit @connection
  if ac != 1
    puts_log "Cannot set IBM_DB::AUTOCOMMIT_ON"
  else
    puts_log "AUTOCOMMIT_ON set"
  end
end

#begin_db_transactionObject

Begins the transaction (and turns off auto-committing)



1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1966

def begin_db_transaction
  puts_log 'begin_db_transaction'
  log('begin transaction', 'TRANSACTION') do
    with_raw_connection(allow_retry: true, materialize_transactions: false) do |conn|
      # Turns off the auto-commit
      auto_commit_off
      verified!
    end
  end
end

#bind_params_lengthObject



1057
1058
1059
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1057

def bind_params_length
  999
end

#build_change_column_default_definition(table_name, column_name, default_or_changes) ⇒ Object

:nodoc:



3293
3294
3295
3296
3297
3298
3299
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3293

def build_change_column_default_definition(table_name, column_name, default_or_changes) # :nodoc:
  column = column_for(table_name, column_name)
  return unless column

  default = extract_new_default_value(default_or_changes)
  ChangeColumnDefaultDefinition.new(column, default)
end

#build_change_column_definition(table_name, column_name, type, **options) ⇒ Object

:nodoc:



3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3301

def build_change_column_definition(table_name, column_name, type, **options) # :nodoc:
  column = column_for(table_name, column_name)
  type ||= column.sql_type

  unless options.key?(:default)
    options[:default] = column.default
  end

  unless options.key?(:null)
    options[:null] = column.null
  end

  unless options.key?(:comment)
    options[:comment] = column.comment
  end

  if options[:collation] == :no_collation
    options.delete(:collation)
  else
    options[:collation] ||= column.collation if text_type?(type)
  end

  unless options.key?(:auto_increment)
    options[:auto_increment] = column.auto_increment?
  end

  td = create_table_definition(table_name)
  cd = td.new_column_definition(column.name, type, **options)
  ChangeColumnDefinition.new(cd, column.name)
end

#build_conn_str_for_dbopsObject



2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2136

def build_conn_str_for_dbops
  puts_log 'build_conn_str_for_dbops'
  connect_str = 'DRIVER={IBM DB2 ODBC DRIVER};ATTACH=true;'
  unless @host.nil?
    connect_str << "HOSTNAME=#{@host};"
    connect_str << "PORT=#{@port};"
    connect_str << 'PROTOCOL=TCPIP;'
  end
  connect_str << "UID=#{@username};PWD=#{@password};"
  connect_str
end

#build_fixture_sql(fixtures, table_name) ⇒ Object



1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1484

def build_fixture_sql(fixtures, table_name)
  columns = schema_cache.columns_hash(table_name).reject { |_, column| supports_virtual_columns? && column.virtual? }
  puts_log "build_fixture_sql - Table = #{table_name}"
  puts_log "build_fixture_sql - Fixtures = #{fixtures}"
  puts_log "build_fixture_sql - Columns = #{columns}"

  values_list = fixtures.map do |fixture|
    fixture = fixture.stringify_keys
    fixture = fixture.transform_keys(&:downcase)

    unknown_columns = fixture.keys - columns.keys
    if unknown_columns.any?
      raise Fixture::FixtureError, %(table "#{table_name}" has no columns named #{unknown_columns.map(&:inspect).join(', ')}.)
    end

    columns.map do |name, column|
      if fixture.key?(name)
        type = lookup_cast_type_from_column(column)
        with_yaml_fallback(type.serialize(fixture[name]))
      else
        default_insert_value(column)
      end
    end
  end

  table = Arel::Table.new(table_name)
  manager = Arel::InsertManager.new(table)

  if values_list.size == 1
    values = values_list.shift
    new_values = []
    columns.each_key.with_index { |column, i|
      unless values[i].equal?(DEFAULT_INSERT_VALUE)
        new_values << values[i]
        manager.columns << table[column]
      end
    }
    values_list << new_values
  else
    columns.each_key { |column| manager.columns << table[column] }
  end

  manager.values = manager.create_values_list(values_list)
  visitor.compile(manager.ast)
end

#build_fixture_statements(fixture_set) ⇒ Object



1530
1531
1532
1533
1534
1535
1536
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1530

def build_fixture_statements(fixture_set)
  puts_log "build_fixture_statements - fixture_set = #{fixture_set}"
  fixture_set.filter_map do |table_name, fixtures|
    next if fixtures.empty?
    build_fixture_sql(fixtures, table_name)
  end
end

#build_statement_poolObject



926
927
928
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 926

def build_statement_pool
  StatementPool.new(self.class.type_cast_config_to_integer(@config[:statement_limit]))
end

#build_truncate_statement(table_name) ⇒ Object



1479
1480
1481
1482
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1479

def build_truncate_statement(table_name)
  puts_log 'build_truncate_statement'
  "DELETE FROM #{quote_table_name(table_name)}"
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)


3258
3259
3260
3261
3262
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3258

def change_column(table_name, column_name, type, options = {})
  puts_log 'change_column'
  @servertype.change_column(table_name, column_name, type, options)
  change_column_comment(table_name, column_name, options[:comment]) if options.key?(:comment)
end

#change_column_comment(table_name, column_name, comment_or_changes) ⇒ Object

Adds comment for given table column or drops it if comment is a nil



2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2922

def change_column_comment(table_name, column_name, comment_or_changes) # :nodoc:
  puts_log 'change_column_comment'
  clear_cache!
  comment = extract_new_comment_value(comment_or_changes)
  if comment.nil?
    execute "COMMENT ON COLUMN #{quote_table_name(table_name)}.#{quote_column_name(column_name)} IS ''"
  else
    execute "COMMENT ON COLUMN #{quote_table_name(table_name)}.#{quote_column_name(column_name)} IS #{quote(comment)}"
  end
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.



3281
3282
3283
3284
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3281

def change_column_default(table_name, column_name, default)
  puts_log 'change_column_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



3287
3288
3289
3290
3291
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3287

def change_column_null(table_name, column_name, null, default = nil)
  puts_log 'change_column_null'
   validate_change_column_null_argument!(null)
  @servertype.change_column_null(table_name, column_name, null, default)
end

#change_table_comment(table_name, comment_or_changes) ⇒ Object

Adds comment for given table or drops it if comment is a nil



2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2934

def change_table_comment(table_name, comment_or_changes) # :nodoc:
  puts_log 'change_table_comment'
  clear_cache!
  comment = extract_new_comment_value(comment_or_changes)
  if comment.nil?
    execute "COMMENT ON TABLE #{quote_table_name(table_name)} IS ''"
  else
    execute "COMMENT ON TABLE #{quote_table_name(table_name)} IS #{quote(comment)}"
  end
end

#check_if_write_query(sql) ⇒ Object

For rails 7.1 just remove this function as it will be defined in AbstractAdapter class

Raises:

  • (ActiveRecord::ReadOnlyError)


1821
1822
1823
1824
1825
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1821

def check_if_write_query(sql) # For rails 7.1 just remove this function as it will be defined in AbstractAdapter class
  return unless preventing_writes? && write_query?(sql)

  raise ActiveRecord::ReadOnlyError, "Write query attempted while in readonly mode: #{sql}"
end

#column_for(table_name, column_name) ⇒ Object



3467
3468
3469
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3467

def column_for(table_name, column_name)
  super
end

#columns(table_name) ⇒ Object

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



2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2652

def columns(table_name)
  default_blob_length = 1048576
  # to_s required because it may be a symbol.
  puts_log "def columns #{table_name}"
  puts_log caller
  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))
  #       sql = "select * from sysibm.sqlcolumns where table_name = #{quote(table_name.upcase)}"
  if @debug == true
    sql = "select * from syscat.columns  where tabname = #{quote(table_name.upcase)}"
    puts_log "SYSIBM.SQLCOLUMNS = #{select_prepared(sql).rows}"
  end

  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)
        puts_log col
        column_name = col['column_name'].downcase
        # Assigns the column default value.
        column_default_value = col['column_def']
        default_value = extract_value_from_default(column_default_value)
        # Assigns the column type
        column_type = col['type_name'].downcase

        # Assigns the field length (size) for the column

        column_length = if column_type =~ /integer|bigint/i
                          col['buffer_length']
                        else
                          col['column_size']
                        end
        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
        if column_type.match(/decimal|numeric/)
          if column_length > 0 and column_scale > 0
            column_type << "(#{column_length},#{column_scale})"
          elsif column_length > 0 and column_scale == 0
            column_type << "(#{column_length})"
          end
        elsif column_type.match(/timestamp/)
          column_type << "(#{column_scale})"
        elsif column_type.match(/varchar/) and column_length > 0
          column_type << "(#{column_length})"
        end

        column_nullable = col['nullable'] == 1
        # Make sure the hidden column (db2_generated_rowid_for_lobs) in DB2 z/OS isn't added to the list
        next if column_name.match(/db2_generated_rowid_for_lobs/i)

        puts_log "Column type = #{column_type}"
        ruby_type = simplified_type(column_type)
        puts_log "Ruby type after = #{ruby_type}"
        precision = extract_precision(ruby_type)

        if column_type.match(/timestamp|integer|bigint|date|time|blob/i)
          if column_type.match(/timestamp/i)
            precision = column_scale
            unless default_value.nil?
              default_value[10] = ' '
              default_value[13] = ':'
              default_value[16] = ':'
            end
          elsif column_type.match(/time/i)
            unless default_value.nil?
              default_value[2] = ':'
              default_value[5] = ':'
            end
          end
          column_scale = nil
          if !(column_type.match(/blob/i) and column_length != default_blob_length) and !column_type.match(/bigint/i)
            column_length = nil
          end
        elsif column_type.match(/decimal|numeric/)
          precision = column_length
          column_length = nil
        end

        column_type = 'boolean' if ruby_type.to_s == 'boolean'

        default_function = extract_default_function(default_value, column_default_value)

         = SqlTypeMetadata.new(
          # sql_type: sql_type,
          sql_type: column_type,
          type: ruby_type,
          limit: column_length,
          precision: precision,
          scale: column_scale
        )

        columns << Column.new(column_name, default_value, , column_nullable, default_function,
                              comment: col['remarks'])
      end
    rescue StandardError => e # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT)
      raise "Failed to retrieve column metadata during fetch: #{error_msg}" if error_msg && !error_msg.empty?

      error_msg = 'An unexpected error occurred during retrieval of column metadata'
      error_msg += ": #{e.message}" unless e.message.empty?
    #             raise error_msg
    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)
    raise "Failed to retrieve column metadata due to error: #{error_msg}" if error_msg && !error_msg.empty?

    raise StandardError.new('An unexpected error occurred during retrieval of columns metadata')

  end
  # Returns the columns array
  puts_log "Inside def columns() #{columns}"
  columns
end

#commit_db_transactionObject

Commits the transaction and turns on auto-committing



1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1978

def commit_db_transaction
  puts_log 'commit_db_transaction'
  log('commit transaction', 'TRANSACTION') do
    with_raw_connection(allow_retry: true, materialize_transactions: false) do |conn|
      # Commits the transaction

      IBM_DB.commit @connection
    end
  rescue StandardError
    nil
  end
  # Turns on auto-committing
  auto_commit_on
end

#create_alter_table(name) ⇒ Object



3449
3450
3451
3452
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3449

def create_alter_table(name)
  puts_log "create_alter_table name = #{name}"
  IBM_DBAdapter::AlterTable.new create_table_definition(name)
end

#create_column_indexes(index_list, column_name, new_column_name) ⇒ Object



3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3148

def create_column_indexes(index_list, column_name, new_column_name)
  puts_log 'create_column_indexes'
  index_list.each do |indexs|
    generated_index_name = index_name(indexs.table, column: indexs.columns)
    custom_index_name = indexs.name
    if indexs.columns.class == Array
      next unless indexs.columns.include?(column_name)

      indexs.columns[indexs.columns.index(column_name)] = new_column_name
    else
      next if indexs.columns != column_name

      indexs.columns = new_column_name
    end

    if generated_index_name == custom_index_name
      add_index(indexs.table, indexs.columns, unique: indexs.unique)
    else
      add_index(indexs.table, indexs.columns, name: custom_index_name, unique: indexs.unique)
    end
  end
end

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



2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2172

def create_database(dbName, codeSet = nil, mode = nil)
  puts_log 'create_database'
  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 => e
    raise "Failed to connect to server due to: #{e}"
  end

  if IBM_DB.createDB(createConn, dbName, codeSet, mode)
    IBM_DB.close(createConn)
    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_schema(schema_name, force: nil, if_not_exists: nil) ⇒ Object

Creates a schema for the given schema name.



3341
3342
3343
3344
3345
3346
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3341

def create_schema(schema_name, force: nil, if_not_exists: nil)
  puts_log "create_schema #{schema_name}"
  drop_schema(schema_name, if_exists: true)

  execute("CREATE SCHEMA #{quote_schema_name(schema_name)}")
end

#create_schema_dumper(options) ⇒ Object



3064
3065
3066
3067
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3064

def create_schema_dumper(options)
  puts_log 'create_schema_dumper'
  SchemaDumper.create(self, options)
end

#create_table(name, id: :primary_key, primary_key: nil, force: nil, **options) ⇒ Object

DATABASE STATEMENTS



1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1332

def create_table(name, id: :primary_key, primary_key: nil, force: nil, **options)
  puts_log "create_table name=#{name}, id=#{id}, primary_key=#{primary_key}, force=#{force}"
  puts_log "create_table Options = #{options}"
  puts_log "primary_key_prefix_type = #{ActiveRecord::Base.primary_key_prefix_type}"
  puts_log caller
  @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 !id.nil? || !primary_key.nil?
    if !id.nil? && id == true
      @servertype.create_index_after_table(name, 'id')
    elsif !primary_key.nil?
      @servertype.create_index_after_table(name, primary_key.to_s)
    end
  else
    @servertype.create_index_after_table(name, 'id')
  end

  # Just incase if id holds any other data type other than primary_key we override it,
  # otherwise it misses "GENERATED BY DEFAULT AS IDENTITY (START WITH 1000)"
  if !id.nil? && id != false && primary_key.nil? && ActiveRecord::Base.primary_key_prefix_type.nil?
    primary_key = :id
    options[:auto_increment] = true if options[:auto_increment].nil? and %i[integer bigint].include?(id)
  end

  super(name, id: id, primary_key: primary_key, force: force, **options)
end

#create_table_definition(name, **options) ⇒ Object



3443
3444
3445
3446
3447
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3443

def create_table_definition(name, **options)
  puts_log "create_table_definition name = #{name}"
  puts_log caller
  IBM_DBAdapter::TableDefinition.new(self, name, **options)
end

#create_table_indexes(index_list, new_table) ⇒ Object



3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3122

def create_table_indexes(index_list, new_table)
  puts_log 'create_table_indexes'
  index_list.each do |indexs|
    generated_index_name = index_name(indexs.table, column: indexs.columns)
    custom_index_name = indexs.name

    if generated_index_name == custom_index_name
      add_index(new_table, indexs.columns, unique: indexs.unique)
    else
      add_index(new_table, indexs.columns, name: custom_index_name, unique: indexs.unique)
    end
  end
end

#data_source_sql(name = nil, type: nil) ⇒ Object



2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2996

def data_source_sql(name = nil, type: nil)
  puts_log 'data_source_sql'
  puts_log "servertype = #{@servertype}"
  if @servertype.instance_of? IBM_IDS
    sql = "SELECT tabname FROM systables WHERE"
    if type || name
      conditions = []
      conditions << "tabtype = #{quote(type.upcase)}" if type
      conditions << "tabname = #{quote(name.upcase)}" if name
      sql << " #{conditions.join(' AND ')}"
    end
    sql << " AND owner = #{quote(@schema.upcase)}"
  else
    sql = +'SELECT tabname FROM (SELECT tabname, type FROM syscat.tables '
    sql << " WHERE tabschema = #{quote(@schema.upcase)}) subquery"
    if type || name
      conditions = []
      conditions << "subquery.type = #{quote(type.upcase)}" if type
      conditions << "subquery.tabname = #{quote(name.upcase)}" if name
      sql << " WHERE #{conditions.join(' AND ')}"
    end
  end
  sql
end

#data_sourcesObject

Returns the relation names useable to back Active Record models. For most adapters this means all #tables and #views.



3057
3058
3059
3060
3061
3062
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3057

def data_sources
  puts_log 'data_sources'
  query_values(data_source_sql, 'SCHEMA').map(&:downcase)
rescue NotImplementedError
  tables | views
end

#default_sequence_name(table, column) ⇒ Object

:nodoc:



2011
2012
2013
2014
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2011

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

#disable_referential_integrityObject

:nodoc:



2894
2895
2896
2897
2898
2899
2900
2901
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2894

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

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

#disconnect!Object

Closes the current connection



1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1304

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
  @lock.synchronize do
    puts_log "disconnect! #{caller}, #{Thread.current}"
    if @connection.nil? || @connection == false
      puts_log "disconnect! return #{caller}, #{Thread.current}"
      return nil
    end

    begin
      super
      IBM_DB.close(@connection)
      puts_log "Connection closed #{Thread.current}"
      @connection = nil
    rescue StandardError => e
      puts_log "Connection close failure #{e.message}, #{Thread.current}"
    end
#reset_transaction
  end
end

#distinct(columns, order_by) ⇒ Object

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



3265
3266
3267
3268
3269
3270
3271
3272
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3265

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

#drop_column_indexes(index_list, column_name) ⇒ Object



3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3136

def drop_column_indexes(index_list, column_name)
  puts_log 'drop_column_indexes'
  index_list.each do |indexs|
    if indexs.columns.class == Array
      next unless indexs.columns.include?(column_name)
    elsif indexs.columns != column_name
      next
    end
    remove_index(indexs.table, name: indexs.name)
  end
end

#drop_database(dbName) ⇒ Object



2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2148

def drop_database(dbName)
  puts_log 'drop_database'
  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 => e
    raise "Failed to connect to server due to: #{e}"
  end

  if IBM_DB.dropDB(dropConn, dbName)
    IBM_DB.close(dropConn)
    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

#drop_schema(schema_name, **options) ⇒ Object

Drops the schema for the given schema name.



3349
3350
3351
3352
3353
3354
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3349

def drop_schema(schema_name, **options)
  puts_log "drop_schema = #{schema_name}"
  schema_list = internal_exec_query("select schemaname from syscat.schemata where schemaname=#{quote(schema_name.upcase)}", "SCHEMA")
  puts_log "drop_schema schema_list = #{schema_list.columns}, #{schema_list.rows}"
  execute("DROP SCHEMA #{quote_schema_name(schema_name)} RESTRICT") if schema_list.rows.size > 0
end

#drop_table_indexes(index_list) ⇒ Object



3115
3116
3117
3118
3119
3120
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3115

def drop_table_indexes(index_list)
  puts_log 'drop_table_indexes'
  index_list.each do |indexs|
    remove_index(indexs.table, name: indexs.name)
  end
end

#empty_insert_statement_value(pkey, table_name) ⇒ Object



1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1603

def empty_insert_statement_value(pkey, table_name)
  puts_log "empty_insert_statement_value pkey = #{pkey}, table_name = #{table_name}"
  puts_log caller

  colCount = columns(table_name).count()
  puts_log "empty_insert_statement_value colCount = #{colCount}"
  val = "DEFAULT, " * (colCount - 1)
  val = val + "DEFAULT"
  " VALUES (#{val})"
end

#exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil, returning: nil) ⇒ Object

:nodoc:



1675
1676
1677
1678
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1675

def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil, returning: nil) # :nodoc:
  puts_log 'exec_insert'
  insert(sql)
end

#exec_insert_db2(sql, name = nil, binds = [], pk = nil, sequence_name = nil, returning = nil) ⇒ Object



1664
1665
1666
1667
1668
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1664

def exec_insert_db2(sql, name = nil, binds = [], pk = nil, sequence_name = nil, returning = nil)
  puts_log 'exec_insert_db2'
  sql, binds = sql_for_insert(sql, pk, binds, returning)
  exec_query_ret_stmt(sql, name, binds, prepare: false)
end

#exec_query_ret_stmt(sql, name = 'SQL', binds = [], prepare: false, async: false) ⇒ 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. Here prepare argument is not used, by default this method creates prepared statment and execute.



1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1762

def exec_query_ret_stmt(sql, name = 'SQL', binds = [], prepare: false, async: false)
  puts_log "exec_query_ret_stmt #{sql}"
  sql = transform_query(sql)
  check_if_write_query(sql)
#materialize_transactions
  mark_transaction_written_if_write(sql)
  begin
    puts_log "SQL = #{sql}"
    puts_log "Binds = #{binds}"
    param_array = type_casted_binds(binds)
    puts_log "Param array = #{param_array}"
    puts_log "Prepare flag = #{prepare}"
    puts_log "#{caller}"

    stmt = @servertype.prepare(sql, name)
    @statements[sql] = stmt if prepare

    puts_log "Statement = #{stmt}"
    log(sql, name, binds, param_array, async: async) do
      with_raw_connection do |conn|
        return false unless stmt
        return stmt if execute_prepared_stmt(stmt, param_array)
      end
    end
  rescue => e
    raise translate_exception_class(e, sql, binds)
  ensure
    @offset = @limit = nil
  end
end

#execute(sql, name = nil, allow_retry: false) ⇒ Object

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



1829
1830
1831
1832
1833
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1829

def execute(sql, name = nil, allow_retry: false)
  puts_log "execute #{sql}"
  ActiveRecord::Base.clear_query_caches_for_current_thread
  internal_execute(sql, name, allow_retry: allow_retry)
end

#execute_prepared_stmt(pstmt, param_array = nil) ⇒ Object

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



1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1722

def execute_prepared_stmt(pstmt, param_array = nil)
  puts_log 'execute_prepared_stmt'
  puts_log "Param array = #{param_array}"
  param_array = nil if !param_array.nil? && param_array.size < 1

  if !IBM_DB.execute(pstmt, param_array)
    error_msg = IBM_DB.getErrormsg(pstmt, IBM_DB::DB_STMT)
    puts_log "Error = #{error_msg}"
    IBM_DB.free_stmt(pstmt) if pstmt
    raise StatementInvalid, error_msg
  else
    true
  end
end

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



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

def explain(arel, binds = [])
  sql = "EXPLAIN ALL SET QUERYNO = 1 FOR #{to_sql(arel, binds)}"
  stmt = execute(sql, 'EXPLAIN')
  result = select("select * from explain_statement where explain_level = 'P' and queryno = 1", 'EXPLAIN')
  result[0]['total_cost'].to_s
# Ensures to free the resources associated with the statement
ensure
  IBM_DB.free_stmt(stmt) if stmt
end

#extract_default_function(default_value, default) ⇒ Object



2786
2787
2788
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2786

def extract_default_function(default_value, default)
  default if has_default_function?(default_value, default)
end

#extract_foreign_key_action(specifier) ⇒ Object

:nodoc:



2881
2882
2883
2884
2885
2886
2887
2888
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2881

def extract_foreign_key_action(specifier) # :nodoc:
  puts_log 'extract_foreign_key_action'
  case specifier
  when 0 then :cascade
  when 1 then :restrict
  when 2 then :nullify
  end
end

#extract_precision(sql_type) ⇒ Object



2782
2783
2784
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2782

def extract_precision(sql_type)
  ::Regexp.last_match(1).to_i if sql_type =~ /\((\d+)(,\d+)?\)/
end

#extract_value_from_default(default) ⇒ Object

method simplified_type



2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2629

def extract_value_from_default(default)
  case default
  when /IDENTITY GENERATED BY DEFAULT/i
    nil
  when /^null$/i
    nil
  # Quoted types
  when /^'(.*)'$/m
    ::Regexp.last_match(1).gsub("''", "'")
  # Quoted types
  when /^"(.*)"$/m
    ::Regexp.last_match(1).gsub('""', '"')
  # Numeric types
  when /\A-?\d+(\.\d*)?\z/
    ::Regexp.last_match(0)
  else
    # Anything else is blank or some function
    # and we can't know the value of that, so return nil.
    nil
  end
end

#fetch_data(stmt) ⇒ Object

Calls the servertype select method to fetch the data



1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1363

def fetch_data(stmt)
  puts_log 'fetch_data'
  return unless stmt

  begin
    @servertype.select(stmt)
  rescue StandardError => e # Handle driver fetch errors
    error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT)
    raise StatementInvalid, "Failed to retrieve data: #{error_msg}" if error_msg && !error_msg.empty?

    error_msg += ": #{e.message}" unless e.message.empty?
   #raise error_msg
  ensure
    # Ensures to free the resources associated with the statement
    if stmt
      puts_log "Free Statement #{stmt}"
      IBM_DB.free_stmt(stmt)
    end
  end
end

#foreign_keys(table_name) ⇒ Object



2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2794

def foreign_keys(table_name)
  puts_log "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 = []
  fks_temp = []
  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))
        puts_log "foreign_keys fetch = #{fk_row}"
        options = {
          column: fk_row[7].downcase,
          name: fk_row[11].downcase,
          primary_key: fk_row[3].downcase
        }
        options[:on_update] = extract_foreign_key_action(fk_row[9])
        options[:on_delete] = extract_foreign_key_action(fk_row[10])
        fks_temp << ForeignKeyDefinition.new(fk_row[6].downcase, fk_row[2].downcase, options)
      end

      fks_temp.each do |fkst|
        comb = false
        if foreignKeys.size > 0
          foreignKeys.each_with_index do |fks, ind|
            if fks.name == fkst.name
              if foreignKeys[ind].column.kind_of?(Array)
                foreignKeys[ind].column << fkst.column
                foreignKeys[ind].primary_key << fkst.primary_key
              else
                options = {
                  name: fks.name,
                  on_update: nil,
                  on_delete: nil
                }

                options[:column] = []
                options[:column] << fks.column
                options[:column] << fkst.column

                options[:primary_key] = []
                options[:primary_key] << fks.primary_key
                options[:primary_key] << fkst.primary_key

                foreignKeys[ind] = ForeignKeyDefinition.new(fks.from_table, fks.to_table, options)
              end
              comb = true
              break
            end
          end
          foreignKeys << fkst if !comb
        else
          foreignKeys << fkst
        end
      end

    rescue StandardError => e # Handle driver fetch errors
      puts_log "foreign_keys e = #{e}"
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT)
      raise "Failed to retrieve foreign key metadata during fetch: #{error_msg}" if error_msg && !error_msg.empty?

      error_msg = 'An unexpected error occurred during retrieval of foreign key metadata'
      error_msg += ": #{e.message}" unless e.message.empty?
    #             raise error_msg
    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)
    raise "Failed to retrieve foreign key metadata due to error: #{error_msg}" if error_msg && !error_msg.empty?

    raise StandardError.new('An unexpected error occurred during foreign key retrieval')

  end
  # Returns the foreignKeys array
  foreignKeys
end

#get_database_versionObject



1045
1046
1047
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1045

def get_database_version
  @database_version
end

#has_default_function?(default_value, default) ⇒ Boolean

Returns:

  • (Boolean)


2790
2791
2792
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2790

def has_default_function?(default_value, default)
  !default_value && /\w+\(.*\)|CURRENT_TIME|CURRENT_DATE|CURRENT_TIMESTAMP/.match?(default)
end

#indexes(table_name, _name = nil) ⇒ Object

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



2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2426

def indexes(table_name, _name = nil)
  puts_log 'indexes'
  puts_log "Table = #{table_name}"
  # 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))
        puts_log "Primary keys = #{pk_index_row}"
        puts_log "pk_index = #{pk_index}"
        next unless 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
        else
          pk_index = IndexDefinition.new(table_name, pk_index_name, true, pk_index_columns)
        end
      end
    rescue StandardError => e # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT)
      raise "Failed to retrieve primarykey metadata during fetch: #{error_msg}" if error_msg && !error_msg.empty?

      error_msg = 'An unexpected error occurred during retrieval of primary key metadata'
      error_msg += ": #{e.message}" unless e.message.empty?
      raise error_msg
    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)
    raise "Failed to retrieve primary key metadata due to error: #{error_msg}" if error_msg && !error_msg.empty?

    raise StandardError.new('An unexpected error occurred during primary key retrieval')

  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
        next unless 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 += 1
        end

        next if is_composite

        sql = "select remarks from syscat.indexes where tabname = #{quote(table_name.upcase)} and indname = #{quote(index_stats[5])}"
        comment = single_value_from_rows(select_prepared(sql, "SCHEMA").rows)

        indexes << IndexDefinition.new(table_name, index_name, index_unique, index_columns,
                                       comment: comment)
        index_schema << index_qualifier
      end
    rescue StandardError => e # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT)
      raise "Failed to retrieve index metadata during fetch: #{error_msg}" if error_msg && !error_msg.empty?

      error_msg = 'An unexpected error occurred during retrieval of index metadata'
      error_msg += ": #{e.message}" unless e.message.empty?
      raise error_msg
    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)
    raise "Failed to retrieve index metadata due to error: #{error_msg}" if error_msg && !error_msg.empty?

    raise StandardError.new('An unexpected error occurred during index retrieval')

  end

  # remove the primary key index entry.... should not be dumped by the dumper

  puts_log "Indexes 1 = #{pk_index}"
  i = 0
  indexes.each do |index|
    indexes.delete_at(i) if pk_index && index.columns == pk_index.columns
    i += 1
  end
  # Returns the indexes array
  puts_log "Indexes 2 = #{indexes}"
  indexes
end

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



1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1636

def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [], returning: nil)
  puts_log "insert Binds P = #{binds}"
  puts_log caller
  if @arelVersion < 6
    sql = to_sql(arel)
    binds = binds
  else
    sql, binds = to_sql_and_binds(arel, binds)
  end

  puts_log "insert Binds A = #{binds}"
  puts_log "insert SQL = #{sql}"
  # unless IBM_DBAdapter.respond_to?(:exec_insert)
  return insert_direct(sql, name, pk, id_value, sequence_name, returning: returning) if binds.nil? || binds.empty?

  ActiveRecord::Base.clear_query_caches_for_current_thread

  return unless stmt = exec_insert_db2(sql, name, binds, pk, sequence_name, returning)

  begin
    @sql << sql
    return [@servertype.last_generated_id(stmt)] unless returning.nil?
    id_value || @servertype.last_generated_id(stmt)
  ensure
    IBM_DB.free_stmt(stmt) if stmt
  end
end

#insert_direct(sql, name = nil, _pk = nil, id_value = nil, _sequence_name = nil, returning: 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.



1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1617

def insert_direct(sql, name = nil, _pk = nil, id_value = nil, _sequence_name = nil, returning: nil)
  puts_log 'insert_direct'
  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

  return unless stmt = execute(sql, name)

  begin
    @sql << sql
    return [@servertype.last_generated_id(stmt)] unless returning.nil?
    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

#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



1541
1542
1543
1544
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
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1541

def insert_fixture(fixture, table_name)
  puts_log "insert_fixture = #{fixture}"
  insert_query = if fixture.respond_to?(:keys)
                   "INSERT INTO #{quote_table_name(table_name)} ( #{fixture.keys.join(', ')})"
                 else
                   "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}"
    end

    raise StandardError.new('An unexpected error occurred during preparing SQL for fixture insert')

  end

  log(insert_query, 'fixture insert') do
    if IBM_DB.execute(stmt, insert_values)
      IBM_DB.free_stmt(stmt) if stmt
    else
      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}"
    end
  end
end

#internal_exec_query(sql, name = 'SQL', binds = [], prepare: false, async: false) ⇒ Object



1793
1794
1795
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1793

def internal_exec_query(sql, name = 'SQL', binds = [], prepare: false, async: false)
  select_prepared(sql, name, binds, prepare: prepare, async: async)
end

#last_inserted_id(result) ⇒ Object



1670
1671
1672
1673
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1670

def last_inserted_id(result)
  puts_log 'last_inserted_id'
  result
end

#log_query(sql, name) ⇒ Object

:nodoc:



1192
1193
1194
1195
1196
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1192

def log_query(sql, name) # :nodoc:
  puts_log 'log_query'
  # 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



2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2106

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' },
    vargraphic: { name: 'vargraphic' },
    bigint: { name: 'bigint' }
  }
end

#prepare(sql, name = nil) ⇒ Object

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



1710
1711
1712
1713
1714
1715
1716
1717
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1710

def prepare(sql, name = nil)
  puts_log 'prepare'
  # 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.



1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1684

def prepared_insert(pstmt, param_array = nil, id_value = nil)
  puts_log 'prepared_insert'
  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

  ActiveRecord::Base.clear_query_caches_for_current_thread

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

#prepared_statements?Boolean Also known as: prepared_statements

Returns:

  • (Boolean)


1049
1050
1051
1052
1053
1054
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1049

def prepared_statements?
  puts_log 'prepared_statements?'
  prepare = @prepared_statements && !prepared_statements_disabled_cache.include?(object_id)
  puts_log "prepare = #{prepare}"
  prepare
end

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

Praveen



1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1874

def prepared_update(pstmt, param_array = nil)
  puts_log 'prepared_update'
  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

  ActiveRecord::Base.clear_query_caches_for_current_thread

  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 => e
    raise e
  ensure
    IBM_DB.free_stmt(pstmt) if pstmt
  end
end

#primary_key(table_name) ⇒ Object

Returns the primary key of the mentioned table



2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2387

def primary_key(table_name)
  puts_log 'primary_key'
  pk_name = []
  stmt = IBM_DB.primary_keys(@connection, nil,
                             @servertype.set_case(@schema),
                             @servertype.set_case(table_name.to_s))
  if stmt
    begin
      while (pk_index_row = IBM_DB.fetch_array(stmt))
        puts_log "Primary_keys = #{pk_index_row}"
        pk_name << pk_index_row[3].downcase
      end
    rescue StandardError => e # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT)
      raise "Failed to retrieve primarykey metadata during fetch: #{error_msg}" if error_msg && !error_msg.empty?

      error_msg = 'An unexpected error occurred during retrieval of primary key metadata'
      error_msg += ": #{e.message}" unless e.message.empty?
      raise error_msg
    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)
    raise "Failed to retrieve primary key metadata due to error: #{error_msg}" if error_msg && !error_msg.empty?

    raise StandardError.new('An unexpected error occurred during primary key retrieval')

  end
  if pk_name.length == 1
    pk_name[0]
  elsif pk_name.empty?
    nil
  else
    pk_name
  end
end

#primary_keys(table_name) ⇒ Object

:nodoc:

Raises:

  • (ArgumentError)


2914
2915
2916
2917
2918
2919
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2914

def primary_keys(table_name) # :nodoc:
  puts_log 'primary_keys'
  raise ArgumentError unless table_name.present?

  primary_key(table_name)
end

#puts_log(val) ⇒ Object



1206
1207
1208
1209
1210
1211
1212
1213
1214
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1206

def puts_log(val)
  begin
  #         puts val
  rescue StandardError
  end
  return unless @debug == true

  log(" IBM_DB = #{val}", 'TRANSACTION') {}
end

#query_values(sql, _name = nil) ⇒ Object

:nodoc:



2991
2992
2993
2994
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2991

def query_values(sql, _name = nil) # :nodoc:
  puts_log 'query_values'
  select_prepared(sql).rows.map(&:first)
end

#quote_column_name(name) ⇒ Object



2091
2092
2093
2094
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2091

def quote_column_name(name)
  puts_log 'quote_column_name'
  @servertype.check_reserved_words(name).gsub('"', '').gsub("'", '')
end

#quote_schema_name(schema_name) ⇒ Object



3336
3337
3338
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3336

def quote_schema_name(schema_name)
  quote_table_name(schema_name)
end

#quote_string(string) ⇒ Object

Quotes a given string, escaping single quote (‘) characters.



2050
2051
2052
2053
2054
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2050

def quote_string(string)
  puts_log 'quote_string'
  string.gsub(/'/, "''")
  # string.gsub('\\', '\&\&').gsub("'", "''")
end

#quote_table_name(name) ⇒ Object



2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2079

def quote_table_name(name)
  puts_log "quote_table_name #{name}"
  if name.start_with? '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
    name = "\"#{name}\""
  else
    name = name.to_s
  end
  puts_log "name = #{name}"
  name
  # @servertype.check_reserved_words(name).gsub('"', '').gsub("'",'')
end

#quote_value_for_pstmt(value, column = nil) ⇒ Object

QUOTING



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
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2020

def quote_value_for_pstmt(value, column = nil)
  puts_log 'quote_value_for_pstmt'
  return value.quoted_id if value.respond_to?(:quoted_id)

  case value
  when String, ActiveSupport::Multibyte::Chars
    value = value.to_s
    if column && column.sql_type.to_s =~ /int|serial|float/i
      column.sql_type.to_s =~ /int|serial/i ? value.to_i : value.to_f

    else
      value
    end
  when NilClass                 then nil
  when TrueClass                then 1
  when FalseClass               then 0
  when Float, Integer, Integer 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_binary(value) ⇒ Object



2096
2097
2098
2099
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2096

def quoted_binary(value)
  puts_log 'quoted_binary'
  "CAST(x'#{value.hex}' AS BLOB)"
end

#quoted_falseObject



2064
2065
2066
2067
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2064

def quoted_false
  puts_log 'quoted_false'
  '0'.freeze
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.



2059
2060
2061
2062
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2059

def quoted_true
  puts_log 'quoted_true'
  '1'.freeze
end

#raw_execute(sql, name, async: false, allow_retry: false, materialize_transactions: true) ⇒ Object



1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1835

def raw_execute(sql, name, async: false, allow_retry: false, materialize_transactions: true)
  # 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')
  puts_log "raw_execute #{sql} #{Thread.current}"
  log(sql, name, async: async) do
    with_raw_connection(allow_retry: allow_retry, materialize_transactions: materialize_transactions) do |conn|
      verify!
      puts_log "raw_execute executes query #{Thread.current}"
      result = @servertype.execute(sql, name)
      puts_log "raw_execute result = #{result} #{Thread.current}"
      verified!
      result
    end
  end
end

#reconnectObject

Closes the current connection and opens a new one



1290
1291
1292
1293
1294
1295
1296
1297
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1290

def reconnect
  puts_log "reconnect #{caller} #{Thread.current}"
#disconnect!
  @lock.synchronize do
    puts_log "Before reconnection = #{@connection}, #{Thread.current}"
    connect unless @connection
  end
end

#remove_column(table_name, column_name, _type = nil, **options) ⇒ Object

Removes the column from the table definition.

Examples
remove_column(:suppliers, :qualification)


3246
3247
3248
3249
3250
3251
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3246

def remove_column(table_name, column_name, _type = nil, **options)
  puts_log 'remove_column'
  return if options[:if_exists] == true && !column_exists?(table_name, column_name)

  @servertype.remove_column(table_name, column_name)
end

#remove_columns(table_name, *column_names, type: nil, **options) ⇒ Object



3076
3077
3078
3079
3080
3081
3082
3083
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3076

def remove_columns(table_name, *column_names, type: nil, **options)
  if column_names.empty?
    raise ArgumentError.new('You must specify at least one column name. Example: remove_columns(:people, :first_name)')
  end

  remove_column_fragments = remove_columns_for_alter(table_name, *column_names, type: type, **options)
  execute "ALTER TABLE #{quote_table_name(table_name)} #{remove_column_fragments.join(' ')}"
end

#remove_foreign_key_byColumn(fkey_list, table_name, column_name) ⇒ Object



3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3217

def remove_foreign_key_byColumn(fkey_list, table_name, column_name)
  puts_log "remove_foreign_key_byColumn = #{table_name}, #{column_name}, #{fkey_list}"
  fkey_removed = false
  fkey_list.each do |fkey|
    if fkey.options[:column] == column_name
      remove_foreign_key(table_name, column: column_name)
      fkey_removed = true
    end
  end
  fkey_removed
end

#remove_index(table_name, column_name = nil, **options) ⇒ Object



3460
3461
3462
3463
3464
3465
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3460

def remove_index(table_name, column_name = nil, **options)
  puts_log "remove_index table_name = #{table_name}, column_name = #{column_name}, options = #{options}"
  return if options[:if_exists] && !index_exists?(table_name, column_name, **options)

  execute("DROP INDEX #{index_name_for_remove(table_name, column_name, options)}")
end

#remove_unique_constraint(table_name, column_name = nil, **options) ⇒ Object



3411
3412
3413
3414
3415
3416
3417
3418
3419
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3411

def remove_unique_constraint(table_name, column_name = nil, **options)
  puts_log "remove_unique_constraint table_name = #{table_name}, column_name = #{column_name}, options = #{options}"
  unique_name_to_delete = unique_constraint_for!(table_name, column: column_name, **options).name

  at = create_alter_table(table_name)
  at.drop_unique_constraint(unique_name_to_delete)

  execute schema_creation.accept(at)
end

#remove_unique_constraint_byColumn(unique_indexes) ⇒ Object



3201
3202
3203
3204
3205
3206
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3201

def remove_unique_constraint_byColumn(unique_indexes)
  puts_log "remove_unique_constraint_byColumn = #{unique_indexes}"
  unique_indexes.each do |unq|
    remove_unique_constraint(unq.table_name, unq.column, name: unq.name)
  end
end

#rename_column(table_name, column_name, new_column_name) ⇒ Object

Renames a column in a table.



3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3172

def rename_column(table_name, column_name, new_column_name) # :nodoc:
  puts_log 'rename_column'
  column_name = quote_column_name(column_name)
  new_column_name = quote_column_name(new_column_name)
  puts_log "rename_column #{table_name}, #{column_name}, #{new_column_name}"
  clear_cache!
  unique_indexes = unique_constraints(table_name)
  puts_log "rename_column Unique Indexes = #{unique_indexes}"
  remove_unique_constraint_byColumn(unique_indexes)
  index_list = indexes(table_name)
  puts_log "rename_column Index List = #{index_list}"
  fkey_list = foreign_keys(table_name)
  puts_log "rename_column ForeignKey = #{fkey_list}"
  drop_column_indexes(index_list, column_name)
  fkey_removed = remove_foreign_key_byColumn(fkey_list, table_name, column_name)
  execute("ALTER TABLE #{quote_table_name(table_name)} #{rename_column_sql(table_name, column_name,
                                                                           new_column_name)}")
  add_unique_constraint_byColumn(unique_indexes, new_column_name)
  add_foreign_keyList(fkey_list, table_name, column_name, new_column_name) if fkey_removed
  create_column_indexes(index_list, column_name, new_column_name)
end

#rename_index(table_name, old_name, new_name) ⇒ Object



3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3229

def rename_index(table_name, old_name, new_name)
  puts_log 'rename_index'
  old_name = old_name.to_s
  new_name = new_name.to_s
  validate_index_length!(table_name, new_name)

  # this is a naive implementation; some DBs may support this more efficiently (PostgreSQL, for instance)
  old_index_def = indexes(table_name).detect { |i| i.name == old_name }
  return unless old_index_def

  remove_index(table_name, name: old_name)
  add_index(table_name, old_index_def.columns, name: new_name, unique: old_index_def.unique)
end

#rename_table(name, new_name, **options) ⇒ Object

Renames a table.

Example

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



3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3089

def rename_table(name, new_name, **options)
  puts_log 'rename_table'
  validate_table_length!(new_name) unless options[:_uses_legacy_table_name]
  clear_cache!
  schema_cache.clear_data_source_cache!(name.to_s)
  schema_cache.clear_data_source_cache!(new_name.to_s)
  name = quote_column_name(name)
  new_name = quote_column_name(new_name)
  puts_log "90 old_table = #{name}, new_table = #{new_name}"
  # SQL rename table statement
  index_list = indexes(name)
  puts_log "Index List = #{index_list}"
  drop_table_indexes(index_list)
  rename_table_sql = "RENAME TABLE #{name} TO #{new_name}"
  stmt = execute(rename_table_sql)
  create_table_indexes(index_list, new_name)
# Ensures to free the resources associated with the statement
ensure
  IBM_DB.free_stmt(stmt) if stmt
end

#reset!Object



1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1278

def reset!
  puts_log "reset! #{caller} #{Thread.current}"
  @lock.synchronize do
    return connect! unless @connection

    rollback_db_transaction

    super
  end
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



1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1995

def rollback_db_transaction
  puts_log 'rollback_db_transaction'
  log('rollback transaction', 'TRANSACTION') do
    with_raw_connection(allow_retry: true, materialize_transactions: false) do |conn|
      # ROLLBACK the transaction

      IBM_DB.rollback(@connection)
    end
  rescue StandardError
    nil
  end
  ActiveRecord::Base.clear_query_caches_for_current_thread
  # Turns on auto-committing
  auto_commit_on
end

#select(sql, name = nil, binds = [], prepare: false, async: false) ⇒ Object



1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1384

def select(sql, name = nil, binds = [], prepare: false, async: false)
  puts_log "select #{sql}"
  puts_log "binds = #{binds}"
  puts_log "prepare = #{prepare}"

  # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"
  begin
    sql.gsub(/(=\s*NULL|IN\s*\(NULL\))/i, ' IS NULL')
  rescue StandardError
    # ...
  end

  if async && async_enabled?
    if current_transaction.joinable?
      raise AsynchronousQueryInsideTransactionError, 'Asynchronous queries are not allowed inside transactions'
    end

    future_result = async.new(
      pool,
      sql,
      name,
      binds,
      prepare: prepare
    )
    if supports_concurrent_connections? && current_transaction.closed?
      future_result.schedule!(ActiveRecord::Base.asynchronous_queries_session)
    else
      future_result.execute!(self)
    end
    return future_result
  end

  results = []

  stmt = if binds.nil? || binds.empty?
           internal_execute(sql, name)
         else
           exec_query_ret_stmt(sql, name, binds, prepare: prepare, async: async)
         end

  cols = IBM_DB.resultCols(stmt)

  if stmt
    results = fetch_data(stmt)
    puts_log "Results = #{results}"
  end

  if @isAr3
    results
  else
    results = ActiveRecord::Result.new(cols, results)
    if async
      results = ActiveRecord::FutureResult::Complete.new(results)
    end
  end

  results
end

#select_prepared(sql, name = nil, binds = [], prepare: true, async: false) ⇒ Object



1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1797

def select_prepared(sql, name = nil, binds = [], prepare: true, async: false)
  puts_log 'select_prepared'
  puts_log "select_prepared sql before = #{sql}"
  puts_log "select_prepared Binds = #{binds}"
  stmt = exec_query_ret_stmt(sql, name, binds, prepare: prepare, async: async)
  if !/^select .*/i.match(sql).nil?
    cols = IBM_DB.resultCols(stmt)

    results = fetch_data(stmt) if stmt

    puts_log "select_prepared columns = #{cols}"
    puts_log "select_prepared sql after = #{sql}"
    puts_log "select_prepared result = #{results}"
  else
    cols = nil
    results = nil
  end
  if @isAr3
    results
  else
    ActiveRecord::Result.new(cols, results)
  end
end

#simplified_type(field_type) ⇒ Object

Mapping IBM data servers SQL datatypes to Ruby data types



2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2590

def simplified_type(field_type)
  puts_log 'simplified_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
    :datetime
  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



2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2550

def simplified_type2(field_type)
  puts_log 'simplified_type2'
  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_comments?Boolean

Returns:

  • (Boolean)


1184
1185
1186
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1184

def supports_comments?
  true
end

#supports_common_table_expressions?Boolean

Returns:

  • (Boolean)


1137
1138
1139
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1137

def supports_common_table_expressions?
  true
end

#supports_datetime_with_precision?Boolean

Returns:

  • (Boolean)


1161
1162
1163
1164
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1161

def supports_datetime_with_precision?
  puts_log '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)


1169
1170
1171
1172
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1169

def supports_ddl_transactions?
  puts_log 'supports_ddl_transactions?'
  true
end

#supports_disable_referential_integrity?Boolean

:nodoc:

Returns:

  • (Boolean)


2890
2891
2892
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2890

def supports_disable_referential_integrity? # :nodoc:
  true
end

#supports_explain?Boolean

Returns:

  • (Boolean)


1174
1175
1176
1177
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1174

def supports_explain?
  puts_log 'supports_explain?'
  true
end

#supports_foreign_keys?Boolean

Returns:

  • (Boolean)


1202
1203
1204
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1202

def supports_foreign_keys?
  true
end

#supports_lazy_transactions?Boolean

Returns:

  • (Boolean)


1179
1180
1181
1182
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1179

def supports_lazy_transactions?
  puts_log 'supports_lazy_transactions?'
  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)


1151
1152
1153
1154
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1151

def supports_migrations?
  puts_log 'supports_migrations?'
  true
end

#supports_partitioned_indexes?Boolean

Returns:

  • (Boolean)


1198
1199
1200
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1198

def supports_partitioned_indexes?
  true
end

#supports_unique_constraints?Boolean

Does this adapter support creating unique constraints?

Returns:

  • (Boolean)


1142
1143
1144
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1142

def supports_unique_constraints?
  true
end

#supports_views?Boolean

Returns:

  • (Boolean)


1188
1189
1190
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1188

def supports_views?
  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



2307
2308
2309
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2307

def table_alias_length
  128
end

#table_comment(table_name) ⇒ Object

:nodoc:



2965
2966
2967
2968
2969
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2965

def table_comment(table_name) # :nodoc:
  puts_log 'table_comment'
  sql = "select remarks from syscat.tables where tabname = #{quote(table_name.upcase)}"
  single_value_from_rows(select_prepared(sql).rows)
end

#table_exists?(table_name) ⇒ Boolean

Checks to see if the table table_name exists on the database.

table_exists?(:developers)

Returns:

  • (Boolean)


3031
3032
3033
3034
3035
3036
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3031

def table_exists?(table_name)
  puts_log "table_exists? = #{table_name}"
  query_values(data_source_sql(table_name, type: 'T'), 'SCHEMA').any? if table_name.present?
rescue NotImplementedError
  tables.include?(table_name.to_s)
end

#table_options(table_name) ⇒ Object

:nodoc:



3069
3070
3071
3072
3073
3074
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3069

def table_options(table_name) # :nodoc:
  puts_log 'table_options'
  return unless comment = table_comment(table_name)

  { comment: comment }
end

#tablesObject

Returns an array of table names defined in the database.



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
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2312

def tables(_name = nil)
  puts_log 'tables'
  # 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 => e # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT)
      raise "Failed to retrieve table metadata during fetch: #{error_msg}" if error_msg && !error_msg.empty?

      error_msg = 'An unexpected error occurred during retrieval of table metadata'
      error_msg += ": #{e.message}" unless e.message.empty?
      raise error_msg
    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)
    raise "Failed to retrieve tables metadata due to error: #{error_msg}" if error_msg && !error_msg.empty?

    raise StandardError.new('An unexpected error occurred during retrieval of table metadata')

  end
  # Returns the tables array
  tables
end

#text_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


3332
3333
3334
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3332

def text_type?(type)
  TYPE_MAP.lookup(type).is_a?(Type::String) || TYPE_MAP.lookup(type).is_a?(Type::Text)
end

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



1126
1127
1128
1129
1130
1131
1132
1133
1134
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1126

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

#translate_exception(exception, message:, sql:, binds:) ⇒ Object



1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1443

def translate_exception(exception, message:, sql:, binds:)
  puts_log "translate_exception - #{message}"
  error_msg1 = /SQL0803N  One or more values in the INSERT statement, UPDATE statement, or foreign key update caused by a DELETE statement are not valid because the primary key, unique constraint or unique index identified by .* constrains table .* from having duplicate values for the index key/
  error_msg2 = /SQL0204N  .* is an undefined name/
  error_msg3 = /SQL0413N  Overflow occurred during numeric data type conversion/
  error_msg4 = /SQL0407N  Assignment of a NULL value to a NOT NULL column .* is not allowed/
  error_msg5 = /SQL0530N  The insert or update value of the FOREIGN KEY .* is not equal to any value of the parent key of the parent table/
  error_msg6 = /SQL0532N  A parent row cannot be deleted because the relationship .* restricts the deletion/
  error_msg7 = /SQL0433N  Value .* is too long/
  error_msg8 = /CLI0109E  String data right truncation/
  if !error_msg1.match(message).nil?
    puts_log 'RecordNotUnique exception'
    RecordNotUnique.new(message, sql: sql, binds: binds, connection_pool: @pool)
  elsif !error_msg2.match(message).nil?
    puts_log 'ArgumentError exception'
    ArgumentError.new(message)
  elsif !error_msg3.match(message).nil?
    puts_log 'RangeError exception'
    RangeError.new(message, sql: sql, binds: binds, connection_pool: @pool)
  elsif !error_msg4.match(message).nil?
    puts_log 'NotNullViolation exception'
    NotNullViolation.new(message, sql: sql, binds: binds, connection_pool: @pool)
  elsif !error_msg5.match(message).nil? or !error_msg6.match(message).nil?
    puts_log 'InvalidForeignKey exception'
    InvalidForeignKey.new(message, sql: sql, binds: binds, connection_pool: @pool)
  elsif !error_msg7.match(message).nil? or !error_msg8.match(message).nil?
    puts_log 'ValueTooLong exception'
    ValueTooLong.new(message, sql: sql, binds: binds, connection_pool: @pool)
  elsif exception.message.match?(/called on a closed database/i)
    puts_log 'ConnectionNotEstablished exception'
    ConnectionNotEstablished.new(exception, connection_pool: @pool)
  else
    super
  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.



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
2301
2302
2303
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2202

def type_to_sql(type, limit = nil, precision = nil, scale = nil)
  puts_log 'type_to_sql'
  puts_log "Type = #{type}, Limit = #{limit}"
  puts_log "type_to_sql = #{caller}"

  if type.to_sym == :binary and limit.class == Hash and limit.has_key?('limit'.to_sym)
    sql_segment = native_database_types[type.to_sym][:name].to_s
    sql_segment << "(#{limit[:limit]})"
    return sql_segment
  end

  if type.to_sym == :datetime and limit.class == Hash and limit.has_key?('precision'.to_sym)
    sql_segment = native_database_types[type.to_sym][:name].to_s
    if limit[:precision].nil?
      return sql_segment
    elsif (0..12).include?(limit[:precision])
      sql_segment << "(#{limit[:precision]})"
      return sql_segment
    else
      raise ArgumentError,
            "No #{sql_segment} type has precision of #{limit[:precision]}. The allowed range of precision is from 0 to 12"
    end
  end

  if type.to_sym == :string and limit.class == Hash and limit.has_key?('limit'.to_sym)
    sql_segment = native_database_types[type.to_sym][:name].to_s
    sql_segment << "(#{limit[:limit]})"
    return sql_segment
  end

  if type.to_sym == :decimal
    precision = limit[:precision] if limit.class == Hash && limit.has_key?('precision'.to_sym)
    scale = limit[:scale] if limit.class == Hash && limit.has_key?('scale'.to_sym)
    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})"
      return sql_segment
    elsif precision.nil? && !scale.nil?
      raise ArgumentError, 'Error adding decimal column: precision cannot be empty if scale is specified'
    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})" unless precision.nil?
    return sql_segment
  end

  if type.to_sym == :vargraphic
    sql_segment = native_database_types[type.to_sym][:name].to_s
    if limit.class == Hash
      return 'vargraphic(1)' unless limit.has_key?('limit'.to_sym)

      limit1 = limit[:limit]
      sql_segment << "(#{limit1})"

    else
      return 'vargraphic(1)' if limit.nil?

      sql_segment << "(#{limit})"

    end
    return sql_segment
  end

  if type.to_sym == :graphic
    sql_segment = native_database_types[type.to_sym][:name].to_s
    if limit.class == Hash
      return 'graphic(1)' unless limit.has_key?('limit'.to_sym)

      limit1 = limit[:limit]
      sql_segment << "(#{limit1})"

    else
      return 'graphic(1)' if limit.nil?

      sql_segment << "(#{limit})"

    end
    return sql_segment
  end

  if limit.class == Hash
    return super(type) if limit.has_key?('limit'.to_sym).nil?
  elsif limit.nil?
    return super(type)
  end

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

#unique_constraint_for(table_name, **options) ⇒ Object



3432
3433
3434
3435
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3432

def unique_constraint_for(table_name, **options)
  name = unique_constraint_name(table_name, **options) unless options.key?(:column)
  unique_constraints(table_name).detect { |unique_constraint| unique_constraint.defined_for?(name: name, **options) }
end

#unique_constraint_for!(table_name, column: nil, **options) ⇒ Object



3437
3438
3439
3440
3441
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3437

def unique_constraint_for!(table_name, column: nil, **options)
  puts_log "unique_constraint_for table_name = #{table_name}, column = #{column}, options = #{options}"
  unique_constraint_for(table_name, column: column, **options) ||
  raise(ArgumentError, "Table '#{table_name}' has no unique constraint for #{column || options}")
end

#unique_constraint_name(table_name, **options) ⇒ Object



3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3421

def unique_constraint_name(table_name, **options)
  puts_log "unique_constraint_name"
  options.fetch(:name) do
    column_or_index = Array(options[:column] || options[:using_index]).map(&:to_s)
    identifier = "#{table_name}_#{column_or_index * '_and_'}_unique"
    hashed_identifier = Digest::SHA256.hexdigest(identifier).first(10)

    "uniq_rails_#{hashed_identifier}"
  end
end

#unique_constraint_options(table_name, column_name, options) ⇒ Object

:nodoc:



3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3365

def unique_constraint_options(table_name, column_name, options) # :nodoc:
  assert_valid_deferrable(options[:deferrable])

  if column_name && options[:using_index]
    raise ArgumentError, "Cannot specify both column_name and :using_index options."
  end

  options = options.dup
  options[:name] ||= unique_constraint_name(table_name, column: column_name, **options)
  options
end

#unique_constraints(table_name) ⇒ Object

Returns an array of unique constraints for the given table. The unique constraints are represented as UniqueConstraintDefinition objects.



3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3379

def unique_constraints(table_name)
  puts_log "unique_constraints table_name = #{table_name}"
  puts_log "unique_constraints #{caller}"
  table_name = table_name.to_s
  if table_name.include?(".")
    schema_name, table_name = table_name.split(".")
    puts_log "unique_constraints split schema_name = #{schema_name}, table_name = #{table_name}"
  else
    schema_name = @schema
  end
  unique_info = internal_exec_query(<<~SQL, "SCHEMA")
    SELECT KEYCOL.CONSTNAME, KEYCOL.COLNAME FROM SYSCAT.KEYCOLUSE KEYCOL
        INNER JOIN SYSCAT.TABCONST TABCONST ON KEYCOL.CONSTNAME=TABCONST.CONSTNAME
        WHERE TABCONST.TABSCHEMA=#{quote(schema_name.upcase)} and
        TABCONST.TABNAME=#{quote(table_name.upcase)} and TABCONST.TYPE='U'
  SQL

  puts_log "unique_constraints unique_info = #{unique_info.columns}, #{unique_info.rows}"
  unique_info.map do |row|
    puts_log "unique_constraints row = #{row}"
    columns = []
    columns << row["colname"].downcase

    options = {
      name: row["constname"].downcase,
      deferrable: false
    }

    UniqueConstraintDefinition.new(table_name, columns, options)
  end
end

#unquoted_falseObject



2074
2075
2076
2077
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2074

def unquoted_false
  puts_log 'unquoted_false'
  0
end

#unquoted_trueObject



2069
2070
2071
2072
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2069

def unquoted_true
  puts_log 'unquoted_true'
  1
end

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



1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1903

def update(arel, name = nil, binds = [])
  puts_log 'update'
  if @arelVersion < 6
    sql = to_sql(arel)
  else
    sql, binds = to_sql_and_binds(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 += sqlarray[size - 1]
  end

  ActiveRecord::Base.clear_query_caches_for_current_thread

  if binds.nil? || binds.empty?
    update_direct(sql, name)
  else
    begin
      if stmt = exec_query_ret_stmt(sql, name, binds, prepare: true)
        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



1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1853

def update_direct(sql, name = nil)
  puts_log 'update_direct'
  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.
  return unless 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

#use_foreign_keys?Boolean

Returns:

  • (Boolean)


1156
1157
1158
1159
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1156

def use_foreign_keys?
  puts_log 'use_foreign_keys?'
  true
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


2196
2197
2198
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2196

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

#view_exists?(view_name) ⇒ Boolean

Checks to see if the view view_name exists on the database.

view_exists?(:ebooks)

Returns:

  • (Boolean)


3048
3049
3050
3051
3052
3053
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3048

def view_exists?(view_name)
  puts_log 'view_exists?'
  query_values(data_source_sql(view_name, type: 'V'), 'SCHEMA').any? if view_name.present?
rescue NotImplementedError
  views.include?(view_name.to_s)
end

#viewsObject

Returns an array of view names defined in the database.



2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2350

def views
  puts_log '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 => e # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT)
      raise "Failed to retrieve views metadata during fetch: #{error_msg}" if error_msg && !error_msg.empty?

      error_msg = 'An unexpected error occurred during retrieval of views metadata'
      error_msg += ": #{e.message}" unless e.message.empty?
      raise error_msg
    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)
    raise "Failed to retrieve tables metadata due to error: #{error_msg}" if error_msg && !error_msg.empty?

    raise StandardError.new('An unexpected error occurred during retrieval of views metadata')

  end
  # Returns the tables array
  tables
end

#write_query?(sql) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


1742
1743
1744
1745
1746
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1742

def write_query?(sql) # :nodoc:
  !READ_QUERY.match?(sql)
rescue ArgumentError # Invalid encoding
  !READ_QUERY.match?(sql.b)
end