Class: ActiveRecord::ConnectionAdapters::IBM_DBAdapter

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

Overview

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

mandatory parameters

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

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

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

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

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

Parameterized Queries Support

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

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

Defined Under Namespace

Classes: SchemaDumper, StatementPool

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from QueryCache

included, #prepared_select_with_query_cache

Constructor Details

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

Returns a new instance of IBM_DBAdapter.



720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 720

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

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

  @handle_lobs_triggered = false

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

  if @connection
    server_info = IBM_DB.server_info( @connection )
    if( server_info )
      case server_info.DBMS_NAME
        when /DB2\//i             # DB2 for Linux, Unix and Windows (LUW)
          case server_info.DBMS_VER
            when /09.07/i          # DB2 Version 9.7 (Cobra)
              @servertype = IBM_DB2_LUW_COBRA.new(self, @isAr3)
            when /10./i #DB2 version 10.1 and above
              @servertype = IBM_DB2_LUW_COBRA.new(self, @isAr3)
            else                  # DB2 Version 9.5 or below
              @servertype = IBM_DB2_LUW.new(self, @isAr3)
          end
        when /DB2/i               # DB2 for zOS
          case server_info.DBMS_VER
            when /09/             # DB2 for zOS version 9 and version 10
              @servertype = IBM_DB2_ZOS.new(self, @isAr3)
            when /10/
              @servertype = IBM_DB2_ZOS.new(self, @isAr3)
      when /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
  if config.has_key?(:start_id)
    @start_id = config[:start_id]
  else
    @start_id = 1
  end

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

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

Instance Attribute Details

#accountObject

Returns the value of attribute account.



701
702
703
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 701

def 
  @account
end

#app_userObject

Returns the value of attribute app_user.



701
702
703
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 701

def app_user
  @app_user
end

#applicationObject

Returns the value of attribute application.



701
702
703
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 701

def application
  @application
end

#connectionObject (readonly)

Returns the value of attribute connection.



699
700
701
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 699

def connection
  @connection
end

#handle_lobs_triggeredObject

Returns the value of attribute handle_lobs_triggered.



700
701
702
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 700

def handle_lobs_triggered
  @handle_lobs_triggered
end

#pstmt_support_onObject (readonly)

Returns the value of attribute pstmt_support_on.



702
703
704
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 702

def pstmt_support_on
  @pstmt_support_on
end

#schemaObject

Returns the value of attribute schema.



701
702
703
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 701

def schema
  @schema
end

#servertypeObject (readonly)

Returns the value of attribute servertype.



699
700
701
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 699

def servertype
  @servertype
end

#set_quoted_literal_replacementObject (readonly)

Returns the value of attribute set_quoted_literal_replacement.



702
703
704
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 702

def set_quoted_literal_replacement
  @set_quoted_literal_replacement
end

#sqlObject

Returns the value of attribute sql.



700
701
702
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 700

def sql
  @sql
end

#sql_parameter_valuesObject

Returns the value of attribute sql_parameter_values.



700
701
702
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 700

def sql_parameter_values
  @sql_parameter_values
end

#workstationObject

Returns the value of attribute workstation.



701
702
703
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 701

def workstation
  @workstation
end

Class Method Details

.visitor_for(pool) ⇒ Object



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

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)


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

def active?
  puts_log "active?"
  IBM_DB.active @connection
  rescue
    false
end

#adapter_nameObject

Name of the adapter



705
706
707
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 705

def adapter_name
  'IBM_DB'
end

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

:nodoc:



2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2620

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



2834
2835
2836
2837
2838
2839
2840
2841
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2834

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:



2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2646

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

#alter_foreign_keys(tables, not_enforced) ⇒ Object



2580
2581
2582
2583
2584
2585
2586
2587
2588
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2580

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|
         execute("ALTER TABLE #{@servertype.set_case(fk.from_table)} ALTER FOREIGN KEY #{@servertype.set_case(fk.name)} #{enforced}")
       end
     end
end

#begin_db_transactionObject

Begins the transaction (and turns off auto-committing)



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

def begin_db_transaction
  puts_log "begin_db_transaction"
  log("begin transaction", "TRANSACTION") {
  # Turns off the auto-commit
  IBM_DB.autocommit(@connection, IBM_DB::SQL_AUTOCOMMIT_OFF) }
end

#bind_params_lengthObject



848
849
850
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 848

def bind_params_length
  999
end

#build_conn_str_for_dbopsObject



1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1814

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

#build_fixture_sql(fixtures, table_name) ⇒ Object



1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1216

def build_fixture_sql(fixtures, table_name)
  puts_log "build_fixture_sql"
  columns = schema_cache.columns_hash(table_name)

  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
  manager.into(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



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

def build_fixture_statements(fixture_set)
  fixture_set.flat_map do |table_name, fixtures|
    next if fixtures.empty?
    fixtures.map { |fixture| build_fixture_sql([fixture], table_name) }
  end.compact
end

#build_statement_poolObject



716
717
718
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 716

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

#build_truncate_statement(table_name) ⇒ Object



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

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)


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

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



2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2597

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.



2905
2906
2907
2908
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2905

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



2911
2912
2913
2914
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2911

def change_column_null(table_name, column_name, null, default = nil)
  puts_log "change_column_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



2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2609

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

#check_if_write_query(sql) ⇒ Object

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



1548
1549
1550
1551
1552
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1548

def check_if_write_query(sql) #For rails 7.1 just remove this function as it will be defined in AbstractAdapter class
  if preventing_writes? && write_query?(sql)
    raise ActiveRecord::ReadOnlyError, "Write query attempted while in readonly mode: #{sql}"
  end
end

#column_for(table_name, column_name) ⇒ Object



2922
2923
2924
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2922

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



2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
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
2421
2422
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
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2356

def columns(table_name)        
  default_blob_length = 1048576
# to_s required because it may be a symbol.
  puts_log "columns"
  puts_log caller
  table_name = @servertype.set_case(table_name.to_s)
				
  # Checks if a blank table name has been given.
  # If so it returns an empty array
  return [] if table_name.strip.empty?
  # +columns+ will contain the resulting array
  columns = []
  # Statement required to access all the columns information
  stmt = IBM_DB.columns( @connection, nil, 
                             @servertype.set_case(@schema), 
                             @servertype.set_case(table_name) )
#       sql = "select * from sysibm.sqlcolumns where table_name = #{quote(table_name.upcase)}"
  if @debug == true
    sql = "select * from syscat.columns  where tabname = #{quote(table_name.upcase)}"
    puts_log "SYSIBM.SQLCOLUMNS = #{select_prepared(sql).rows}"
  end

  if(stmt)
    begin
      # Fetches all the columns and assigns them to col.
      # +col+ is an hash with keys/value pairs for a column
      while col = IBM_DB.fetch_assoc(stmt)
        puts_log col
        column_name = col["column_name"].downcase
        # Assigns the column default value.
        column_default_value = col["column_def"]
        default_value = extract_value_from_default(column_default_value)
        # Assigns the column type
        column_type = col["type_name"].downcase

        # Assigns the field length (size) for the column
			  
        if column_type =~ /integer|bigint/i
          column_length = col["buffer_length"]
        else
          column_length = 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) ? true : false
        # Make sure the hidden column (db2_generated_rowid_for_lobs) in DB2 z/OS isn't added to the list
        if !(column_name.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
              if !default_value.nil?
                default_value[10] = " "
                default_value[13] = ":"
                default_value[16] = ":"
              end
            elsif column_type.match(/time/i)
              if !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

          if ruby_type.to_s == "boolean"
            column_type = "boolean"
          end

          default_function = extract_default_function(default_value, column_default_value)

				 = SqlTypeMetadata.new(					
					#sql_type: sql_type,
					sql_type: column_type,
					type: ruby_type,
					limit: column_length,
					precision: precision,
					scale: column_scale,
				)
				
				columns << Column.new(column_name, default_value, , column_nullable, default_function, comment: col["remarks"])
        end
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve column metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of column metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
#             raise error_msg
      end
    ensure  # Free resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  else  # Handle driver execution errors
    error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve column metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during retrieval of columns metadata')
    end
  end
  # Returns the columns array
  puts_log "Inside def columns() #{columns}"
  return columns
end

#commit_db_transactionObject

Commits the transaction and turns on auto-committing



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

def commit_db_transaction
  puts_log "commit_db_transaction"
  log("commit transaction", "TRANSACTION") {
  # Commits the transaction
  IBM_DB.commit @connection rescue nil }
  # Turns on auto-committing
  IBM_DB.autocommit @connection, IBM_DB::SQL_AUTOCOMMIT_ON
end

#create_column_indexes(index_list, column_name, new_column_name) ⇒ Object



2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2795

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 if !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



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

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 => connect_err
    raise "Failed to connect to server due to: #{connect_err}"
  end

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

#create_schema_dumper(options) ⇒ Object



2720
2721
2722
2723
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2720

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



1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1069

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

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

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

#create_table_indexes(index_list, new_table) ⇒ Object



2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2769

def create_table_indexes(index_list, new_table)
  puts_log "create_table_indexes"
  index_list.each do |indexs|
    generated_index_name = index_name(indexs.table, column: indexs.columns)
    custom_index_name = indexs.name
    
    if generated_index_name == custom_index_name
      add_index(new_table, indexs.columns, unique: indexs.unique)
    else
      add_index(new_table, indexs.columns, name: custom_index_name, unique: indexs.unique)
    end
  end
end

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



2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2664

def data_source_sql(name = nil, type: nil)
     puts_log "data_source_sql"
		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
		sql
end

#data_sourcesObject

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



2713
2714
2715
2716
2717
2718
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2713

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:



1692
1693
1694
1695
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1692

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

#disable_referential_integrityObject

:nodoc:



2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2567

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

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

#disconnect!Object

Closes the current connection



1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1053

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
  puts_log "disconnect!"
  return nil if @connection.nil? || @connection == false
  IBM_DB.close(@connection) rescue nil
  @connection = nil
  reset_transaction
end

#distinct(columns, order_by) ⇒ Object

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



2889
2890
2891
2892
2893
2894
2895
2896
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2889

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



2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2783

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

#drop_database(dbName) ⇒ Object



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

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 => connect_err
    raise "Failed to connect to server due to: #{connect_err}"
  end

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

#drop_table_indexes(index_list) ⇒ Object



2762
2763
2764
2765
2766
2767
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2762

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

#empty_insert_statement_value(pkey) ⇒ Object



1325
1326
1327
1328
1329
1330
1331
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1325

def empty_insert_statement_value(pkey)
  if !pkey.nil?
    "(#{pkey}) VALUES (DEFAULT)"
  else
    raise ArgumentError, "Empty Insert Statement not allowed in DB2"
  end
end

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

:nodoc:



1394
1395
1396
1397
1398
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1394

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

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



1383
1384
1385
1386
1387
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1383

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

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



1518
1519
1520
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1518

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

#exec_query_ret_stmt(sql, name = 'SQL', binds = [], prepare = 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.



1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1484

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

    stmt = @servertype.prepare(sql, name)
    if prepare 
      @statements[sql] = stmt
    end
    
    puts_log "Statement = #{stmt}"
    log(sql, name, binds, param_array) do
      if( stmt )
        if(execute_prepared_stmt(stmt, param_array))
          return stmt
        end
      else
        return false
      end
    end
  ensure
    @offset = @limit = nil
  end
end

#execute(sql, name = nil) ⇒ Object

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



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

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

#execute_prepared_stmt(pstmt, param_array = nil) ⇒ Object

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



1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1442

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

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

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



1470
1471
1472
1473
1474
1475
1476
1477
1478
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1470

def explain(arel, binds = [])
  sql = "EXPLAIN ALL SET QUERYNO = 1 FOR #{to_sql(arel, binds)}"
  stmt = execute(sql, "EXPLAIN")
  result = select("select * from explain_statement where explain_level = 'P' and queryno = 1", "EXPLAIN")
  return 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



2493
2494
2495
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2493

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

#extract_foreign_key_action(specifier) ⇒ Object

:nodoc:



2554
2555
2556
2557
2558
2559
2560
2561
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2554

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

#extract_precision(sql_type) ⇒ Object



2489
2490
2491
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2489

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

#extract_value_from_default(default) ⇒ Object

method simplified_type



2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2333

def extract_value_from_default(default)
  case default
  when /IDENTITY GENERATED BY DEFAULT/i
    nil
  when /^null$/i
    nil
  # Quoted types
  when /^'(.*)'$/m
    $1.gsub("''", "'")
  # Quoted types
  when /^"(.*)"$/m
    $1.gsub('""', '"')
  # Numeric types
  when /\A-?\d+(\.\d*)?\z/
    $&
  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



1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1100

def fetch_data(stmt)
  puts_log "fetch_data"
  if(stmt)
    begin
      return @servertype.select(stmt)
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise StatementInvalid,"Failed to retrieve data: #{error_msg}"
      else
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    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
end

#foreign_keys(table_name) ⇒ Object



2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2501

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 = []
  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])
			  foreignKeys << ForeignKeyDefinition.new(fk_row[6].downcase, fk_row[2].downcase, options) 
      end			

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

#get_database_versionObject



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

def get_database_version
  @database_version
end

#has_default_function?(default_value, default) ⇒ Boolean

Returns:

  • (Boolean)


2497
2498
2499
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2497

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

#indexes(table_name, name = nil) ⇒ Object

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



2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2123

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}"
        if pk_index_row[5] 
          pk_index_name = pk_index_row[5].downcase
          pk_index_columns = [pk_index_row[3].downcase]           # COLUMN_NAME
          if pk_index 
            pk_index.columns << pk_index_columns
          else
            pk_index = IndexDefinition.new(table_name, pk_index_name, true, pk_index_columns)
          end
        end 
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve primarykey metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of primary key metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure  # Free resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  else  # Handle driver execution errors
    error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve primary key metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during primary key retrieval')
    end
  end

  # Query table statistics for all indexes on the table
  # "TABLE_NAME:   #{index_stats[2]}"
  # "NON_UNIQUE:   #{index_stats[3]}"
  # "INDEX_NAME:   #{index_stats[5]}"
  # "COLUMN_NAME:  #{index_stats[8]}"
  stmt = IBM_DB.statistics( @connection, nil, 
                            @servertype.set_case(@schema), 
                            @servertype.set_case(table_name), 1 )
  if(stmt)
    begin
      while ( index_stats = IBM_DB.fetch_array(stmt) )
        is_composite = false
        if index_stats[5]             # INDEX_NAME
          index_name = index_stats[5].downcase
          index_unique = (index_stats[3] == 0)
          index_columns = [index_stats[8].downcase]     # COLUMN_NAME
          index_qualifier = index_stats[4].downcase             #Index_Qualifier
          # Create an IndexDefinition object and add to the indexes array
          i = 0;
          indexes.each do |index|
            if index.name == index_name && index_schema[i] == index_qualifier
               #index.columns = index.columns + index_columns
               index.columns.concat index_columns
               is_composite = true
            end 
            i = i+1
          end
        
          unless is_composite 
            sql = "select remarks from syscat.indexes where tabname = #{quote(table_name.upcase)} and indname = #{quote(index_stats[5])}"
            comment = single_value_from_rows(select_prepared(sql).rows)

            indexes << IndexDefinition.new(table_name, index_name, index_unique, index_columns, comment: comment)
            index_schema << index_qualifier
          end 
        end
      end
    rescue StandardError => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve index metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of index metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure  # Free resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  else  # Handle driver execution errors
    error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve index metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during index retrieval')
    end
  end
    
  # remove the primary key index entry.... should not be dumped by the dumper
    
  puts_log "Indexes 1 = #{pk_index}"
  i = 0
  indexes.each do |index|
    if pk_index && index.columns == pk_index.columns
      indexes.delete_at(i)
    end
    i = i+1
  end 
  # Returns the indexes array
  puts_log "Indexes 2 = #{indexes}"
  return indexes
end

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



1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1356

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

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

  ActiveRecord::Base.clear_query_caches_for_current_thread
    
		if stmt = exec_insert_db2(sql, name, binds)
    begin
      @sql << sql
      return id_value || @servertype.last_generated_id(stmt)
    ensure
      IBM_DB.free_stmt(stmt) if stmt
    end
  end
end

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

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



1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1336

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

  ActiveRecord::Base.clear_query_caches_for_current_thread

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

#insert_fixture(fixture, table_name) ⇒ Object

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



1264
1265
1266
1267
1268
1269
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
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1264

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

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

#last_inserted_id(result) ⇒ Object



1389
1390
1391
1392
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1389

def last_inserted_id(result)
  puts_log "last_inserted_id"
  return result
end

#log_query(sql, name) ⇒ Object

:nodoc:



974
975
976
977
978
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 974

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



1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1784

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

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

#prepare(sql, name = nil) ⇒ Object

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



1430
1431
1432
1433
1434
1435
1436
1437
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1430

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.



1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1404

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
      return id_value || @servertype.last_generated_id(pstmt)
    end
  rescue StandardError => insert_err
    raise insert_err
  ensure
    IBM_DB.free_stmt(pstmt) if pstmt
  end
end

#prepared_statements?Boolean Also known as: prepared_statements

Returns:

  • (Boolean)


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

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



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

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

#primary_key(table_name) ⇒ Object

Returns the primary key of the mentioned table



2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2081

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 => fetch_error # Handle driver fetch errors
      error_msg = IBM_DB.getErrormsg( stmt, IBM_DB::DB_STMT )
      if error_msg && !error_msg.empty?
        raise "Failed to retrieve primarykey metadata during fetch: #{error_msg}"
      else
        error_msg = "An unexpected error occurred during retrieval of primary key metadata"
        error_msg = error_msg + ": #{fetch_error.message}" if !fetch_error.message.empty?
        raise error_msg
      end
    ensure  # Free resources associated with the statement
      IBM_DB.free_stmt(stmt) if stmt
    end
  else
    error_msg = IBM_DB.getErrormsg( @connection, IBM_DB::DB_CONN )
    if error_msg && !error_msg.empty?
      raise "Failed to retrieve primary key metadata due to error: #{error_msg}"
    else
      raise StandardError.new('An unexpected error occurred during primary key retrieval')
    end
  end
  if pk_name.length() == 1
    return pk_name[0]
  elsif pk_name.empty?
    return nil
  else
    return pk_name
  end
end

#primary_keys(table_name) ⇒ Object

:nodoc:

Raises:

  • (ArgumentError)


2590
2591
2592
2593
2594
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2590

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



984
985
986
987
988
989
990
991
992
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 984

def puts_log (val)
  begin
#         puts val
  rescue
  end
  if @debug == true
    log(" IBM_DB = #{val}", "TRANSACTION"){}
  end
end

#query_values(sql, name = nil) ⇒ Object

:nodoc:



2659
2660
2661
2662
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2659

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

#quote_column_name(name) ⇒ Object



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

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

#quote_string(string) ⇒ Object

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



1731
1732
1733
1734
1735
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1731

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

#quote_table_name(name) ⇒ Object



1760
1761
1762
1763
1764
1765
1766
1767
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1760

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

#quote_value_for_pstmt(value, column = nil) ⇒ Object

QUOTING



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

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

#quoted_binary(value) ⇒ Object



1774
1775
1776
1777
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1774

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

#quoted_falseObject



1745
1746
1747
1748
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1745

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.



1740
1741
1742
1743
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1740

def quoted_true
  puts_log "quoted_true"
  "1".freeze
end

#reconnect!Object

Closes the current connection and opens a new one



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

def reconnect!
  puts_log "reconnect!"
  disconnect!
  connect
end

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

Removes the column from the table definition.

Examples
remove_column(:suppliers, :qualification)


2871
2872
2873
2874
2875
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2871

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



2732
2733
2734
2735
2736
2737
2738
2739
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2732

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

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

#remove_foreign_key_byColumn(fkey_list, table_name, column_name) ⇒ Object



2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2843

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



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

def remove_index(table_name, column_name = nil, **options)
  puts_log "remove_index"
  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

#rename_column(table_name, column_name, new_column_name) ⇒ Object

Renames a column in a table.



2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2817

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!
  index_list = indexes(table_name)
  puts_log "Index List = #{index_list}"
  fkey_list = foreign_keys(table_name)
  puts_log "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_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



2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2855

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) ⇒ Object

Renames a table.

Example

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



2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2745

def rename_table(name, new_name)
	    puts_log "rename_table"
  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

#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



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

def rollback_db_transaction
  puts_log "rollback_db_transaction"
  log("rollback transaction", "TRANSACTION") {
  # ROLLBACK the transaction
  IBM_DB.rollback(@connection) rescue nil }
  ActiveRecord::Base.clear_query_caches_for_current_thread
  # Turns on auto-committing
  IBM_DB.autocommit @connection, IBM_DB::SQL_AUTOCOMMIT_ON
end

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



1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1123

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

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

  cols = IBM_DB.resultCols(stmt)

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

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

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



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

def select_prepared(sql, name = nil, binds = [], prepare = true)
  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)
  if !/^select .*/i.match(sql).nil?
    cols = IBM_DB.resultCols(stmt)

    if( stmt )
      results = fetch_data(stmt)
    end

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

#simplified_type(field_type) ⇒ Object

Mapping IBM data servers SQL datatypes to Ruby data types



2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2294

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



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

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)


966
967
968
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 966

def supports_comments?
  true
end

#supports_datetime_with_precision?Boolean

Returns:

  • (Boolean)


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

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)


951
952
953
954
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 951

def supports_ddl_transactions?
  puts_log "supports_ddl_transactions?"
  true
end

#supports_disable_referential_integrity?Boolean

:nodoc:

Returns:

  • (Boolean)


2563
2564
2565
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2563

def supports_disable_referential_integrity? #:nodoc:
  true
end

#supports_explain?Boolean

Returns:

  • (Boolean)


956
957
958
959
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 956

def supports_explain?
  puts_log "supports_explain?"
  true
end

#supports_foreign_keys?Boolean

Returns:

  • (Boolean)


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

def supports_foreign_keys?
  puts_log "supports_foreign_keys?"
  true
end

#supports_lazy_transactions?Boolean

Returns:

  • (Boolean)


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

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)


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

def supports_migrations?
  puts_log "supports_migrations?"
  true
end

#supports_partitioned_indexes?Boolean

Returns:

  • (Boolean)


980
981
982
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 980

def supports_partitioned_indexes?
  true
end

#supports_views?Boolean

Returns:

  • (Boolean)


970
971
972
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 970

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



1995
1996
1997
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1995

def table_alias_length
  128
end

#table_comment(table_name) ⇒ Object

:nodoc:



2640
2641
2642
2643
2644
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2640

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

#table_exists?(table_name) ⇒ Boolean

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

table_exists?(:developers)

Returns:

  • (Boolean)


2687
2688
2689
2690
2691
2692
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2687

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:



2725
2726
2727
2728
2729
2730
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2725

def table_options(table_name) # :nodoc:
  puts_log "table_options"
  if comment = table_comment(table_name)
    { comment: comment }
  end
end

#tablesObject

Returns an array of table names defined in the database.



2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2000

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

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



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

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



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

def translate_exception(exception, message:, sql:, binds:)
  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?
    RecordNotUnique.new(message, sql: sql, binds: binds)
		elsif !error_msg2.match(message).nil?
    ArgumentError.new(message)
		elsif !error_msg3.match(message).nil?
    RangeError.new(message, sql: sql, binds: binds)
  elsif !error_msg4.match(message).nil?
    NotNullViolation.new(message, sql: sql, binds: binds)
  elsif !error_msg5.match(message).nil? or !error_msg6.match(message).nil?
    InvalidForeignKey.new(message, sql: sql, binds: binds)
		elsif !error_msg7.match(message).nil? or !error_msg8.match(message).nil?
    ValueTooLong.new(message, sql: sql, binds: binds)
  elsif exception.message.match?(/called on a closed database/i)
    ConnectionNotEstablished.new(exception)
  else
    super
  end
end

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

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



1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1880

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

  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) === 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
    if limit.class == Hash
      if limit.has_key?("precision".to_sym)
        precision = limit[:precision]
      end
    end
    if limit.class == Hash
      if limit.has_key?("scale".to_sym)
        scale = limit[:scale]
      end
    end
    sql_segment = native_database_types[type.to_sym][:name].to_s
    if !precision.nil? && !scale.nil?
      sql_segment << "(#{precision},#{scale})"
      return sql_segment
    elsif scale.nil? && !precision.nil?
      sql_segment << "(#{precision})"
      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})" if !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
      if limit.has_key?("limit".to_sym)
        limit1 = limit[:limit]
        sql_segment << "(#{limit1})"
      else
        return "vargraphic(1)"
      end
 else
   if limit != nil
        sql_segment << "(#{limit})"
      else
        return "vargraphic(1)"
      end
    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
      if limit.has_key?("limit".to_sym)
        limit1 = limit[:limit]
        sql_segment << "(#{limit1})"
      else
        return "graphic(1)"
      end
 else
      if limit != nil
        sql_segment << "(#{limit})"
      else
        return "graphic(1)"
      end
    end
    return sql_segment
  end

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

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

#unquoted_falseObject



1755
1756
1757
1758
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1755

def unquoted_false
  puts_log "unquoted_false"
  0
end

#unquoted_trueObject



1750
1751
1752
1753
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1750

def unquoted_true
  puts_log "unquoted_true"
  1
end

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



1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1622

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



1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1572

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.
  if stmt = execute(sql, name)
    begin
      @sql << sql
      # Retrieves the number of affected rows
      IBM_DB.num_rows(stmt)
      # Ensures to free the resources associated with the statement
    ensure
      IBM_DB.free_stmt(stmt) if stmt
    end
  end
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


1874
1875
1876
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1874

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)


2704
2705
2706
2707
2708
2709
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2704

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.



2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 2041

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

#write_query?(sql) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


1464
1465
1466
1467
1468
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1464

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