Class: ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter
- Includes:
- ActiveRecord::ConnectionAdapters::OracleEnhanced::ColumnDumper, ActiveRecord::ConnectionAdapters::OracleEnhanced::ContextIndex, ActiveRecord::ConnectionAdapters::OracleEnhanced::DatabaseStatements, ActiveRecord::ConnectionAdapters::OracleEnhanced::SchemaStatements
- Defined in:
- lib/active_record/connection_adapters/oracle_enhanced_adapter.rb,
lib/active_record/connection_adapters/oracle_enhanced/database_tasks.rb
Overview
Oracle enhanced adapter will work with both Ruby 1.8/1.9 ruby-oci8 gem (which provides interface to Oracle OCI client) or with JRuby and Oracle JDBC driver.
It should work with Oracle 9i, 10g and 11g databases. Limited set of functionality should work on Oracle 8i as well but several features rely on newer functionality in Oracle database.
Usage notes:
-
Key generation assumes a “$table_name_seq” sequence is available for all tables; the sequence name can be changed using ActiveRecord::Base.set_sequence_name. When using Migrations, these sequences are created automatically. Use set_sequence_name :autogenerated with legacy tables that have triggers that populate primary keys automatically.
-
Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently some hacks are employed to map data back to Date or Time in Ruby. Timezones and sub-second precision on timestamps are not supported.
-
Default values that are functions (such as “SYSDATE”) are not supported. This is a restriction of the way ActiveRecord supports default values.
Required parameters:
-
:username
-
:password
-
:database
- either TNS alias or connection string for OCI client or database name in JDBC connection string
Optional parameters:
-
:host
- host name for JDBC connection, defaults to “localhost” -
:port
- port number for JDBC connection, defaults to 1521 -
:privilege
- set “SYSDBA” if you want to connect with this privilege -
:allow_concurrency
- set to “true” if non-blocking mode should be enabled (just for OCI client) -
:prefetch_rows
- how many rows should be fetched at one time to increase performance, defaults to 100 -
:cursor_sharing
- cursor sharing mode to minimize amount of unique statements, defaults to “force” -
:time_zone
- database session time zone (it is recommended to set it using ENV which will be then also used for database session time zone)
Optionals NLS parameters:
-
:nls_calendar
-
:nls_comp
-
:nls_currency
-
:nls_date_format
- format for :date columns, defaults toYYYY-MM-DD HH24:MI:SS
-
:nls_date_language
-
:nls_dual_currency
-
:nls_iso_currency
-
:nls_language
-
:nls_length_semantics
- semantics of size of VARCHAR2 and CHAR columns, defaults toCHAR
(meaning that size specifies number of characters and not bytes) -
:nls_nchar_conv_excp
-
:nls_numeric_characters
-
:nls_sort
-
:nls_territory
-
:nls_timestamp_format
- format for :timestamp columns, defaults toYYYY-MM-DD HH24:MI:SS:FF6
-
:nls_timestamp_tz_format
-
:nls_time_format
-
:nls_time_tz_format
Direct Known Subclasses
Defined Under Namespace
Classes: DatabaseTasks, StatementPool
Constant Summary collapse
- ADAPTER_NAME =
'OracleEnhanced'.freeze
- DEFAULT_NLS_PARAMETERS =
:stopdoc:
{ :nls_calendar => nil, :nls_comp => nil, :nls_currency => nil, :nls_date_format => 'YYYY-MM-DD HH24:MI:SS', :nls_date_language => nil, :nls_dual_currency => nil, :nls_iso_currency => nil, :nls_language => nil, :nls_length_semantics => 'CHAR', :nls_nchar_conv_excp => nil, :nls_numeric_characters => nil, :nls_sort => nil, :nls_territory => nil, :nls_timestamp_format => 'YYYY-MM-DD HH24:MI:SS:FF6', :nls_timestamp_tz_format => nil, :nls_time_format => nil, :nls_time_tz_format => nil }
- NATIVE_DATABASE_TYPES =
:stopdoc:
{ :primary_key => "NUMBER(38) NOT NULL PRIMARY KEY", :string => { :name => "VARCHAR2", :limit => 255 }, :text => { :name => "CLOB" }, :integer => { :name => "NUMBER", :limit => 38 }, :float => { :name => "BINARY_FLOAT" }, :decimal => { :name => "DECIMAL" }, :datetime => { :name => "DATE" }, # changed to native TIMESTAMP type # :timestamp => { :name => "DATE" }, :timestamp => { :name => "TIMESTAMP" }, :time => { :name => "DATE" }, :date => { :name => "DATE" }, :binary => { :name => "BLOB" }, :boolean => { :name => "NUMBER", :limit => 1 }, :raw => { :name => "RAW", :limit => 2000 }, :bigint => { :name => "NUMBER", :limit => 19 } }
- NATIVE_DATABASE_TYPES_BOOLEAN_STRINGS =
if emulate_booleans_from_strings then store booleans in VARCHAR2
NATIVE_DATABASE_TYPES.dup.merge( :boolean => { :name => "VARCHAR2", :limit => 1 } )
- IDENTIFIER_MAX_LENGTH =
maximum length of Oracle identifiers
30
- NONQUOTED_OBJECT_NAME =
Names must be from 1 to 30 bytes long with these exceptions:
-
Names of databases are limited to 8 bytes.
-
Names of database links can be as long as 128 bytes.
Nonquoted identifiers cannot be Oracle Database reserved words
Nonquoted identifiers must begin with an alphabetic character from your database character set
Nonquoted identifiers can contain only alphanumeric characters from your database character set and the underscore (_), dollar sign ($), and pound sign (#). Database links can also contain periods (.) and “at” signs (@). Oracle strongly discourages you from using $ and # in nonquoted identifiers.
-
/[A-Za-z][A-z0-9$#]{0,29}/
- NONQUOTED_DATABASE_LINK =
/[A-Za-z][A-z0-9$#\.@]{0,127}/
- VALID_TABLE_NAME =
/\A(?:#{NONQUOTED_OBJECT_NAME}\.)?#{NONQUOTED_OBJECT_NAME}(?:@#{NONQUOTED_DATABASE_LINK})?\Z/
- AUTOGENERATED_SEQUENCE_NAME =
use in set_sequence_name to avoid fetching primary key value from sequence
'autogenerated'.freeze
- DBMS_OUTPUT_BUFFER_SIZE =
Maximum DBMS_OUTPUT buffer size
10000
- VERSION =
File.read(File.('../../../../../VERSION', __FILE__)).chomp
- @@do_not_prefetch_primary_key =
{}
- @@ignore_table_columns =
:nodoc:
nil
- @@table_column_type =
:nodoc:
nil
Instance Attribute Summary collapse
-
#auto_retry ⇒ Object
If SQL statement fails due to lost connection then reconnect and retry SQL statement if autocommit mode is enabled.
Class Method Summary collapse
-
.boolean_to_string(bool) ⇒ Object
How boolean value should be quoted to String.
-
.encode_raw(value) ⇒ Object
Encode a string or byte array as string of hex codes.
-
.is_boolean_column?(name, sql_type, table_name = nil) ⇒ Boolean
Check column name to identify if it is boolean (and not String) column.
-
.is_date_column?(name, table_name = nil) ⇒ Boolean
Check column name to identify if it is Date (and not Time) column.
-
.is_integer_column?(name, table_name = nil) ⇒ Boolean
Check column name to identify if it is Integer (and not Float or BigDecimal) column.
-
.valid_table_name?(name) ⇒ Boolean
unescaped table name should start with letter and contain letters, digits, _, $ or # can be prefixed with schema name CamelCase table names should be quoted.
Instance Method Summary collapse
-
#active? ⇒ Boolean
Returns true if the connection is active.
-
#adapter_name ⇒ Object
:nodoc:.
-
#allowed_index_name_length ⇒ Object
Returns the maximum allowed length for an index name.
-
#cache_columns ⇒ Object
:singleton-method: Cache column description between requests.
-
#clear_columns_cache ⇒ Object
used just in tests to clear column cache.
-
#clear_ignored_table_columns ⇒ Object
used just in tests to clear ignored table columns.
-
#clear_prefetch_primary_key ⇒ Object
used just in tests to clear prefetch primary key flag for all tables.
-
#clear_table_columns_cache(table_name) ⇒ Object
used in migrations to clear column cache for specified table.
-
#clear_types_for_columns ⇒ Object
used just in tests to clear column data type definitions.
-
#column_name_length ⇒ Object
the maximum length of a column name.
-
#columns(table_name, name = nil) ⇒ Object
:nodoc:.
-
#columns_for_distinct(columns, orders) ⇒ Object
:nodoc:.
-
#columns_without_cache(table_name, name = nil) ⇒ Object
:nodoc:.
-
#current_database ⇒ Object
Current database name.
-
#current_schema ⇒ Object
Current database session schema.
-
#current_user ⇒ Object
Current database session user.
-
#dbms_output_enabled? ⇒ Boolean
Is DBMS_Output logging enabled?.
-
#default_sequence_start_value ⇒ Object
:singleton-method: Specify default sequence start with value (by default 10000 if not explicitly set), e.g.:.
-
#default_tablespace ⇒ Object
Default tablespace name of current user.
-
#disable_dbms_output ⇒ Object
Turn DBMS_Output logging off.
-
#disconnect! ⇒ Object
Disconnects from the database.
-
#distinct(columns, orders) ⇒ Object
SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
-
#emulate_booleans ⇒ Object
:singleton-method: By default, the OracleEnhancedAdapter will consider all columns of type
NUMBER(1)
as boolean. -
#emulate_booleans_from_strings ⇒ Object
:singleton-method: If you wish that CHAR(1), VARCHAR2(1) columns or VARCHAR2 columns with FLAG or YN at the end of their name are typecasted to booleans then you can add the following line to your initializer file:.
-
#emulate_dates ⇒ Object
:singleton-method: By default, the OracleEnhancedAdapter will typecast all columns of type
DATE
to Time or DateTime (if value is out of Time value range) value. -
#emulate_dates_by_column_name ⇒ Object
:singleton-method: By default, the OracleEnhancedAdapter will typecast all columns of type
DATE
to Time or DateTime (if value is out of Time value range) value. -
#emulate_integers_by_column_name ⇒ Object
:singleton-method: By default, the OracleEnhancedAdapter will typecast all columns of type
NUMBER
(without precision or scale) to Float or BigDecimal value. -
#enable_dbms_output ⇒ Object
Turn DBMS_Output logging on.
-
#get_type_for_column(table_name, column_name) ⇒ Object
:nodoc:.
-
#has_primary_key?(table_name, owner = nil, desc_table_name = nil, db_link = nil) ⇒ Boolean
:nodoc:.
-
#has_primary_key_trigger?(table_name, owner = nil, desc_table_name = nil, db_link = nil) ⇒ Boolean
check if table has primary key trigger with _pkt suffix.
-
#ignore_table_columns(table_name, *args) ⇒ Object
set ignored columns for table.
-
#ignored_table_columns(table_name) ⇒ Object
:nodoc:.
-
#in_clause_length ⇒ Object
(also: #ids_in_list_limit)
To avoid ORA-01795: maximum number of expressions in a list is 1000 tell ActiveRecord to limit us to 1000 ids at a time.
-
#index_name_length ⇒ Object
the maximum length of an index name supported by this database.
-
#indexes(table_name, name = nil) ⇒ Object
This method selects all indexes at once, and caches them in a class variable.
-
#initialize(connection, logger, config) ⇒ OracleEnhancedAdapter
constructor
:nodoc:.
-
#is_date_column?(name, table_name = nil) ⇒ Boolean
instance method uses at first check if column type defined at class level.
-
#join_to_update(update, select) ⇒ Object
construct additional wrapper subquery if select.offset is used to avoid generation of invalid subquery …
-
#materialized_views ⇒ Object
:nodoc:.
-
#native_database_types ⇒ Object
:startdoc:.
- #new_column(name, default, cast_type, sql_type = nil, null = true, table_name = nil, virtual = false, returning_id = false) ⇒ Object
-
#next_sequence_value(sequence_name) ⇒ Object
Returns the next sequence value from a sequence generator.
-
#pk_and_sequence_for(table_name, owner = nil, desc_table_name = nil, db_link = nil) ⇒ Object
Find a table’s primary key and sequence.
-
#pk_and_sequence_for_without_cache(table_name, owner = nil, desc_table_name = nil, db_link = nil) ⇒ Object
:nodoc:.
-
#prefetch_primary_key?(table_name = nil) ⇒ Boolean
Returns true for Oracle adapter (since Oracle requires primary key values to be pre-fetched before insert).
-
#primary_key(table_name) ⇒ Object
Returns just a table’s primary key.
-
#quote(value, column = nil) ⇒ Object
:nodoc:.
-
#quote_column_name(name) ⇒ Object
QUOTING ==================================================.
-
#quote_column_name_or_expression(name) ⇒ Object
This method is used in add_index to identify either column name (which is quoted) or function based index (in which case function expression is not quoted).
-
#quote_database_link(name) ⇒ Object
Used only for quoting database links as the naming rules for links differ from the rules for column names.
-
#quote_date_with_to_date(value) ⇒ Object
:nodoc:.
-
#quote_raw(value) ⇒ Object
quote encoded raw value.
-
#quote_string(s) ⇒ Object
:nodoc:.
-
#quote_table_name(name) ⇒ Object
:nodoc:.
-
#quote_timestamp_with_to_timestamp(value) ⇒ Object
:nodoc:.
-
#quoted_false ⇒ Object
:nodoc:.
-
#quoted_true ⇒ Object
:nodoc:.
-
#raw_connection ⇒ Object
return raw OCI8 or JDBC connection.
-
#reconnect! ⇒ Object
Reconnects to the database.
- #reset! ⇒ Object
-
#reset_pk_sequence!(table_name, primary_key = nil, sequence_name = nil) ⇒ Object
:nodoc:.
- #schema_creation ⇒ Object
-
#sequence_name_length ⇒ Object
the maximum length of a sequence name.
-
#set_type_for_columns(table_name, column_type, *args) ⇒ Object
set explicit type for specified table columns.
-
#string_to_date_format ⇒ Object
:singleton-method: Specify non-default date format that should be used when assigning string values to :date columns, e.g.:.
-
#string_to_time_format ⇒ Object
:singleton-method: Specify non-default time format that should be used when assigning string values to :datetime columns, e.g.:.
- #supports_foreign_keys? ⇒ Boolean
-
#supports_migrations? ⇒ Boolean
:nodoc:.
-
#supports_primary_key? ⇒ Boolean
:nodoc:.
-
#supports_savepoints? ⇒ Boolean
:nodoc:.
-
#supports_transaction_isolation? ⇒ Boolean
:nodoc:.
- #supports_views? ⇒ Boolean
-
#table_alias_length ⇒ Object
:nodoc:.
-
#table_exists?(table_name) ⇒ Boolean
Will return true if database object exists (to be able to use also views and synonyms for ActiveRecord models).
-
#table_name_length ⇒ Object
the maximum length of a table name.
-
#tables(name = nil) ⇒ Object
:nodoc:.
-
#temporary_table?(table_name) ⇒ Boolean
:nodoc:.
-
#type_cast(value, column) ⇒ Object
Cast a
value
to a type that the database understands. -
#write_lobs(table_name, klass, attributes, columns) ⇒ Object
Writes LOB values from attributes for specified columns.
Methods included from ActiveRecord::ConnectionAdapters::OracleEnhanced::ContextIndex
#add_context_index, #remove_context_index
Methods included from ActiveRecord::ConnectionAdapters::OracleEnhanced::ColumnDumper
#column_spec_with_oracle_enhanced, included, #migration_keys_with_oracle_enhanced, #prepare_column_options_with_oracle_enhanced
Methods included from ActiveRecord::ConnectionAdapters::OracleEnhanced::SchemaStatements
#add_column, #add_comment, #add_foreign_key, #add_index, #add_index_options, #add_table_comment, #aliased_types, #change_column, #change_column_default, #change_column_null, #column_comment, #create_table, #create_table_definition, #disable_referential_integrity, #drop_table, #dump_schema_information, #extract_foreign_key_action, #foreign_keys, #index_name, #index_name_exists?, #initialize_schema_migrations_table, #remove_column, #remove_foreign_key, #remove_index, #remove_index!, #rename_column, #rename_index, #rename_table, #table_comment, #tablespace, #type_to_sql, #update_table_definition
Methods included from ActiveRecord::ConnectionAdapters::OracleEnhanced::DatabaseStatements
#begin_db_transaction, #begin_isolated_db_transaction, #clear_cache!, #commit_db_transaction, #create_savepoint, #default_sequence_name, #exec_insert, #exec_query, #exec_rollback_db_transaction, #exec_rollback_to_savepoint, #exec_update, #execute, #explain, #insert_fixture, #release_savepoint, #select_rows, #sql_for_insert, #supports_explain?, #supports_statement_cache?, #transaction_isolation_levels
Constructor Details
#initialize(connection, logger, config) ⇒ OracleEnhancedAdapter
:nodoc:
392 393 394 395 396 397 398 399 400 401 402 403 404 405 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 392 def initialize(connection, logger, config) #:nodoc: super(connection, logger) @quoted_column_names, @quoted_table_names = {}, {} @config = config @statements = StatementPool.new(connection, config.fetch(:statement_limit) { 250 }) @enable_dbms_output = false @visitor = Arel::Visitors::Oracle.new self if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true }) @prepared_statements = true else @prepared_statements = false end end |
Instance Attribute Details
#auto_retry ⇒ Object
If SQL statement fails due to lost connection then reconnect and retry SQL statement if autocommit mode is enabled. By default this functionality is disabled.
709 710 711 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 709 def auto_retry @auto_retry end |
Class Method Details
.boolean_to_string(bool) ⇒ Object
How boolean value should be quoted to String. Used if emulate_booleans_from_strings
option is set to true
.
342 343 344 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 342 def self.boolean_to_string(bool) bool ? "Y" : "N" end |
.encode_raw(value) ⇒ Object
Encode a string or byte array as string of hex codes
661 662 663 664 665 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 661 def self.encode_raw(value) # When given a string, convert to a byte array. value = value.unpack('C*') if value.is_a?(String) value.map { |x| "%02X" % x }.join end |
.is_boolean_column?(name, sql_type, table_name = nil) ⇒ Boolean
Check column name to identify if it is boolean (and not String) column. Is used if emulate_booleans_from_strings
option is set to true
. Override this method definition in initializer file if different boolean column recognition is needed.
335 336 337 338 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 335 def self.is_boolean_column?(name, sql_type, table_name = nil) return true if ["CHAR(1)","VARCHAR2(1)"].include?(sql_type) sql_type =~ /^VARCHAR2/ && (name =~ /_flag$/i || name =~ /_yn$/i) end |
.is_date_column?(name, table_name = nil) ⇒ Boolean
Check column name to identify if it is Date (and not Time) column. Is used if emulate_dates_by_column_name
option is set to true
. Override this method definition in initializer file if different Date column recognition is needed.
289 290 291 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 289 def self.is_date_column?(name, table_name = nil) name =~ /(^|_)date(_|$)/i end |
.is_integer_column?(name, table_name = nil) ⇒ Boolean
Check column name to identify if it is Integer (and not Float or BigDecimal) column. Is used if emulate_integers_by_column_name
option is set to true
. Override this method definition in initializer file if different Integer column recognition is needed.
319 320 321 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 319 def self.is_integer_column?(name, table_name = nil) name =~ /(^|_)id$/i end |
.valid_table_name?(name) ⇒ Boolean
unescaped table name should start with letter and contain letters, digits, _, $ or # can be prefixed with schema name CamelCase table names should be quoted
599 600 601 602 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 599 def self.valid_table_name?(name) #:nodoc: name = name.to_s name =~ VALID_TABLE_NAME && !(name =~ /[A-Z]/ && name =~ /[a-z]/) ? true : false end |
Instance Method Details
#active? ⇒ Boolean
Returns true if the connection is active.
723 724 725 726 727 728 729 730 731 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 723 def active? #:nodoc: # Pings the connection to check if it's still good. Note that an # #active? method is also available, but that simply returns the # last known state, which isn't good enough if the connection has # gone stale since the last use. @connection.ping rescue OracleEnhancedConnectionException false end |
#adapter_name ⇒ Object
:nodoc:
409 410 411 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 409 def adapter_name #:nodoc: ADAPTER_NAME end |
#allowed_index_name_length ⇒ Object
Returns the maximum allowed length for an index name. This limit is enforced by rails and Is less than or equal to index_name_length
. The gap between index_name_length
is to allow internal rails opreations to use prefixes in temporary opreations.
509 510 511 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 509 def allowed_index_name_length index_name_length end |
#cache_columns ⇒ Object
:singleton-method: Cache column description between requests. Could be used in development environment to avoid selecting table columns from data dictionary tables for each request. This can speed up request processing in development mode if development database is not on local computer.
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.cache_columns = true
1016 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1016 cattr_accessor :cache_columns |
#clear_columns_cache ⇒ Object
used just in tests to clear column cache
1133 1134 1135 1136 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1133 def clear_columns_cache #:nodoc: @@columns_cache = nil @@pk_and_sequence_for_cache = nil end |
#clear_ignored_table_columns ⇒ Object
used just in tests to clear ignored table columns
968 969 970 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 968 def clear_ignored_table_columns #:nodoc: @@ignore_table_columns = nil end |
#clear_prefetch_primary_key ⇒ Object
used just in tests to clear prefetch primary key flag for all tables
783 784 785 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 783 def clear_prefetch_primary_key #:nodoc: @@do_not_prefetch_primary_key = {} end |
#clear_table_columns_cache(table_name) ⇒ Object
used in migrations to clear column cache for specified table
1139 1140 1141 1142 1143 1144 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1139 def clear_table_columns_cache(table_name) if @@cache_columns @@columns_cache ||= {} @@columns_cache[table_name.to_s] = nil end end |
#clear_types_for_columns ⇒ Object
used just in tests to clear column data type definitions
988 989 990 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 988 def clear_types_for_columns #:nodoc: @@table_column_type = nil end |
#column_name_length ⇒ Object
the maximum length of a column name
500 501 502 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 500 def column_name_length IDENTIFIER_MAX_LENGTH end |
#columns(table_name, name = nil) ⇒ Object
:nodoc:
1019 1020 1021 1022 1023 1024 1025 1026 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1019 def columns(table_name, name = nil) #:nodoc: if @@cache_columns @@columns_cache ||= {} @@columns_cache[table_name] ||= columns_without_cache(table_name, name) else columns_without_cache(table_name, name) end end |
#columns_for_distinct(columns, orders) ⇒ Object
:nodoc:
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1232 def columns_for_distinct(columns, orders) #:nodoc: # construct a valid columns name for DISTINCT clause, # ie. one that includes the ORDER BY columns, using FIRST_VALUE such that # the inclusion of these columns doesn't invalidate the DISTINCT # # It does not construct DISTINCT clause. Just return column names for distinct. order_columns = orders.reject(&:blank?).map{ |s| s = s.to_sql unless s.is_a?(String) # remove any ASC/DESC modifiers s.gsub(/\s+(ASC|DESC)\s*?/i, '') }.reject(&:blank?).map.with_index { |column,i| "FIRST_VALUE(#{column}) OVER (PARTITION BY #{columns} ORDER BY #{column}) AS alias_#{i}__" } [super, *order_columns].join(', ') end |
#columns_without_cache(table_name, name = nil) ⇒ Object
:nodoc:
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 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 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1028 def columns_without_cache(table_name, name = nil) #:nodoc: table_name = table_name.to_s # get ignored_columns by original table name ignored_columns = ignored_table_columns(table_name) (owner, desc_table_name, db_link) = @connection.describe(table_name) # reset do_not_prefetch_primary_key cache for this table @@do_not_prefetch_primary_key[table_name] = nil table_cols = <<-SQL.strip.gsub(/\s+/, ' ') SELECT column_name AS name, data_type AS sql_type, data_default, nullable, virtual_column, hidden_column, data_type_owner AS sql_type_owner, DECODE(data_type, 'NUMBER', data_precision, 'FLOAT', data_precision, 'VARCHAR2', DECODE(char_used, 'C', char_length, data_length), 'RAW', DECODE(char_used, 'C', char_length, data_length), 'CHAR', DECODE(char_used, 'C', char_length, data_length), NULL) AS limit, DECODE(data_type, 'NUMBER', data_scale, NULL) AS scale FROM all_tab_cols#{db_link} WHERE owner = '#{owner}' AND table_name = '#{desc_table_name}' AND hidden_column = 'NO' ORDER BY column_id SQL # added deletion of ignored columns select_all(table_cols, name).to_a.delete_if do |row| ignored_columns && ignored_columns.include?(row['name'].downcase) end.map do |row| limit, scale = row['limit'], row['scale'] if limit || scale row['sql_type'] += "(#{(limit || 38).to_i}" + ((scale = scale.to_i) > 0 ? ",#{scale})" : ")") end if row['sql_type_owner'] row['sql_type'] = row['sql_type_owner'] + '.' + row['sql_type'] end is_virtual = row['virtual_column']=='YES' # clean up odd default spacing from Oracle if row['data_default'] && !is_virtual row['data_default'].sub!(/^(.*?)\s*$/, '\1') # If a default contains a newline these cleanup regexes need to # match newlines. row['data_default'].sub!(/^'(.*)'$/m, '\1') row['data_default'] = nil if row['data_default'] =~ /^(null|empty_[bc]lob\(\))$/i # TODO: Needs better fix to fallback "N" to false row['data_default'] = false if row['data_default'] == "N" end # TODO: Consider to extract another method such as `get_cast_type` case row['sql_type'] when /decimal|numeric|number/i if get_type_for_column(table_name, oracle_downcase(row['name'])) == :integer cast_type = ActiveRecord::OracleEnhanced::Type::Integer.new elsif OracleEnhancedAdapter.emulate_booleans && row['sql_type'].upcase == "NUMBER(1)" cast_type = Type::Boolean.new elsif OracleEnhancedAdapter.emulate_integers_by_column_name && OracleEnhancedAdapter.is_integer_column?(row['name'], table_name) cast_type = ActiveRecord::OracleEnhanced::Type::Integer.new else cast_type = lookup_cast_type(row['sql_type']) end when /char/i if get_type_for_column(table_name, oracle_downcase(row['name'])) == :string cast_type = Type::String.new elsif get_type_for_column(table_name, oracle_downcase(row['name'])) == :boolean cast_type = Type::Boolean.new elsif OracleEnhancedAdapter.emulate_booleans_from_strings && OracleEnhancedAdapter.is_boolean_column?(row['name'], row['sql_type'], table_name) cast_type = Type::Boolean.new else cast_type = lookup_cast_type(row['sql_type']) end when /date/i if get_type_for_column(table_name, oracle_downcase(row['name'])) == :date cast_type = Type::Date.new elsif get_type_for_column(table_name, oracle_downcase(row['name'])) == :datetime cast_type = Type::DateTime.new elsif OracleEnhancedAdapter.emulate_dates_by_column_name && OracleEnhancedAdapter.is_date_column?(row['name'], table_name) cast_type = Type::Date.new else cast_type = lookup_cast_type(row['sql_type']) end else cast_type = lookup_cast_type(row['sql_type']) end new_column(oracle_downcase(row['name']), row['data_default'], cast_type, row['sql_type'], row['nullable'] == 'Y', table_name, is_virtual, false ) end end |
#current_database ⇒ Object
Current database name
843 844 845 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 843 def current_database select_value("SELECT SYS_CONTEXT('userenv', 'db_name') FROM dual") end |
#current_schema ⇒ Object
Current database session schema
853 854 855 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 853 def current_schema select_value("SELECT SYS_CONTEXT('userenv', 'current_schema') FROM dual") end |
#current_user ⇒ Object
Current database session user
848 849 850 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 848 def current_user select_value("SELECT SYS_CONTEXT('userenv', 'current_schema') FROM dual") end |
#dbms_output_enabled? ⇒ Boolean
Is DBMS_Output logging enabled?
1347 1348 1349 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1347 def dbms_output_enabled? @enable_dbms_output end |
#default_sequence_start_value ⇒ Object
:singleton-method: Specify default sequence start with value (by default 10000 if not explicitly set), e.g.:
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.default_sequence_start_value = 1
1151 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1151 cattr_accessor :default_sequence_start_value |
#default_tablespace ⇒ Object
Default tablespace name of current user
858 859 860 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 858 def default_tablespace select_value("SELECT LOWER(default_tablespace) FROM user_users WHERE username = SYS_CONTEXT('userenv', 'current_schema')") end |
#disable_dbms_output ⇒ Object
Turn DBMS_Output logging off
1341 1342 1343 1344 1345 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1341 def disable_dbms_output set_dbms_output_plsql_connection @enable_dbms_output = false plsql(:dbms_output).sys.dbms_output.disable end |
#disconnect! ⇒ Object
Disconnects from the database.
747 748 749 750 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 747 def disconnect! #:nodoc: super @connection.logoff rescue nil end |
#distinct(columns, orders) ⇒ Object
SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
Oracle requires the ORDER BY columns to be in the SELECT list for DISTINCT queries. However, with those columns included in the SELECT DISTINCT list, you won’t actually get a distinct list of the column you want (presuming the column has duplicates with multiple values for the ordered-by columns. So we use the FIRST_VALUE function to get a single (first) value for each column, effectively making every row the same.
distinct("posts.id", "posts.created_at desc")
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1215 def distinct(columns, orders) #:nodoc: # To support Rails 4.0.0 and future releases # because `columns_for_distinct method introduced after Rails 4.0.0 released if super.respond_to?(:columns_for_distinct) super else order_columns = orders.map { |c| c = c.to_sql unless c.is_a?(String) # remove any ASC/DESC modifiers c.gsub(/\s+(ASC|DESC)\s*?/i, '') }.reject(&:blank?).map.with_index { |c,i| "FIRST_VALUE(#{c}) OVER (PARTITION BY #{columns} ORDER BY #{c}) AS alias_#{i}__" } [super].concat(order_columns).join(', ') end end |
#emulate_booleans ⇒ Object
:singleton-method: By default, the OracleEnhancedAdapter will consider all columns of type NUMBER(1)
as boolean. If you wish to disable this emulation you can add the following line to your initializer file:
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_booleans = false
242 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 242 cattr_accessor :emulate_booleans |
#emulate_booleans_from_strings ⇒ Object
:singleton-method: If you wish that CHAR(1), VARCHAR2(1) columns or VARCHAR2 columns with FLAG or YN at the end of their name are typecasted to booleans then you can add the following line to your initializer file:
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_booleans_from_strings = true
329 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 329 cattr_accessor :emulate_booleans_from_strings |
#emulate_dates ⇒ Object
:singleton-method: By default, the OracleEnhancedAdapter will typecast all columns of type DATE
to Time or DateTime (if value is out of Time value range) value. If you wish that DATE values with hour, minutes and seconds equal to 0 are typecasted to Date then you can add the following line to your initializer file:
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_dates = true
As this option can have side effects when unnecessary typecasting is done it is recommended that Date columns are explicily defined with set_date_columns
method.
256 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 256 cattr_accessor :emulate_dates |
#emulate_dates_by_column_name ⇒ Object
:singleton-method: By default, the OracleEnhancedAdapter will typecast all columns of type DATE
to Time or DateTime (if value is out of Time value range) value. If you wish that DATE columns with “date” in their name (e.g. “creation_date”) are typecasted to Date then you can add the following line to your initializer file:
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_dates_by_column_name = true
As this option can have side effects when unnecessary typecasting is done it is recommended that Date columns are explicily defined with set_date_columns
method.
283 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 283 cattr_accessor :emulate_dates_by_column_name |
#emulate_integers_by_column_name ⇒ Object
:singleton-method: By default, the OracleEnhancedAdapter will typecast all columns of type NUMBER
(without precision or scale) to Float or BigDecimal value. If you wish that NUMBER columns with name “id” or that end with “_id” are typecasted to Integer then you can add the following line to your initializer file:
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.emulate_integers_by_column_name = true
313 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 313 cattr_accessor :emulate_integers_by_column_name |
#enable_dbms_output ⇒ Object
Turn DBMS_Output logging on
1335 1336 1337 1338 1339 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1335 def enable_dbms_output set_dbms_output_plsql_connection @enable_dbms_output = true plsql(:dbms_output).sys.dbms_output.enable(DBMS_OUTPUT_BUFFER_SIZE) end |
#get_type_for_column(table_name, column_name) ⇒ Object
:nodoc:
983 984 985 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 983 def get_type_for_column(table_name, column_name) #:nodoc: @@table_column_type && @@table_column_type[table_name] && @@table_column_type[table_name][column_name.to_s.downcase] end |
#has_primary_key?(table_name, owner = nil, desc_table_name = nil, db_link = nil) ⇒ Boolean
:nodoc:
1201 1202 1203 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1201 def has_primary_key?(table_name, owner=nil, desc_table_name=nil, db_link=nil) #:nodoc: !pk_and_sequence_for(table_name, owner, desc_table_name, db_link).nil? end |
#has_primary_key_trigger?(table_name, owner = nil, desc_table_name = nil, db_link = nil) ⇒ Boolean
check if table has primary key trigger with _pkt suffix
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 993 def has_primary_key_trigger?(table_name, owner = nil, desc_table_name = nil, db_link = nil) (owner, desc_table_name, db_link) = @connection.describe(table_name) unless owner trigger_name = default_trigger_name(table_name).upcase pkt_sql = <<-SQL SELECT trigger_name FROM all_triggers#{db_link} WHERE owner = '#{owner}' AND trigger_name = '#{trigger_name}' AND table_owner = '#{owner}' AND table_name = '#{desc_table_name}' AND status = 'ENABLED' SQL select_value(pkt_sql, 'Primary Key Trigger') ? true : false end |
#ignore_table_columns(table_name, *args) ⇒ Object
set ignored columns for table
955 956 957 958 959 960 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 955 def ignore_table_columns(table_name, *args) #:nodoc: @@ignore_table_columns ||= {} @@ignore_table_columns[table_name] ||= [] @@ignore_table_columns[table_name] += args.map{|a| a.to_s.downcase} @@ignore_table_columns[table_name].uniq! end |
#ignored_table_columns(table_name) ⇒ Object
:nodoc:
962 963 964 965 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 962 def ignored_table_columns(table_name) #:nodoc: @@ignore_table_columns ||= {} @@ignore_table_columns[table_name] end |
#in_clause_length ⇒ Object Also known as: ids_in_list_limit
To avoid ORA-01795: maximum number of expressions in a list is 1000 tell ActiveRecord to limit us to 1000 ids at a time
526 527 528 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 526 def in_clause_length 1000 end |
#index_name_length ⇒ Object
the maximum length of an index name supported by this database
515 516 517 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 515 def index_name_length IDENTIFIER_MAX_LENGTH end |
#indexes(table_name, name = nil) ⇒ Object
This method selects all indexes at once, and caches them in a class variable. Subsequent index calls get them from the variable, without going to the DB.
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 884 def indexes(table_name, name = nil) #:nodoc: (owner, table_name, db_link) = @connection.describe(table_name) unless all_schema_indexes default_tablespace_name = default_tablespace result = select_all(<<-SQL.strip.gsub(/\s+/, ' ')) SELECT LOWER(i.table_name) AS table_name, LOWER(i.index_name) AS index_name, i.uniqueness, i.index_type, i.ityp_owner, i.ityp_name, i.parameters, LOWER(i.tablespace_name) AS tablespace_name, LOWER(c.column_name) AS column_name, e.column_expression, atc.virtual_column FROM all_indexes#{db_link} i JOIN all_ind_columns#{db_link} c ON c.index_name = i.index_name AND c.index_owner = i.owner LEFT OUTER JOIN all_ind_expressions#{db_link} e ON e.index_name = i.index_name AND e.index_owner = i.owner AND e.column_position = c.column_position LEFT OUTER JOIN all_tab_cols#{db_link} atc ON i.table_name = atc.table_name AND c.column_name = atc.column_name AND i.owner = atc.owner AND atc.hidden_column = 'NO' WHERE i.owner = '#{owner}' AND i.table_owner = '#{owner}' AND NOT EXISTS (SELECT uc.index_name FROM all_constraints uc WHERE uc.index_name = i.index_name AND uc.owner = i.owner AND uc.constraint_type = 'P') ORDER BY i.index_name, c.column_position SQL current_index = nil self.all_schema_indexes = [] result.each do |row| # have to keep track of indexes because above query returns dups # there is probably a better query we could figure out if current_index != row['index_name'] statement_parameters = nil if row['index_type'] == 'DOMAIN' && row['ityp_owner'] == 'CTXSYS' && row['ityp_name'] == 'CONTEXT' procedure_name = default_datastore_procedure(row['index_name']) source = select_values(<<-SQL).join SELECT text FROM all_source#{db_link} WHERE owner = '#{owner}' AND name = '#{procedure_name.upcase}' ORDER BY line SQL if source =~ /-- add_context_index_parameters (.+)\n/ statement_parameters = $1 end end all_schema_indexes << OracleEnhanced::IndexDefinition.new(row['table_name'], row['index_name'], row['uniqueness'] == "UNIQUE", row['index_type'] == 'DOMAIN' ? "#{row['ityp_owner']}.#{row['ityp_name']}" : nil, row['parameters'], statement_parameters, row['tablespace_name'] == default_tablespace_name ? nil : row['tablespace_name'], []) current_index = row['index_name'] end # Functional index columns and virtual columns both get stored as column expressions, # but re-creating a virtual column index as an expression (instead of using the virtual column's name) # results in a ORA-54018 error. Thus, we only want the column expression value returned # when the column is not virtual. if row['column_expression'] && row['virtual_column'] != 'YES' all_schema_indexes.last.columns << row['column_expression'] else all_schema_indexes.last.columns << row['column_name'].downcase end end end # Return the indexes just for the requested table, since AR is structured that way table_name = table_name.downcase all_schema_indexes.select{|i| i.table == table_name} end |
#is_date_column?(name, table_name = nil) ⇒ Boolean
instance method uses at first check if column type defined at class level
294 295 296 297 298 299 300 301 302 303 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 294 def is_date_column?(name, table_name = nil) #:nodoc: case get_type_for_column(table_name, name) when nil self.class.is_date_column?(name, table_name) when :date true else false end end |
#join_to_update(update, select) ⇒ Object
construct additional wrapper subquery if select.offset is used to avoid generation of invalid subquery … IN ( SELECT * FROM ( SELECT raw_sql_.*, rownum raw_rnum_ FROM ( … ) raw_sql_ ) WHERE raw_rnum_ > … )
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1254 def join_to_update(update, select) #:nodoc: if select.offset subsubselect = select.clone subsubselect.projections = [update.key] subselect = Arel::SelectManager.new(select.engine) subselect.project Arel.sql(quote_column_name update.key.name) subselect.from subsubselect.as('alias_join_to_update') update.where update.key.in(subselect) else super end end |
#materialized_views ⇒ Object
:nodoc:
876 877 878 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 876 def materialized_views #:nodoc: select_values("SELECT LOWER(mview_name) FROM all_mviews WHERE owner = SYS_CONTEXT('userenv', 'current_schema')") end |
#native_database_types ⇒ Object
:startdoc:
483 484 485 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 483 def native_database_types #:nodoc: emulate_booleans_from_strings ? NATIVE_DATABASE_TYPES_BOOLEAN_STRINGS : NATIVE_DATABASE_TYPES end |
#new_column(name, default, cast_type, sql_type = nil, null = true, table_name = nil, virtual = false, returning_id = false) ⇒ Object
1128 1129 1130 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1128 def new_column(name, default, cast_type, sql_type = nil, null = true, table_name = nil, virtual=false, returning_id=false) OracleEnhancedColumn.new(name, default, cast_type, sql_type, null, table_name, virtual, returning_id) end |
#next_sequence_value(sequence_name) ⇒ Object
Returns the next sequence value from a sequence generator. Not generally called directly; used by ActiveRecord to get the next primary key value when inserting a new database record (see #prefetch_primary_key?).
758 759 760 761 762 763 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 758 def next_sequence_value(sequence_name) # if sequence_name is set to :autogenerated then it means that primary key will be populated by trigger return nil if sequence_name == AUTOGENERATED_SEQUENCE_NAME # call directly connection method to avoid prepared statement which causes fetching of next sequence value twice @connection.select_value("SELECT #{quote_table_name(sequence_name)}.NEXTVAL FROM dual") end |
#pk_and_sequence_for(table_name, owner = nil, desc_table_name = nil, db_link = nil) ⇒ Object
Find a table’s primary key and sequence. Note: Only primary key is implemented - sequence will be nil.
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1156 def pk_and_sequence_for(table_name, owner=nil, desc_table_name=nil, db_link=nil) #:nodoc: if @@cache_columns @@pk_and_sequence_for_cache ||= {} if @@pk_and_sequence_for_cache.key?(table_name) @@pk_and_sequence_for_cache[table_name] else @@pk_and_sequence_for_cache[table_name] = pk_and_sequence_for_without_cache(table_name, owner, desc_table_name, db_link) end else pk_and_sequence_for_without_cache(table_name, owner, desc_table_name, db_link) end end |
#pk_and_sequence_for_without_cache(table_name, owner = nil, desc_table_name = nil, db_link = nil) ⇒ Object
:nodoc:
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 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1169 def pk_and_sequence_for_without_cache(table_name, owner=nil, desc_table_name=nil, db_link=nil) #:nodoc: (owner, desc_table_name, db_link) = @connection.describe(table_name) unless owner seqs = select_values(<<-SQL.strip.gsub(/\s+/, ' '), 'Sequence') select us.sequence_name from all_sequences#{db_link} us where us.sequence_owner = '#{owner}' and us.sequence_name = '#{desc_table_name}_SEQ' SQL # changed back from user_constraints to all_constraints for consistency pks = select_values(<<-SQL.strip.gsub(/\s+/, ' '), 'Primary Key') SELECT cc.column_name FROM all_constraints#{db_link} c, all_cons_columns#{db_link} cc WHERE c.owner = '#{owner}' AND c.table_name = '#{desc_table_name}' AND c.constraint_type = 'P' AND cc.owner = c.owner AND cc.constraint_name = c.constraint_name SQL # only support single column keys pks.size == 1 ? [oracle_downcase(pks.first), oracle_downcase(seqs.first)] : nil end |
#prefetch_primary_key?(table_name = nil) ⇒ Boolean
Returns true for Oracle adapter (since Oracle requires primary key values to be pre-fetched before insert). See also #next_sequence_value.
769 770 771 772 773 774 775 776 777 778 779 780 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 769 def prefetch_primary_key?(table_name = nil) return true if table_name.nil? table_name = table_name.to_s do_not_prefetch = @@do_not_prefetch_primary_key[table_name] if do_not_prefetch.nil? owner, desc_table_name, db_link = @connection.describe(table_name) @@do_not_prefetch_primary_key[table_name] = do_not_prefetch = !has_primary_key?(table_name, owner, desc_table_name, db_link) || has_primary_key_trigger?(table_name, owner, desc_table_name, db_link) end !do_not_prefetch end |
#primary_key(table_name) ⇒ Object
Returns just a table’s primary key
1196 1197 1198 1199 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1196 def primary_key(table_name) pk_and_sequence = pk_and_sequence_for(table_name) pk_and_sequence && pk_and_sequence.first end |
#quote(value, column = nil) ⇒ Object
:nodoc:
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 613 def quote(value, column = nil) #:nodoc: if value && column case column.type when :text, :binary %Q{empty_#{ type_to_sql(column.type.to_sym).downcase rescue 'blob' }()} # NLS_DATE_FORMAT independent TIMESTAMP support when :timestamp (value) # NLS_DATE_FORMAT independent DATE support when :date, :time, :datetime quote_date_with_to_date(value) when :raw quote_raw(value) when :string # NCHAR and NVARCHAR2 literals should be quoted with N'...'. # Read directly instance variable as otherwise migrations with table column default values are failing # as migrations pass ColumnDefinition object to this method. # Check if instance variable is defined to avoid warnings about accessing undefined instance variable. column.instance_variable_defined?('@nchar') && column.instance_variable_get('@nchar') ? 'N' << super : super else super end elsif value.acts_like?(:date) quote_date_with_to_date(value) elsif value.acts_like?(:time) value.to_i == value.to_f ? quote_date_with_to_date(value) : (value) else super end end |
#quote_column_name(name) ⇒ Object
QUOTING ==================================================
see: abstract/quoting.rb
535 536 537 538 539 540 541 542 543 544 545 546 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 535 def quote_column_name(name) #:nodoc: name = name.to_s @quoted_column_names[name] ||= begin # if only valid lowercase column characters in name if name =~ /\A[a-z][a-z_0-9\$#]*\Z/ "\"#{name.upcase}\"" else # remove double quotes which cannot be used inside quoted identifier "\"#{name.gsub('"', '')}\"" end end end |
#quote_column_name_or_expression(name) ⇒ Object
This method is used in add_index to identify either column name (which is quoted) or function based index (in which case function expression is not quoted)
550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 550 def quote_column_name_or_expression(name) #:nodoc: name = name.to_s case name # if only valid lowercase column characters in name when /^[a-z][a-z_0-9\$#]*$/ "\"#{name.upcase}\"" when /^[a-z][a-z_0-9\$#\-]*$/i "\"#{name}\"" # if other characters present then assume that it is expression # which should not be quoted else name end end |
#quote_database_link(name) ⇒ Object
Used only for quoting database links as the naming rules for links differ from the rules for column names. Specifically, link names may include periods.
568 569 570 571 572 573 574 575 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 568 def quote_database_link(name) case name when NONQUOTED_DATABASE_LINK %Q("#{name.upcase}") else name end end |
#quote_date_with_to_date(value) ⇒ Object
:nodoc:
654 655 656 657 658 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 654 def quote_date_with_to_date(value) #:nodoc: # should support that composite_primary_keys gem will pass date as string value = quoted_date(value) if value.acts_like?(:date) || value.acts_like?(:time) "TO_DATE('#{value}','YYYY-MM-DD HH24:MI:SS')" end |
#quote_raw(value) ⇒ Object
quote encoded raw value
668 669 670 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 668 def quote_raw(value) #:nodoc: "'#{self.class.encode_raw(value)}'" end |
#quote_string(s) ⇒ Object
:nodoc:
609 610 611 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 609 def quote_string(s) #:nodoc: s.gsub(/'/, "''") end |
#quote_table_name(name) ⇒ Object
:nodoc:
604 605 606 607 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 604 def quote_table_name(name) #:nodoc: name, link = name.to_s.split('@') @quoted_table_names[name] ||= [name.split('.').map{|n| quote_column_name(n)}.join('.'), quote_database_link(link)].compact.join('@') end |
#quote_timestamp_with_to_timestamp(value) ⇒ Object
:nodoc:
672 673 674 675 676 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 672 def (value) #:nodoc: # add up to 9 digits of fractional seconds to inserted time value = "#{quoted_date(value)}:#{("%.6f"%value.to_f).split('.')[1]}" if value.acts_like?(:time) "TO_TIMESTAMP('#{value}','YYYY-MM-DD HH24:MI:SS:FF6')" end |
#quoted_false ⇒ Object
:nodoc:
649 650 651 652 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 649 def quoted_false #:nodoc: return "'#{self.class.boolean_to_string(false)}'" if emulate_booleans_from_strings "0" end |
#quoted_true ⇒ Object
:nodoc:
644 645 646 647 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 644 def quoted_true #:nodoc: return "'#{self.class.boolean_to_string(true)}'" if emulate_booleans_from_strings "1" end |
#raw_connection ⇒ Object
return raw OCI8 or JDBC connection
718 719 720 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 718 def raw_connection @connection.raw_connection end |
#reconnect! ⇒ Object
Reconnects to the database.
734 735 736 737 738 739 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 734 def reconnect! #:nodoc: super @connection.reset! rescue OracleEnhancedConnectionException => e @logger.warn "#{adapter_name} automatic reconnection failed: #{e.}" if @logger end |
#reset! ⇒ Object
741 742 743 744 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 741 def reset! clear_cache! super end |
#reset_pk_sequence!(table_name, primary_key = nil, sequence_name = nil) ⇒ Object
:nodoc:
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 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 787 def reset_pk_sequence!(table_name, primary_key = nil, sequence_name = nil) #:nodoc: return nil unless table_exists?(table_name) unless primary_key and sequence_name # *Note*: Only primary key is implemented - sequence will be nil. primary_key, sequence_name = pk_and_sequence_for(table_name) # TODO This sequence_name implemantation is just enough # to satisty fixures. To get correct sequence_name always # pk_and_sequence_for method needs some work. begin sequence_name = table_name.classify.constantize.sequence_name rescue sequence_name = default_sequence_name(table_name) end end if @logger && primary_key && !sequence_name @logger.warn "#{table_name} has primary key #{primary_key} with no default sequence" end if primary_key && sequence_name new_start_value = select_value(" select NVL(max(#{quote_column_name(primary_key)}),0) + 1 from #{quote_table_name(table_name)} ", new_start_value) execute ("DROP SEQUENCE #{quote_table_name(sequence_name)}") execute ("CREATE SEQUENCE #{quote_table_name(sequence_name)} START WITH #{new_start_value}") end end |
#schema_creation ⇒ Object
231 232 233 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 231 def schema_creation OracleEnhanced::SchemaCreation.new self end |
#sequence_name_length ⇒ Object
the maximum length of a sequence name
520 521 522 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 520 def sequence_name_length IDENTIFIER_MAX_LENGTH end |
#set_type_for_columns(table_name, column_type, *args) ⇒ Object
set explicit type for specified table columns
975 976 977 978 979 980 981 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 975 def set_type_for_columns(table_name, column_type, *args) #:nodoc: @@table_column_type ||= {} @@table_column_type[table_name] ||= {} args.each do |col| @@table_column_type[table_name][col.to_s.downcase] = column_type end end |
#string_to_date_format ⇒ Object
:singleton-method: Specify non-default date format that should be used when assigning string values to :date columns, e.g.:
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.string_to_date_format = “%d.%m.%Y”
351 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 351 cattr_accessor :string_to_date_format |
#string_to_time_format ⇒ Object
:singleton-method: Specify non-default time format that should be used when assigning string values to :datetime columns, e.g.:
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.string_to_time_format = “%d.%m.%Y %H:%M:%S”
359 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 359 cattr_accessor :string_to_time_format |
#supports_foreign_keys? ⇒ Boolean
429 430 431 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 429 def supports_foreign_keys? true end |
#supports_migrations? ⇒ Boolean
:nodoc:
413 414 415 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 413 def supports_migrations? #:nodoc: true end |
#supports_primary_key? ⇒ Boolean
:nodoc:
417 418 419 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 417 def supports_primary_key? #:nodoc: true end |
#supports_savepoints? ⇒ Boolean
:nodoc:
421 422 423 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 421 def supports_savepoints? #:nodoc: true end |
#supports_transaction_isolation? ⇒ Boolean
:nodoc:
425 426 427 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 425 def supports_transaction_isolation? #:nodoc: true end |
#supports_views? ⇒ Boolean
433 434 435 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 433 def supports_views? true end |
#table_alias_length ⇒ Object
:nodoc:
490 491 492 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 490 def table_alias_length #:nodoc: IDENTIFIER_MAX_LENGTH end |
#table_exists?(table_name) ⇒ Boolean
Will return true if database object exists (to be able to use also views and synonyms for ActiveRecord models)
869 870 871 872 873 874 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 869 def table_exists?(table_name) (owner, table_name, db_link) = @connection.describe(table_name) true rescue false end |
#table_name_length ⇒ Object
the maximum length of a table name
495 496 497 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 495 def table_name_length IDENTIFIER_MAX_LENGTH end |
#tables(name = nil) ⇒ Object
:nodoc:
862 863 864 865 866 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 862 def tables(name = nil) #:nodoc: select_values( "SELECT DECODE(table_name, UPPER(table_name), LOWER(table_name), table_name) FROM all_tables WHERE owner = SYS_CONTEXT('userenv', 'current_schema') AND secondary = 'N'", name) end |
#temporary_table?(table_name) ⇒ Boolean
:nodoc:
1248 1249 1250 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 1248 def temporary_table?(table_name) #:nodoc: select_value("SELECT temporary FROM user_tables WHERE table_name = '#{table_name.upcase}'") == 'Y' end |
#type_cast(value, column) ⇒ Object
Cast a value
to a type that the database understands.
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 679 def type_cast(value, column) if column && column.cast_type.is_a?(Type::Serialized) super else case value when true, false if emulate_booleans_from_strings || column && column.type == :string self.class.boolean_to_string(value) else value ? 1 : 0 end when Date, Time if value.acts_like?(:time) zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal value.respond_to?(zone_conversion_method) ? value.send(zone_conversion_method) : value else value end else super end end end |
#write_lobs(table_name, klass, attributes, columns) ⇒ Object
Writes LOB values from attributes for specified columns
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 |
# File 'lib/active_record/connection_adapters/oracle_enhanced_adapter.rb', line 817 def write_lobs(table_name, klass, attributes, columns) #:nodoc: # is class with composite primary key> is_with_cpk = klass.respond_to?(:composite?) && klass.composite? if is_with_cpk id = klass.primary_key.map {|pk| attributes[pk.to_s] } else id = quote(attributes[klass.primary_key]) end columns.each do |col| value = attributes[col.name] # changed sequence of next two lines - should check if value is nil before converting to yaml next if value.nil? || (value == '') value = value.to_yaml if col.cast_type.is_a?(Type::Serialized) # klass.serialized_attributes[col.name] uncached do sql = is_with_cpk ? "SELECT #{quote_column_name(col.name)} FROM #{quote_table_name(table_name)} WHERE #{klass.composite_where_clause(id)} FOR UPDATE" : "SELECT #{quote_column_name(col.name)} FROM #{quote_table_name(table_name)} WHERE #{quote_column_name(klass.primary_key)} = #{id} FOR UPDATE" unless lob_record = select_one(sql, 'Writable Large Object') raise ActiveRecord::RecordNotFound, "statement #{sql} returned no rows" end lob = lob_record[col.name] @connection.write_lob(lob, value.to_s, col.type == :binary) end end end |