Class: ActiveRecord::ConnectionAdapters::IBM_DBAdapter

Inherits:
AbstractAdapter
  • Object
show all
Includes:
QueryCache, Savepoints
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, Column, 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(args) ⇒ IBM_DBAdapter

Returns a new instance of IBM_DBAdapter.



793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 793

def initialize(args)
  # Caching database connection configuration (+connect+ or +reconnect+ support)\
  connection, ar3, config, conn_options = ActiveRecord::Base.ibm_db_connection(args)
  @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
  super(@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.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def 
  @account
end

#app_userObject

Returns the value of attribute app_user.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def app_user
  @app_user
end

#applicationObject

Returns the value of attribute application.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def application
  @application
end

#connectionObject (readonly)

Returns the value of attribute connection.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def connection
  @connection
end

#handle_lobs_triggeredObject

Returns the value of attribute handle_lobs_triggered.



660
661
662
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 660

def handle_lobs_triggered
  @handle_lobs_triggered
end

#pstmt_support_onObject (readonly)

Returns the value of attribute pstmt_support_on.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def pstmt_support_on
  @pstmt_support_on
end

#schemaObject

Returns the value of attribute schema.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def schema
  @schema
end

#servertypeObject (readonly)

Returns the value of attribute servertype.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def servertype
  @servertype
end

#set_quoted_literal_replacementObject (readonly)

Returns the value of attribute set_quoted_literal_replacement.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def set_quoted_literal_replacement
  @set_quoted_literal_replacement
end

#sqlObject

Returns the value of attribute sql.



660
661
662
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 660

def sql
  @sql
end

#sql_parameter_valuesObject

Returns the value of attribute sql_parameter_values.



660
661
662
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 660

def sql_parameter_values
  @sql_parameter_values
end

#workstationObject

Returns the value of attribute workstation.



658
659
660
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 658

def workstation
  @workstation
end

Class Method Details

.visitor_for(pool) ⇒ Object



977
978
979
980
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 977

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)


1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1093

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



663
664
665
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 663

def adapter_name
  'IBM_DB'
end

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

:nodoc:



2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2958

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



3222
3223
3224
3225
3226
3227
3228
3229
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3222

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:



2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2984

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:



3123
3124
3125
3126
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3123

def add_reference(table_name, ref_name, **options) # :nodoc:
  puts_log "add_reference table_name = #{table_name}, ref_name = #{ref_name}"
  super(table_name, ref_name, type: :integer, **options)
end

#add_timestamps(table_name, **options) ⇒ Object



2998
2999
3000
3001
3002
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2998

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



3370
3371
3372
3373
3374
3375
3376
3377
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3370

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



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

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



2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2915

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)


3525
3526
3527
3528
3529
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3525

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



1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1949

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



1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1938

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)



1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1961

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



920
921
922
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 920

def bind_params_length
  999
end

#build_change_column_default_definition(table_name, column_name, default_or_changes) ⇒ Object

:nodoc:



3307
3308
3309
3310
3311
3312
3313
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3307

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:



3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3315

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



2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2133

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



1378
1379
1380
1381
1382
1383
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
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1378

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



1424
1425
1426
1427
1428
1429
1430
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1424

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_insert_sql(insert) ⇒ Object

:nodoc:



1601
1602
1603
1604
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1601

def build_insert_sql(insert) # :nodoc:
  sql = +"INSERT #{insert.into} #{insert.values_list}"
  sql
end

#build_statement_poolObject



789
790
791
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 789

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

#build_truncate_statement(table_name) ⇒ Object



1373
1374
1375
1376
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1373

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)


3272
3273
3274
3275
3276
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3272

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



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

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.



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

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



3301
3302
3303
3304
3305
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3301

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



2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2946

def change_table_comment(table_name, comment_or_changes) # :nodoc:
  puts_log "change_table_comment table_name = #{table_name}, comment_or_changes = #{comment_or_changes}"
  clear_cache!
  comment = extract_new_comment_value(comment_or_changes)
  puts_log "change_table_comment new_comment = #{comment}"
  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)


1799
1800
1801
1802
1803
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1799

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

#closeObject

Check the connection back in to the connection pool



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

def close
  pool.checkin self
  disconnect!
end

#column_for(table_name, column_name) ⇒ Object



3538
3539
3540
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3538

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



2649
2650
2651
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
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2649

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 = #{execute_without_logging(sql).rows}"
  end

  pri_key = primary_key(table_name)

  if stmt
    begin
      # Fetches all the columns and assigns them to col.
      # +col+ is an hash with keys/value pairs for a column
      while col = IBM_DB.fetch_assoc(stmt)
        rowid = false
        puts_log "def columns fecthed = #{col}"
        column_name = col['column_name'].downcase
        sql = "select 1 FROM syscat.columns where tabname = #{quote(table_name.upcase)} and generated = 'D' and colname = '#{col['column_name']}'"
        rows = execute_without_logging(sql).rows
        auto_increment = rows.dig(0, 0) == 1 ? true : nil
        puts_log "def columns auto_increment = #{rows}, #{auto_increment}"

        # 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

        if Array(pri_key).include?(column_name) and column_type =~ /integer|bigint/i
          rowid = true
          puts_log "def columns rowid = true"
        end
        # 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'

        puts_log "Inside def columns() - default_value = #{default_value}, column_default_value = #{column_default_value}"
        default_function = extract_default_function(default_value, column_default_value)
        puts_log "Inside def columns() - default_function = #{default_function}"

         = 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'], auto_increment: auto_increment, rowid: rowid)
      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



1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1973

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

#connected?Boolean

Returns:

  • (Boolean)


1208
1209
1210
1211
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1208

def connected?
  puts_log "connected? #{@connection}"
  !(@connection.nil?)
end

#create_alter_table(name) ⇒ Object



3520
3521
3522
3523
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3520

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



3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3162

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



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

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_savepoint(name = current_savepoint_name) ⇒ Object



669
670
671
672
673
674
675
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 669

def create_savepoint(name = current_savepoint_name)
  puts_log 'create_savepoint'
  # Turns off auto-committing
  auto_commit_off
  # Create savepoint
  internal_execute("SAVEPOINT #{name} ON ROLLBACK RETAIN CURSORS", 'TRANSACTION')
end

#create_schema(schema_name, force: nil, if_not_exists: nil) ⇒ Object

Creates a schema for the given schema name.



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

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



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

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



1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1217

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 1 = #{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

  puts_log "create_table Options 2 = #{options}"
  super(name, id: id, primary_key: primary_key, force: force, **options)
end

#create_table_definition(name, **options) ⇒ Object



3514
3515
3516
3517
3518
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3514

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



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

def create_table_indexes(index_list, new_table)
  puts_log "create_table_indexes index_list = #{index_list}, new_table = #{new_table}"
  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



3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3009

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.



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

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:



2006
2007
2008
2009
2010
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2006

def default_sequence_name(table, column) # :nodoc:
  puts_log "default_sequence_name table = #{table}, column = #{column}"
  return nil if column.is_a?(Array)
  "#{table}_#{column}_seq"
end

#disable_referential_integrityObject

:nodoc:



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

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



1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1177

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
      @raw_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



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

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



3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3150

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



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

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.



3363
3364
3365
3366
3367
3368
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3363

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



3129
3130
3131
3132
3133
3134
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3129

def drop_table_indexes(index_list)
  puts_log "drop_table_indexes index_list = #{index_list}"
  index_list.each do |indexs|
    remove_index(indexs.table, name: indexs.name)
  end
end

#empty_insert_statement_value(pkey, table_name) ⇒ Object



1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1497

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:



1611
1612
1613
1614
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1611

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



1595
1596
1597
1598
1599
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1595

def exec_insert_db2(sql, name = nil, binds = [], pk = nil, sequence_name = nil, returning = nil)
  puts_log "exec_insert_db2 sql = #{sql}, name = #{name}, binds = #{binds}, pk = #{pk}, returning = #{returning}"
  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, allow_retry: 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.



1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1739

def exec_query_ret_stmt(sql, name = 'SQL', binds = [], prepare: false, async: false, allow_retry: false)
  puts_log "exec_query_ret_stmt #{sql}"
  sql = transform_query(sql)
  check_if_write_query(sql)
  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(allow_retry: allow_retry) 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.



1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1807

def execute(sql, name = nil, allow_retry: false)
  puts_log "execute #{sql}"
  ActiveRecord::Base.clear_query_caches_for_current_thread
  stmt = internal_execute(sql, name, allow_retry: allow_retry)
  cols = nil
  results = nil
  puts_log "raw_execute stmt = #{stmt}"
  if sql.strip.upcase.start_with?("SELECT") and stmt
    cols = IBM_DB.resultCols(stmt)
    results = fetch_data(stmt)

    puts_log "execute columns = #{cols}"
    puts_log "execute result = #{results}"
  end
  if results.nil? || results.empty?
    stmt
  else
    formatted = cols.each_with_index.map { |col, i| { col => results[i].first } }
    puts_log "raw_execute formatted = #{formatted}"
    formatted.to_s
  end
end

#execute_prepared_stmt(pstmt, param_array = nil) ⇒ Object

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



1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1658

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

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



1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1694

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

  sql = transform_query(sql)
  check_if_write_query(sql)
  mark_transaction_written_if_write(sql)
  cols = nil
  results = nil
  begin
    param_array = type_casted_binds(binds)
    puts_log "execute_without_logging Param array = #{param_array}"
    puts_log "execute_without_logging #{caller}"

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

    puts_log "execute_without_logging Statement = #{stmt}"

    execute_prepared_stmt(stmt, param_array)

    if stmt and sql.strip.upcase.start_with?("SELECT")
      cols = IBM_DB.resultCols(stmt)
      results = fetch_data(stmt) if stmt

      puts_log "execute_without_logging columns = #{cols}"
      puts_log "execute_without_logging result = #{results}"
    end
  rescue => e
    raise translate_exception_class(e, sql, binds)
  ensure
    @offset = @limit = nil
  end
  if @isAr3
    results
  elsif results.nil?
    ActiveRecord::Result.empty
  else
    ActiveRecord::Result.new(cols, results)
  end
end

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



1684
1685
1686
1687
1688
1689
1690
1691
1692
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1684

def explain(arel, binds = [], options = [])
  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



2797
2798
2799
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2797

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

#extract_foreign_key_action(specifier) ⇒ Object

:nodoc:



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

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



2793
2794
2795
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2793

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



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

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



1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1249

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_key_exists?(from_table, to_table = nil, **options) ⇒ Boolean

Returns:

  • (Boolean)


3493
3494
3495
3496
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3493

def foreign_key_exists?(from_table, to_table = nil, **options)
  puts_log "foreign_key_exists? from_table = #{from_table}, to_table = #{to_table}, options = #{options}"
  foreign_key_for(from_table, to_table: to_table, **options).present?
end

#foreign_key_for(from_table, **options) ⇒ Object



3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3473

def foreign_key_for(from_table, **options)
  puts_log "foreign_key_for from_table = #{from_table}, options = #{options}"
  return unless use_foreign_keys?
  fks = foreign_keys(from_table)
  puts_log "foreign_key_for fks = #{fks}"
  if options.key?(:column) && options.key?(:to_table) && options[:to_table] != nil
    name = foreign_key_name(from_table, options)
    puts_log "foreign_key_for name = #{options}"
    fks.detect { |fk| fk.defined_for?(name: name) }
  else
    fks.detect { |fk| fk.defined_for?(**options) }
  end
end

#foreign_key_for!(from_table, to_table: nil, **options) ⇒ Object



3487
3488
3489
3490
3491
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3487

def foreign_key_for!(from_table, to_table: nil, **options)
  puts_log "foreign_key_for! from_table = #{from_table}, to_table = #{to_table}, options = #{options}"
  foreign_key_for(from_table, to_table: to_table, **options) ||
    raise(ArgumentError, "Table '#{from_table}' has no foreign key for #{to_table || options}")
end

#foreign_key_name(table_name, options) ⇒ Object



3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3462

def foreign_key_name(table_name, options)
  puts_log "foreign_key_name table_name = #{table_name}, options = #{options}"
  options.fetch(:name) do
    columns = Array(options.fetch(:column)).map(&:to_s)
    identifier = "#{table_name}_#{columns * '_and_'}_fk"
    hashed_identifier = OpenSSL::Digest::SHA256.hexdigest(identifier).first(10)

    "fk_rails_#{hashed_identifier}"
  end
end

#foreign_keys(table_name) ⇒ Object



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
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2806

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



908
909
910
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 908

def get_database_version
  @database_version
end

#getTableIdentityColumn(table_name) ⇒ Object



1508
1509
1510
1511
1512
1513
1514
1515
1516
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1508

def getTableIdentityColumn(table_name)
  query = "SELECT COLNAME FROM SYSCAT.COLUMNS WHERE TABNAME = #{quote(table_name.upcase)} AND IDENTITY = 'Y'"
  puts_log "getTableIdentityColumn table_name = #{table_name}, query = #{query}"
  rows = execute_without_logging(query).rows
  puts_log "getTableIdentityColumn rows = #{rows}"
  if rows.any?
    return rows.first
  end
end

#has_default_function?(default_value, default) ⇒ Boolean

Returns:

  • (Boolean)


2801
2802
2803
2804
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2801

def has_default_function?(default_value, default)
  !default_value && /\w+\(.*\)|CURRENT_TIME|CURRENT_DATE|CURRENT_TIMESTAMP/.match?(default)
  !default_value && /(\w+\(.*\)|CURRENT(?:[_\s]TIME|[_\s]DATE|[_\s]TIMESTAMP))/i.match?(default)
end

#indexes(table_name, _name = nil) ⇒ Object

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



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

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(execute_without_logging(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



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

def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [], returning: nil)
  puts_log "insert Binds P = #{binds}, name = #{name}, pk = #{pk}, id_value = #{id_value}, returning = #{returning}"
  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, 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
    return_insert(stmt, sql, binds, pk, id_value, returning: returning)
  ensure
    IBM_DB.free_stmt(stmt) if stmt
  end
end

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



1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1552

def insert_direct(sql, name = nil, _pk = nil, id_value = nil, returning: nil)
  puts_log "insert_direct sql = #{sql}, name = #{name}, _pk = #{_pk}, returning = #{returning}"
  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
    return_insert(stmt, sql, nil, _pk, id_value, returning: returning)
    # 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



1435
1436
1437
1438
1439
1440
1441
1442
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
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1435

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



1769
1770
1771
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1769

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



1606
1607
1608
1609
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1606

def last_inserted_id(result)
  puts_log 'last_inserted_id'
  result
end

#log_query(sql, name) ⇒ Object

:nodoc:



1064
1065
1066
1067
1068
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1064

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



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

def native_database_types
  {
    primary_key: { name: @servertype.primary_key_definition(@start_id) },
    string: { name: 'varchar', limit: 400 },
    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.



1646
1647
1648
1649
1650
1651
1652
1653
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1646

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.



1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1620

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)


912
913
914
915
916
917
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 912

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



1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1869

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



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

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)


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

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



1078
1079
1080
1081
1082
1083
1084
1085
1086
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1078

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:



3004
3005
3006
3007
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3004

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

#quote_column_name(name) ⇒ Object



2088
2089
2090
2091
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2088

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

#quote_schema_name(schema_name) ⇒ Object



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

def quote_schema_name(schema_name)
  quote_table_name(schema_name)
end

#quote_string(string) ⇒ Object

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



2046
2047
2048
2049
2050
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2046

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

#quote_table_name(name) ⇒ Object



2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2075

def quote_table_name(name)
  puts_log "quote_table_name #{name}"
  puts_log caller
  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



2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2016

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



2093
2094
2095
2096
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2093

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

#quoted_falseObject



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

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.



2055
2056
2057
2058
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2055

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

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



1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1830

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 = #{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



1163
1164
1165
1166
1167
1168
1169
1170
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1163

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)


3260
3261
3262
3263
3264
3265
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3260

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



3089
3090
3091
3092
3093
3094
3095
3096
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3089

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(from_table, to_table = nil, **options) ⇒ Object



3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3498

def remove_foreign_key(from_table, to_table = nil, **options)
  puts_log "remove_foreign_key from_table = #{from_table}, to_table = #{to_table}, options = #{options}"
  #to_table ||= options[:to_table]
  return unless use_foreign_keys?
  #return if options.delete(:if_exists) == true && !foreign_key_exists?(from_table, to_table, **options.slice(:column))
  return if options.delete(:if_exists) == true && !foreign_key_exists?(from_table, to_table)

  fk_name_to_delete = foreign_key_for!(from_table, to_table: to_table, **options).name
  puts_log "remove_foreign_key fk_name_to_delete = #{fk_name_to_delete}"

  at = create_alter_table from_table
  at.drop_foreign_key fk_name_to_delete

  execute schema_creation.accept(at)
end

#remove_foreign_key_byColumn(fkey_list, table_name, column_name) ⇒ Object



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

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



3531
3532
3533
3534
3535
3536
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3531

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



3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3425

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

  puts_log "remove_unique_constraint unique_name_to_delete = #{unique_name_to_delete}"
  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



3215
3216
3217
3218
3219
3220
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3215

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.



3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3186

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



3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3243

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



3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3102

def rename_table(name, new_name, **options)
  puts_log "rename_table name = #{name}, new_name = #{new_name}"
  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



1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1151

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

    rollback_db_transaction

    super
  end
end

#return_insert(stmt, sql, binds, pk, id_value = nil, returning: nil) ⇒ Object



1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1518

def return_insert (stmt, sql, binds, pk, id_value = nil, returning: nil)
  puts_log "return_insert sql = #{sql}, pk = #{pk}, returning = #{returning}"
  @sql << sql

  table_name = sql[/\AINSERT\s+INTO\s+([^\s\(]+)/i, 1]
  rowID = getTableIdentityColumn(table_name)
  #Identity column exist.
  if Array(rowID).any?
    val = @servertype.last_generated_id(stmt)
    #returning required is just an ID, or nothing is expected to return
    only_returning_id = Array(returning).empty? ||
                       (Array(returning).size == 1 && Array(rowID).first == Array(returning).first)
    unless only_returning_id
      cols = Array(returning).join(', ')
      query = "SELECT #{cols} FROM #{table_name} WHERE #{Array(rowID).first} = #{val}"
      puts_log "return_insert val = #{val}, cols = #{cols}, table_name = #{table_name}"
      puts_log "return_insert query = #{query}"
      rows = execute_without_logging(query).rows
      puts_log "return_insert rows = #{rows}"
      return rows.first
    end
  end

  puts_log "return_insert id_value = #{id_value}, val = #{val}"
  if !returning.nil?
    [id_value || val]
  else
    id_value || val
  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



1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1990

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, allow_retry: false) ⇒ Object



1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1270

def select(sql, name = nil, binds = [], prepare: false, async: false, allow_retry: false)
  puts_log "select sql = #{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 = []
  cols = []

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

  if stmt
    cols = IBM_DB.resultCols(stmt)
    results = fetch_data(stmt)
  end

  puts_log "select cols = #{cols}, results = #{results}"

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

  puts_log "select final results = #{results} #{caller}"
  results
end

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



1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1773

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)
  cols = nil
  results = nil

  if stmt and sql.strip.upcase.start_with?("SELECT")
    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}"
  end
  if @isAr3
    results
  elsif results.nil?
    ActiveRecord::Result.empty
  else
    ActiveRecord::Result.new(cols, results)
  end
end

#simplified_type(field_type) ⇒ Object

Mapping IBM data servers SQL datatypes to Ruby data types



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

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



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

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)


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

def supports_comments?
  true
end

#supports_common_table_expressions?Boolean

Returns:

  • (Boolean)


1000
1001
1002
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1000

def supports_common_table_expressions?
  true
end

#supports_datetime_with_precision?Boolean

Returns:

  • (Boolean)


1033
1034
1035
1036
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1033

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)


1041
1042
1043
1044
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1041

def supports_ddl_transactions?
  puts_log 'supports_ddl_transactions?'
  true
end

#supports_disable_referential_integrity?Boolean

:nodoc:

Returns:

  • (Boolean)


2902
2903
2904
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2902

def supports_disable_referential_integrity? # :nodoc:
  true
end

#supports_explain?Boolean

Returns:

  • (Boolean)


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

def supports_explain?
  puts_log 'supports_explain?'
  true
end

#supports_foreign_keys?Boolean

Returns:

  • (Boolean)


1074
1075
1076
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1074

def supports_foreign_keys?
  true
end

#supports_insert_on_duplicate_skip?Boolean

IBM Db2 does not natively support skipping rows on insert when there’s a duplicate key

Returns:

  • (Boolean)


1010
1011
1012
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1010

def supports_insert_on_duplicate_skip?
  false
end

#supports_insert_on_duplicate_update?Boolean

Returns:

  • (Boolean)


1014
1015
1016
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1014

def supports_insert_on_duplicate_update?
  false
end

#supports_lazy_transactions?Boolean

Returns:

  • (Boolean)


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

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)


1023
1024
1025
1026
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1023

def supports_migrations?
  puts_log 'supports_migrations?'
  true
end

#supports_partitioned_indexes?Boolean

Returns:

  • (Boolean)


1070
1071
1072
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1070

def supports_partitioned_indexes?
  true
end

#supports_unique_constraints?Boolean

Does this adapter support creating unique constraints?

Returns:

  • (Boolean)


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

def supports_unique_constraints?
  true
end

#supports_views?Boolean

Returns:

  • (Boolean)


1060
1061
1062
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1060

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



2304
2305
2306
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2304

def table_alias_length
  128
end

#table_comment(table_name) ⇒ Object

:nodoc:



2978
2979
2980
2981
2982
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2978

def table_comment(table_name) # :nodoc:
  puts_log "table_comment table_name = #{table_name}"
  sql = "select remarks from syscat.tables where tabname = #{quote(table_name.upcase)}"
  single_value_from_rows(execute_without_logging(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)


3044
3045
3046
3047
3048
3049
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3044

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:



3082
3083
3084
3085
3086
3087
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3082

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.



2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2309

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)


3346
3347
3348
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3346

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



989
990
991
992
993
994
995
996
997
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 989

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



1331
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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1331

def translate_exception(exception, message:, sql:, binds:)
  puts_log "translate_exception - exception = #{exception}, message = #{message}"
  puts_log "translate_exception #{caller}"
  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)
  elsif message.strip.start_with?("FrozenError") or
        message.strip.start_with?("ActiveRecord::Encryption::Errors::Encoding:") or
        message.strip.start_with?("ActiveRecord::Encryption::Errors::Encryption") or
        message.strip.start_with?("ActiveRecord::ConnectionFailed")
    exception
  else
    super(message, message: exception, sql: sql, binds: binds)
  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.



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

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



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

def unique_constraint_for(table_name, **options)
  puts_log "unique_constraint_for table_name = #{table_name}, options = #{options}"
  name = unique_constraint_name(table_name, **options)
  puts_log "unique_constraint_for name = #{name}"
  uq = unique_constraints(table_name)
  puts_log "unique_constraint_for unique_constraints = #{uq}"
  uq.detect { |unique_constraint| unique_constraint.defined_for?(name: name) }
end

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



3456
3457
3458
3459
3460
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3456

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



3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3436

def unique_constraint_name(table_name, **options)
  puts_log "unique_constraint_name table_name = #{table_name}, options = #{options}"
  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:



3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3379

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.



3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3393

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



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

def unquoted_false
  puts_log 'unquoted_false'
  0
end

#unquoted_trueObject



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

def unquoted_true
  puts_log 'unquoted_true'
  1
end

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



1898
1899
1900
1901
1902
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
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1898

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



1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1848

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)


1028
1029
1030
1031
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1028

def use_foreign_keys?
  puts_log 'use_foreign_keys?'
  true
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


2193
2194
2195
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2193

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)


3061
3062
3063
3064
3065
3066
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 3061

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.



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

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)


1678
1679
1680
1681
1682
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1678

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