Class: ActiveRecord::ConnectionAdapters::IBM_DBAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- ActiveRecord::ConnectionAdapters::IBM_DBAdapter
- 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.
Instance Attribute Summary collapse
-
#account ⇒ Object
Returns the value of attribute account.
-
#app_user ⇒ Object
Returns the value of attribute app_user.
-
#application ⇒ Object
Returns the value of attribute application.
-
#connection ⇒ Object
readonly
Returns the value of attribute connection.
-
#handle_lobs_triggered ⇒ Object
Returns the value of attribute handle_lobs_triggered.
-
#pstmt_support_on ⇒ Object
readonly
Returns the value of attribute pstmt_support_on.
-
#schema ⇒ Object
Returns the value of attribute schema.
-
#servertype ⇒ Object
readonly
Returns the value of attribute servertype.
-
#set_quoted_literal_replacement ⇒ Object
readonly
Returns the value of attribute set_quoted_literal_replacement.
-
#sql ⇒ Object
Returns the value of attribute sql.
-
#sql_parameter_values ⇒ Object
Returns the value of attribute sql_parameter_values.
-
#workstation ⇒ Object
Returns the value of attribute workstation.
Instance Method Summary collapse
-
#active? ⇒ Boolean
Tests the connection status.
-
#adapter_name ⇒ Object
Name of the adapter.
-
#add_limit_offset!(sql, options) ⇒ Object
Modifies a sql statement in order to implement a LIMIT and an OFFSET.
-
#begin_db_transaction ⇒ Object
Begins the transaction (and turns off auto-committing).
-
#change_column(table_name, column_name, type, options = {}) ⇒ Object
Changes the column’s definition according to the new options.
-
#change_column_default(table_name, column_name, default) ⇒ Object
Sets a new default value for a column.
-
#change_column_null(table_name, column_name, null, default = nil) ⇒ Object
Changes the nullability value of a column.
-
#columns(table_name, name = nil) ⇒ Object
Returns an array of Column objects for the table specified by
table_name
. -
#commit_db_transaction ⇒ Object
Commits the transaction and turns on auto-committing.
-
#create_table(name, options = {}) ⇒ Object
DATABASE STATEMENTS ==============================================.
-
#default_sequence_name(table, column) ⇒ Object
method add_limit_offset!.
-
#disconnect! ⇒ Object
Closes the current connection.
-
#execute(sql, name = nil) ⇒ Object
Executes and logs
sql
commands and returns aIBM_DB.Statement
object. -
#execute_prepared_stmt(pstmt, param_array = nil) ⇒ Object
Praveen Executes the prepared statement ReturnsTrue on success and False on Failure.
-
#indexes(table_name, name = nil) ⇒ Object
Returns an array of non-primary key indexes for a specified table name.
-
#initialize(connection, logger, config, conn_options) ⇒ IBM_DBAdapter
constructor
A new instance of IBM_DBAdapter.
-
#insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) ⇒ Object
Perform an insert and returns the last ID generated.
-
#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.
-
#log_query(sql, name) ⇒ Object
:nodoc:.
-
#native_database_types ⇒ Object
Returns a Hash of mappings from the abstract data types to the native database types.
-
#prepare(sql, name = nil) ⇒ Object
Praveen Prepares and logs
sql
commands and returns aIBM_DB.Statement
object. -
#prepared_insert(pstmt, param_array = nil) ⇒ Object
Praveen Performs an insert using the prepared statement and returns the last ID generated.
-
#prepared_select(sql_param_hash, name = nil) ⇒ Object
Returns an array of hashes with the column names as keys and column values as values.
-
#prepared_select_values(sql_param_hash, name = nil) ⇒ Object
Returns an array of hashes with the column names as keys and column values as values.
-
#prepared_update(pstmt, param_array = nil) ⇒ Object
(also: #prepared_delete)
Praveen.
-
#primary_key(table_name) ⇒ Object
Returns the primary key of the mentioned table.
-
#quote(value, column = nil) ⇒ Object
Properly quotes the various data types.
- #quote_column_name(name) ⇒ Object
-
#quote_string(string) ⇒ Object
Quotes a given string, escaping single quote (‘) characters.
-
#quote_value_for_pstmt(value, column = nil) ⇒ Object
Praveen.
- #quoted_false ⇒ Object
-
#quoted_true ⇒ Object
true is represented by a smallint 1, false by 0, as no native boolean type exists in DB2.
-
#reconnect! ⇒ Object
Closes the current connection and opens a new one.
-
#remove_column(table_name, column_name) ⇒ Object
Removes the column from the table definition.
-
#remove_index(table_name, options = {}) ⇒ Object
Remove the given index from the table.
-
#rename_column(table_name, column_name, new_column_name) ⇒ Object
Renames a column.
-
#rename_table(name, new_name) ⇒ Object
Renames a table.
-
#rollback_db_transaction ⇒ Object
Rolls back the transaction and turns on auto-committing.
-
#select(sql, name = nil) ⇒ Object
Returns an array of hashes with the column names as keys and column values as values.
-
#select_one(sql, name = nil) ⇒ Object
Returns a record hash with the column names as keys and column values as values.
-
#select_rows(sql, name = nil) ⇒ Object
Returns an array of arrays containing the field values.
-
#supports_ddl_transactions? ⇒ Boolean
This Adapter supports DDL transactions.
-
#supports_migrations? ⇒ Boolean
This adapter supports migrations.
-
#table_alias_length ⇒ Object
Returns the maximum length a table alias identifier can be.
-
#tables(name = nil) ⇒ Object
Retrieves table’s metadata for a specified shema name.
-
#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 data types.
-
#update(sql, name = nil) ⇒ Object
(also: #delete)
Executes an “UPDATE” SQL statement.
Methods included from QueryCache
included, #prepared_select_with_query_cache
Constructor Details
#initialize(connection, logger, config, conn_options) ⇒ IBM_DBAdapter
Returns a new instance of IBM_DBAdapter.
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 435 def initialize(connection, logger, config, ) # Caching database connection configuration (+connect+ or +reconnect+ support) @connection = connection @conn_options = @database = config[:database] @username = config[:username] @password = config[:password] if config.has_key?(:host) @host = config[:host] @port = config[:port] || 50000 # default port end @schema = config[:schema] @security = config[:security] || nil @authentication = config[:authentication] || nil @timeout = config[:timeout] || 0 # default timeout value is 0 if( config.has_key?(:parameterized) && config[:parameterized] == true ) @pstmt_support_on = true @set_quoted_literal_replacement = IBM_DB::QUOTED_LITERAL_REPLACEMENT_OFF else @pstmt_support_on = false @set_quoted_literal_replacement = IBM_DB::QUOTED_LITERAL_REPLACEMENT_ON end # Caching database connection options (auditing and billing support) @app_user = [:app_user] if .has_key?(:app_user) @account = [:account] if .has_key?(:account) @application = [:application] if .has_key?(:application) @workstation = [:workstation] if .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) 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) else # DB2 Version 9.5 or below @servertype = IBM_DB2_LUW.new(self) end when /DB2/i # DB2 for zOS case server_info.DBMS_VER when /09/ # DB2 for zOS version 9 @servertype = IBM_DB2_ZOS.new(self) when /08/ # DB2 for zOS version 8 @servertype = IBM_DB2_ZOS_8.new(self) 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) when /IDS/i # Informix Dynamic Server @servertype = IBM_IDS.new(self) 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) end else error_msg = IBM_DB.getErrormsg( @connection, IBM_DB::DB_CONN ) IBM_DB.close( @connection ) raise "Cannot retrieve server information: #{error_msg}" end end # Executes the +set schema+ statement using the schema identifier provided @servertype.set_schema(@schema) if @schema && @schema != @username # Check for the start value for id (primary key column). By default it is 1 if config.has_key?(:start_id) @start_id = config[:start_id] else @start_id = 1 end end |
Instance Attribute Details
#account ⇒ Object
Returns the value of attribute account.
427 428 429 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 427 def account @account end |
#app_user ⇒ Object
Returns the value of attribute app_user.
427 428 429 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 427 def app_user @app_user end |
#application ⇒ Object
Returns the value of attribute application.
427 428 429 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 427 def application @application end |
#connection ⇒ Object (readonly)
Returns the value of attribute connection.
425 426 427 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 425 def connection @connection end |
#handle_lobs_triggered ⇒ Object
Returns the value of attribute handle_lobs_triggered.
426 427 428 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 426 def handle_lobs_triggered @handle_lobs_triggered end |
#pstmt_support_on ⇒ Object (readonly)
Returns the value of attribute pstmt_support_on.
428 429 430 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 428 def pstmt_support_on @pstmt_support_on end |
#schema ⇒ Object
Returns the value of attribute schema.
427 428 429 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 427 def schema @schema end |
#servertype ⇒ Object (readonly)
Returns the value of attribute servertype.
425 426 427 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 425 def servertype @servertype end |
#set_quoted_literal_replacement ⇒ Object (readonly)
Returns the value of attribute set_quoted_literal_replacement.
428 429 430 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 428 def set_quoted_literal_replacement @set_quoted_literal_replacement end |
#sql ⇒ Object
Returns the value of attribute sql.
426 427 428 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 426 def sql @sql end |
#sql_parameter_values ⇒ Object
Returns the value of attribute sql_parameter_values.
426 427 428 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 426 def sql_parameter_values @sql_parameter_values end |
#workstation ⇒ Object
Returns the value of attribute workstation.
427 428 429 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 427 def workstation @workstation end |
Instance Method Details
#active? ⇒ Boolean
Tests the connection status
595 596 597 598 599 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 595 def active? IBM_DB.active @connection rescue false end |
#adapter_name ⇒ Object
Name of the adapter
431 432 433 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 431 def adapter_name 'IBM_DB' end |
#add_limit_offset!(sql, options) ⇒ Object
Modifies a sql statement in order to implement a LIMIT and an OFFSET. A LIMIT defines the number of rows that should be fetched, while an OFFSET defines from what row the records must be fetched. IBM data servers implement a LIMIT in SQL statements through: FETCH FIRST n ROWS ONLY, where n is the number of rows required. The implementation of OFFSET is more elaborate, and requires the usage of subqueries and the ROW_NUMBER() command in order to add row numbering as an additional column to a copy of the existing table.
Examples
add_limit_offset!(‘SELECT * FROM staff’, => 10) generates: “SELECT * FROM staff FETCH FIRST 10 ROWS ONLY”
add_limit_offset!(‘SELECT * FROM staff’, => 10, :offset => 30) generates “SELECT O.* FROM (SELECT I.*, ROW_NUMBER() OVER () sys_rownum FROM (SELECT * FROM staff) AS I) AS O WHERE sys_row_num BETWEEN 31 AND 40”
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 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1070 def add_limit_offset!(sql, ) # If there is a limit if limit = [:limit] # if the limit is zero if limit == 0 # Returns a query that will always generate zero records # (e.g. WHERE sys_row_num BETWEEN 1 and 0) if( @pstmt_support_on ) sql = @servertype.query_offset_limit!(sql, 0, limit, ) else sql = @servertype.query_offset_limit(sql, 0, limit) end # If there is a non-zero limit else offset = [:offset] # If an offset is specified builds the query with offset and limit, # otherwise retrieves only the first +limit+ rows if( @pstmt_support_on ) sql = @servertype.query_offset_limit!(sql, offset, limit, ) else sql = @servertype.query_offset_limit(sql, offset, limit) end end end # Returns the sql query in any case sql end |
#begin_db_transaction ⇒ Object
Begins the transaction (and turns off auto-committing)
1032 1033 1034 1035 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1032 def begin_db_transaction # Turns off the auto-commit IBM_DB.autocommit(@connection, IBM_DB::SQL_AUTOCOMMIT_OFF) 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)
1582 1583 1584 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1582 def change_column(table_name, column_name, type, = {}) @servertype.change_column(table_name, column_name, type, ) 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.
1619 1620 1621 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1619 def change_column_default(table_name, column_name, default) @servertype.change_column_default(table_name, column_name, default) end |
#change_column_null(table_name, column_name, null, default = nil) ⇒ Object
Changes the nullability value of a column
1624 1625 1626 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1624 def change_column_null(table_name, column_name, null, default = nil) @servertype.change_column_null(table_name, column_name, null, default) end |
#columns(table_name, name = nil) ⇒ Object
Returns an array of Column objects for the table specified by table_name
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1472 def columns(table_name, name = nil) # to_s required because it may be a symbol. table_name = @servertype.set_case(table_name.to_s) # Checks if a blank table name has been given. # If so it returns an empty array return [] if table_name.strip.empty? # +columns+ will contain the resulting array columns = [] # Statement required to access all the columns information stmt = IBM_DB.columns( @connection, nil, @servertype.set_case(@schema), @servertype.set_case(table_name) ) if(stmt) begin # Fetches all the columns and assigns them to col. # +col+ is an hash with keys/value pairs for a column while col = IBM_DB.fetch_assoc(stmt) column_name = col["column_name"].downcase # Assigns the column default value. column_default_value = col["column_def"] # If there is no default value, it assigns NIL column_default_value = nil if (column_default_value && column_default_value.upcase == 'NULL') # Removes single quotes from the default value column_default_value.gsub!(/^'(.*)'$/, '\1') unless column_default_value.nil? # Assigns the column type column_type = col["type_name"].downcase # Assigns the field length (size) for the column column_length = col["column_size"] column_scale = col["decimal_digits"] # The initializer of the class Column, requires the +column_length+ to be declared # between brackets after the datatype(e.g VARCHAR(50)) for :string and :text types. # If it's a "for bit data" field it does a subsitution in place, if not # it appends the (column_length) string on the supported data types unless column_length.nil? || column_length == '' || column_type.sub!(/ \(\) for bit data/i,"(#{column_length}) FOR BIT DATA") || !column_type =~ /char|lob|graphic/i if column_type =~ /decimal/i column_type << "(#{column_length},#{column_scale})" elsif column_type =~ /smallint|integer|double|date|time|timestamp|xml/i column_type << "" # override native limits incompatible with table create else column_type << "(#{column_length})" end end # col["NULLABLE"] is 1 if the field is nullable, 0 if not. column_nullable = (col["nullable"] == 1) ? true : false # Make sure the hidden column (db2_generated_rowid_for_lobs) in DB2 z/OS isn't added to the list if !(column_name =~ /db2_generated_rowid_for_lobs/i) # Pushes into the array the *IBM_DBColumn* object, created by passing to the initializer # +column_name+, +default_value+, +column_type+ and +column_nullable+. columns << IBM_DBColumn.new(column_name, column_default_value, column_type, column_nullable) 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.}" if !fetch_error..empty? raise error_msg end ensure # Free resources associated with the statement IBM_DB.free_stmt(stmt) if stmt end else # Handle driver execution errors error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN ) if error_msg && !error_msg.empty? raise "Failed to retrieve column metadata due to error: #{error_msg}" else raise StandardError.new('An unexpected error occurred during retrieval of columns metadata') end end # Returns the columns array return columns end |
#commit_db_transaction ⇒ Object
Commits the transaction and turns on auto-committing
1038 1039 1040 1041 1042 1043 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1038 def commit_db_transaction # Commits the transaction IBM_DB.commit @connection rescue nil # Turns on auto-committing IBM_DB.autocommit @connection, IBM_DB::SQL_AUTOCOMMIT_ON end |
#create_table(name, options = {}) ⇒ Object
DATABASE STATEMENTS
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 654 def create_table(name, = {}) @servertype.setup_for_lob_table super #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 end |
#default_sequence_name(table, column) ⇒ Object
method add_limit_offset!
1098 1099 1100 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1098 def default_sequence_name(table, column) # :nodoc: "#{table}_#{column}_seq" end |
#disconnect! ⇒ Object
Closes the current connection
642 643 644 645 646 647 648 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 642 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 IBM_DB.close(@connection) rescue nil end |
#execute(sql, name = nil) ⇒ Object
Executes and logs sql
commands and returns a IBM_DB.Statement
object.
956 957 958 959 960 961 962 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 956 def execute(sql, name = nil) # Logs and execute the sql instructions. # The +log+ method is defined in the parent class +AbstractAdapter+ 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
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 935 def execute_prepared_stmt(pstmt, param_array = nil) if !param_array.nil? && param_array.size < 1 param_array = nil end if( !IBM_DB.execute(pstmt, param_array) ) error_msg = IBM_DB.getErrormsg(pstmt, IBM_DB::DB_STMT) if !error_msg.empty? error_msg = "Statement execution failed: " + error_msg else error_msg = "Statement execution failed" end IBM_DB.free_stmt(pstmt) if pstmt raise StatementInvalid, error_msg else return true end end |
#indexes(table_name, name = nil) ⇒ Object
Returns an array of non-primary key indexes for a specified table name
1351 1352 1353 1354 1355 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 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1351 def indexes(table_name, name = nil) # to_s required because +table_name+ may be a symbol. table_name = table_name.to_s # Checks if a blank table name has been given. # If so it returns an empty array of columns. return [] if table_name.strip.empty? indexes = [] pk_index = nil index_schema = [] #fetch the primary keys of the table using function primary_keys #TABLE_SCHEM:: pk_index[1] #TABLE_NAME:: pk_index[2] #COLUMN_NAME:: pk_index[3] #PK_NAME:: pk_index[5] stmt = IBM_DB.primary_keys( @connection, nil, @servertype.set_case(@schema), @servertype.set_case(table_name)) if(stmt) begin while ( pk_index_row = IBM_DB.fetch_array(stmt) ) if pk_index_row[5] pk_index_name = pk_index_row[5].downcase pk_index_columns = [pk_index_row[3].downcase] # COLUMN_NAME if pk_index pk_index.columns = pk_index.columns + pk_index_columns else pk_index = IndexDefinition.new(table_name, pk_index_name, true, pk_index_columns) end end end rescue StandardError => fetch_error # Handle driver fetch errors error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT ) if error_msg && !error_msg.empty? raise "Failed to retrieve primarykey metadata during fetch: #{error_msg}" else error_msg = "An unexpected error occurred during retrieval of primary key metadata" error_msg = error_msg + ": #{fetch_error.}" if !fetch_error..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 is_composite = true end i = i+1 end unless is_composite indexes << IndexDefinition.new(table_name, index_name, index_unique, index_columns) index_schema << index_qualifier end end end rescue StandardError => fetch_error # Handle driver fetch errors error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT ) if error_msg && !error_msg.empty? raise "Failed to retrieve index metadata during fetch: #{error_msg}" else error_msg = "An unexpected error occurred during retrieval of index metadata" error_msg = error_msg + ": #{fetch_error.}" if !fetch_error..empty? raise error_msg end ensure # Free resources associated with the statement IBM_DB.free_stmt(stmt) if stmt end else # Handle driver execution errors error_msg = IBM_DB.getErrormsg(@connection, IBM_DB::DB_CONN ) if error_msg && !error_msg.empty? raise "Failed to retrieve index metadata due to error: #{error_msg}" else raise StandardError.new('An unexpected error occurred during index retrieval') end end # remove the primary key index entry.... should not be dumped by the dumper i = 0 indexes.each do |index| if pk_index && index.columns == pk_index.columns indexes.delete_at(i) end i = i+1 end # Returns the indexes array return indexes end |
#insert(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.
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 876 def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) if @handle_lobs_triggered #Ensure the array of sql is cleared if they have been handled in the callback @sql = [] @handle_lobs_triggered = false end clear_query_cache if defined? clear_query_cache if stmt = execute(sql, name) begin @sql << sql return id_value || @servertype.last_generated_id(stmt) # Ensures to free the resources associated with the statement ensure IBM_DB.free_stmt(stmt) if stmt end end end |
#insert_fixture(fixture, table_name) ⇒ Object
inserts values from fixtures overridden to handle LOB’s fixture insertion, as, in normal inserts callbacks are triggered but during fixture insertion callbacks are not triggered hence only markers like @@@IBMBINARY@@@ will be inserted and are not updated to actual data
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 815 def insert_fixture(fixture, table_name) insert_query = "INSERT INTO #{quote_table_name(table_name)} ( #{fixture.key_list})" 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.type.to_sym == :text)) params << 'NULL' elsif col.type.to_sym == :xml || col.type.to_sym == :text || col.type.to_sym == :binary # 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 << item.at(1) params << '?' else insert_values << quote(item.at(1),col) params << '?' end end insert_query << " VALUES ("+ params.join(',') + ")" unless stmt = IBM_DB.prepare(@connection, insert_query) error_msg = IBM_DB.getErrormsg( @connection, IBM_DB::DB_CONN ) if error_msg && !error_msg.empty? raise "Failed to prepare statement for fixtures insert due to : #{error_msg}" else raise StandardError.new('An unexpected error occurred during preparing SQL for fixture insert') end end #log_query(insert_query,'fixture insert') log(insert_query,'fixture insert') do unless IBM_DB.execute(stmt, insert_values) error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT ) IBM_DB.free_stmt(stmt) if stmt raise "Failed to insert due to: #{error_msg}" else IBM_DB.free_stmt(stmt) if stmt end end end |
#log_query(sql, name) ⇒ Object
:nodoc:
585 586 587 588 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 585 def log_query(sql, name) #:nodoc: # Used by handle_lobs log(sql,name){} end |
#native_database_types ⇒ Object
Returns a Hash of mappings from the abstract data types to the native database types
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 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1222 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 => @servertype.get_datetime_mapping }, :timestamp => { :name => @servertype.get_datetime_mapping }, :time => { :name => @servertype.get_time_mapping }, :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"} } end |
#prepare(sql, name = nil) ⇒ Object
Praveen Prepares and logs sql
commands and returns a IBM_DB.Statement
object.
924 925 926 927 928 929 930 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 924 def prepare(sql,name = nil) # The +log+ method is defined in the parent class +AbstractAdapter+ @prepared_sql = sql log(sql,name) do @servertype.prepare(sql, name) end end |
#prepared_insert(pstmt, param_array = nil) ⇒ 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.
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 899 def prepared_insert(pstmt, param_array = nil) if @handle_lobs_triggered #Ensure the array of sql is cleared if they have been handled in the callback @sql = [] @sql_parameter_values = [] @handle_lobs_triggered = false end clear_query_cache if defined? clear_query_cache begin if execute_prepared_stmt(pstmt, param_array) @sql << @prepared_sql @sql_parameter_values << param_array return @servertype.last_generated_id(pstmt) end rescue StandardError => insert_err raise insert_err ensure IBM_DB.free_stmt(pstmt) if pstmt end end |
#prepared_select(sql_param_hash, name = nil) ⇒ Object
Returns an array of hashes with the column names as keys and column values as values. sql
is the select query, and name
is an optional description for logging
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 676 def prepared_select(sql_param_hash, name = nil) # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"} results = [] # Invokes the method +prepare+ in order prepare the SQL # IBM_DB.Statement is returned from which the statement is executed and results fetched pstmt = prepare(sql_param_hash["sqlSegment"], name) if(execute_prepared_stmt(pstmt, sql_param_hash["paramArray"])) begin @servertype.select(sql_param_hash["sqlSegment"], name, pstmt, results) rescue StandardError => fetch_error # Handle driver fetch errors error_msg = IBM_DB.getErrormsg(pstmt, IBM_DB::DB_STMT ) if error_msg && !error_msg.empty? raise StatementInvalid,"Failed to retrieve data: #{error_msg}" else error_msg = "An unexpected error occurred during data retrieval" error_msg = error_msg + ": #{fetch_error.}" if !fetch_error..empty? raise error_msg end ensure # Ensures to free the resources associated with the statement IBM_DB.free_stmt(pstmt) if pstmt end end # The array of record hashes is returned results end |
#prepared_select_values(sql_param_hash, name = nil) ⇒ Object
Returns an array of hashes with the column names as keys and column values as values. sql
is the select query, and name
is an optional description for logging
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 707 def prepared_select_values(sql_param_hash, name = nil) # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"} results = [] # Invokes the method +prepare+ in order prepare the SQL # IBM_DB.Statement is returned from which the statement is executed and results fetched pstmt = prepare(sql_param_hash["sqlSegment"], name) if(execute_prepared_stmt(pstmt, sql_param_hash["paramArray"])) begin @servertype.select_rows(sql_param_hash["sqlSegment"], name, pstmt, results) if results return results.map { |v| v[0] } else nil end rescue StandardError => fetch_error # Handle driver fetch errors error_msg = IBM_DB.getErrormsg(pstmt, IBM_DB::DB_STMT ) if error_msg && !error_msg.empty? raise StatementInvalid,"Failed to retrieve data: #{error_msg}" else error_msg = "An unexpected error occurred during data retrieval" error_msg = error_msg + ": #{fetch_error.}" if !fetch_error..empty? raise error_msg end ensure # Ensures to free the resources associated with the statement IBM_DB.free_stmt(pstmt) if pstmt end end # The array of record hashes is returned results end |
#prepared_update(pstmt, param_array = nil) ⇒ Object Also known as: prepared_delete
Praveen
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1002 def prepared_update(pstmt, param_array = nil ) if @handle_lobs_triggered #Ensure the array of sql is cleared if they have been handled in the callback @sql = [] @sql_parameter_values = [] @handle_lobs_triggered = false end clear_query_cache if defined? clear_query_cache begin if execute_prepared_stmt(pstmt, param_array) @sql << @prepared_sql @sql_parameter_values << param_array # Retrieves the number of affected rows IBM_DB.num_rows(pstmt) # Ensures to free the resources associated with the statement end rescue StandardError => updt_err raise updt_err ensure IBM_DB.free_stmt(pstmt) if pstmt end end |
#primary_key(table_name) ⇒ Object
Returns the primary key of the mentioned table
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1317 def primary_key(table_name) pk_name = nil stmt = IBM_DB.primary_keys( @connection, nil, @servertype.set_case(@schema), @servertype.set_case(table_name)) if(stmt) begin if ( pk_index_row = IBM_DB.fetch_array(stmt) ) pk_name = pk_index_row[3].downcase end rescue StandardError => fetch_error # Handle driver fetch errors error_msg = IBM_DB.getErrormsg( stmt, IBM_DB::DB_STMT ) if error_msg && !error_msg.empty? raise "Failed to retrieve primarykey metadata during fetch: #{error_msg}" else error_msg = "An unexpected error occurred during retrieval of primary key metadata" error_msg = error_msg + ": #{fetch_error.}" if !fetch_error..empty? raise error_msg end ensure # Free resources associated with the statement IBM_DB.free_stmt(stmt) if stmt end else error_msg = IBM_DB.getErrormsg( @connection, IBM_DB::DB_CONN ) if error_msg && !error_msg.empty? raise "Failed to retrieve primary key metadata due to error: #{error_msg}" else raise StandardError.new('An unexpected error occurred during primary key retrieval') end end return pk_name end |
#quote(value, column = nil) ⇒ Object
Properly quotes the various data types. value
contains the data, column
is optional and contains info on the field
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 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1138 def quote(value, column = nil) case value # If it's a numeric value and the column type is not a string, it shouldn't be quoted # (IBM_DB doesn't accept quotes on numeric types) when Numeric # If the column type is text or string, return the quote value if column && column.type.to_sym == :text || column && column.type.to_sym == :string unless caller[0] =~ /insert_fixture/i "'#{value}'" else "#{value}" end else # value is Numeric, column.type is not a string, # therefore it converts the number to string without quoting it value.to_s end when String, ActiveSupport::Multibyte::Chars if column && column.type.to_sym == :binary # If quoting is required for the insert/update of a BLOB unless caller[0] =~ /add_column_options/i # Invokes a convertion from string to binary @servertype.set_binary_value else # Quoting required for the default value of a column @servertype.set_binary_default(value) end elsif column && column.type.to_sym == :text unless caller[0] =~ /add_column_options/i "'@@@IBMTEXT@@@'" else @servertype.set_text_default(quote_string(value)) end elsif column && column.type.to_sym == :xml unless caller[0] =~ /add_column_options/i "'<ibm>@@@IBMXML@@@</ibm>'" else "#{value}" end else unless caller[0] =~ /insert_fixture/i "'#{quote_string(value)}'" else "#{value}" end end when TrueClass then quoted_true # return '1' for true when FalseClass then quoted_false # return '0' for false when NilClass if column && column.instance_of?(IBM_DBColumn) && !column.primary && !column.null "''" # allow empty inserts if not nullable or identity else # in order to support default ActiveRecord constructors "NULL" end else super # rely on superclass handling end end |
#quote_column_name(name) ⇒ Object
1212 1213 1214 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1212 def quote_column_name(name) @servertype.check_reserved_words(name) end |
#quote_string(string) ⇒ Object
Quotes a given string, escaping single quote (‘) characters.
1197 1198 1199 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1197 def quote_string(string) string.gsub(/'/, "''") end |
#quote_value_for_pstmt(value, column = nil) ⇒ Object
Praveen
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1108 def quote_value_for_pstmt(value, column=nil) return value.quoted_id if value.respond_to?(:quoted_id) case value when String, ActiveSupport::Multibyte::Chars then value = value.to_s if column && [:integer, :float].include?(column.type) value = column.type == :integer ? 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') else if value.acts_like?(:date) || value.acts_like?(:time) quoted_date(value) else value.to_yaml end end end |
#quoted_false ⇒ Object
1208 1209 1210 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1208 def quoted_false "0" end |
#quoted_true ⇒ Object
true is represented by a smallint 1, false by 0, as no native boolean type exists in DB2. Numerics are not quoted in DB2.
1204 1205 1206 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1204 def quoted_true "1" end |
#reconnect! ⇒ Object
Closes the current connection and opens a new one
636 637 638 639 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 636 def reconnect! disconnect! connect end |
#remove_column(table_name, column_name) ⇒ Object
Removes the column from the table definition.
Examples
remove_column(:suppliers, :qualification)
1573 1574 1575 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1573 def remove_column(table_name, column_name) @servertype.remove_column(table_name, column_name) end |
#remove_index(table_name, options = {}) ⇒ Object
Remove the given index from the table.
Remove the suppliers_name_index in the suppliers table (legacy support, use the second or third forms).
remove_index :suppliers, :name
Remove the index named accounts_branch_id in the accounts table.
remove_index :accounts, :column => :branch_id
Remove the index named by_branch_party in the accounts table.
remove_index :accounts, :name => :by_branch_party
You can remove an index on multiple columns by specifying the first column.
add_index :accounts, [:username, :password]
remove_index :accounts, :username
Overriden to use the IBM data servers SQL syntax.
1641 1642 1643 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1641 def remove_index(table_name, = {}) execute("DROP INDEX #{index_name(table_name, )}") end |
#rename_column(table_name, column_name, new_column_name) ⇒ Object
Renames a column.
Example
rename_column(:suppliers, :description, :name)
1566 1567 1568 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1566 def rename_column(table_name, column_name, new_column_name) @servertype.rename_column(table_name, column_name, new_column_name) end |
#rename_table(name, new_name) ⇒ Object
Renames a table.
Example
rename_table(‘octopuses’, ‘octopi’) Overriden to satisfy IBM data servers syntax
1554 1555 1556 1557 1558 1559 1560 1561 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1554 def rename_table(name, new_name) # SQL rename table statement rename_table_sql = "RENAME TABLE #{name} TO #{new_name}" stmt = execute(rename_table_sql) # Ensures to free the resources associated with the statement ensure IBM_DB.free_stmt(stmt) if stmt end |
#rollback_db_transaction ⇒ Object
Rolls back the transaction and turns on auto-committing. Must be done if the transaction block raises an exception or returns false
1047 1048 1049 1050 1051 1052 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1047 def rollback_db_transaction # ROLLBACK the transaction IBM_DB.rollback(@connection) rescue nil # Turns on auto-committing IBM_DB.autocommit @connection, IBM_DB::SQL_AUTOCOMMIT_ON end |
#select(sql, name = nil) ⇒ Object
Returns an array of hashes with the column names as keys and column values as values. sql
is the select query, and name
is an optional description for logging
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 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 743 def select(sql, name = nil) # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"} sql.gsub!( /(=\s*NULL|IN\s*\(NULL\))/i, " IS NULL" ) results = [] # Invokes the method +execute+ in order to log and execute the SQL # IBM_DB.Statement is returned from which results can be fetched stmt = execute(sql, name) if(stmt) begin @servertype.select(sql, name, stmt, results) rescue StandardError => fetch_error # Handle driver fetch errors error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT ) if error_msg && !error_msg.empty? raise StatementInvalid,"Failed to retrieve data: #{error_msg}" else error_msg = "An unexpected error occurred during data retrieval" error_msg = error_msg + ": #{fetch_error.}" if !fetch_error..empty? raise error_msg end ensure # Ensures to free the resources associated with the statement IBM_DB.free_stmt(stmt) if stmt end end # The array of record hashes is returned results end |
#select_one(sql, name = nil) ⇒ Object
Returns a record hash with the column names as keys and column values as values.
806 807 808 809 810 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 806 def select_one(sql, name = nil) # Gets the first hash from the array of hashes returned by # select_all select_all(sql,name).first end |
#select_rows(sql, name = nil) ⇒ Object
Returns an array of arrays containing the field values. This is an implementation for the abstract method sql
is the select query and name
is an optional description for logging
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 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 775 def select_rows(sql, name = nil) # Replaces {"= NULL" with " IS NULL"} OR {"IN (NULL)" with " IS NULL"} sql.gsub!( /(=\s*NULL|IN\s*\(NULL\))/i, " IS NULL" ) results = [] # Invokes the method +execute+ in order to log and execute the SQL # IBM_DB.Statement is returned from which results can be fetched stmt = execute(sql, name) if(stmt) begin @servertype.select_rows(sql, name, stmt, results) rescue StandardError => fetch_error # Handle driver fetch errors error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT ) if error_msg && !error_msg.empty? raise StatementInvalid,"Failed to retrieve data: #{error_msg}" else error_msg = "An unexpected error occurred during data retrieval" error_msg = error_msg + ": #{fetch_error.}" if !fetch_error..empty? raise error_msg end ensure # Ensures to free the resources associated with the statement IBM_DB.free_stmt(stmt) if stmt end end # The array of record hashes is returned results end |
#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.
581 582 583 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 581 def supports_ddl_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
574 575 576 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 574 def supports_migrations? true end |
#table_alias_length ⇒ Object
Returns the maximum length a table alias identifier can be. IBM data servers (cross-platform) table limit is 128 characters
1272 1273 1274 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1272 def table_alias_length 128 end |
#tables(name = nil) ⇒ Object
Retrieves table’s metadata for a specified shema name
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 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1277 def tables(name = nil) # Initializes the tables array tables = [] # Retrieve table's metadata through IBM_DB driver stmt = IBM_DB.tables(@connection, nil, @servertype.set_case(@schema)) if(stmt) begin # Fetches all the records available while tab = IBM_DB.fetch_assoc(stmt) # Adds the lowercase table name to the array if(tab["table_type"]== 'TABLE') #check, so that only tables are dumped,IBM_DB.tables also returns views,alias etc in the schema tables << tab["table_name"].downcase end end rescue StandardError => fetch_error # Handle driver fetch errors error_msg = IBM_DB.getErrormsg(stmt, IBM_DB::DB_STMT ) if error_msg && !error_msg.empty? raise "Failed to retrieve table metadata during fetch: #{error_msg}" else error_msg = "An unexpected error occurred during retrieval of table metadata" error_msg = error_msg + ": #{fetch_error.}" if !fetch_error..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 |
#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 data types.
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 1251 def type_to_sql(type, limit = nil, precision = nil, scale = nil) 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 return super if limit.nil? # 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 end end |
#update(sql, name = nil) ⇒ Object Also known as: delete
Executes an “UPDATE” SQL statement
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 |
# File 'lib/active_record/connection_adapters/ibm_db_adapter.rb', line 965 def update(sql, name = nil) if @handle_lobs_triggered #Ensure the array of sql is cleared if they have been handled in the callback @sql = [] @handle_lobs_triggered = false end clear_query_cache if defined? clear_query_cache # 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 # 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 |