diff --git a/.gitignore b/.gitignore index ff20d0deb..27b05d95f 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ debug.log .DS_Store pkg/ doc/ +db/ *.gem .bundle Gemfile.lock diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..55040ad53 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,5 @@ +AllCops: + TargetRubyVersion: 2.5 + +Style/StringLiterals: + EnforcedStyle: double_quotes diff --git a/Gemfile b/Gemfile index 2b094d3cc..a5b35593e 100644 --- a/Gemfile +++ b/Gemfile @@ -61,3 +61,7 @@ group :guard do gem "guard-minitest" gem "terminal-notifier-guard" if RbConfig::CONFIG["host_os"] =~ /darwin/ end + +group :rubocop do + gem "rubocop", require: false +end diff --git a/Guardfile b/Guardfile index 2f8a80820..ab781a114 100644 --- a/Guardfile +++ b/Guardfile @@ -1,29 +1,30 @@ +# frozen_string_literal: true -require_relative 'test/support/paths_sqlserver' +require_relative "test/support/paths_sqlserver" clearing :on notification :terminal_notifier if defined?(TerminalNotifier) ignore %r{debug\.log} -ar_lib = File.join ARTest::SQLServer.root_activerecord, 'lib' -ar_test = File.join ARTest::SQLServer.root_activerecord, 'test' +ar_lib = File.join ARTest::SQLServer.root_activerecord, "lib" +ar_test = File.join ARTest::SQLServer.root_activerecord, "test" guard :minitest, { all_on_start: false, autorun: false, - include: ['lib', 'test', ar_lib, ar_test], - test_folders: ['test'], + include: ["lib", "test", ar_lib, ar_test], + test_folders: ["test"], test_file_patterns: ["*_test.rb", "*_test_sqlserver.rb"] } do # Our project watchers. - if ENV['TEST_FILES'] - ENV['TEST_FILES'].split(',').map(&:strip).each do |file| + if ENV["TEST_FILES"] + ENV["TEST_FILES"].split(",").map(&:strip).each do |file| watch(%r{.*}) { file } end else watch(%r{^test/cases/\w+_test_sqlserver\.rb$}) watch(%r{^test/cases/coerced_tests\.rb$}) { "test/cases/coerced_tests.rb" } watch(%r{^lib/active_record/connection_adapters/sqlserver/([^/]+)\.rb$}) { |m| "test/cases/#{m[1]}_test_sqlserver.rb" } - watch(%r{^test/cases/helper_sqlserver\.rb$}) { 'test' } + watch(%r{^test/cases/helper_sqlserver\.rb$}) { "test" } end end diff --git a/Rakefile b/Rakefile index 1477ac6f5..d8174b1b2 100644 --- a/Rakefile +++ b/Rakefile @@ -1,11 +1,11 @@ # frozen_string_literal: true -require 'bundler/gem_tasks' -require 'rake/testtask' -require_relative 'test/support/paths_sqlserver' -require_relative 'test/support/rake_helpers' +require "bundler/gem_tasks" +require "rake/testtask" +require_relative "test/support/paths_sqlserver" +require_relative "test/support/rake_helpers" -task test: ['test:dblib'] +task test: ["test:dblib"] task default: [:test] namespace :test do @@ -15,25 +15,25 @@ namespace :test do Rake::TestTask.new(mode) do |t| t.libs = ARTest::SQLServer.test_load_paths t.test_files = test_files - t.warning = !!ENV['WARNING'] + t.warning = !!ENV["WARNING"] t.verbose = false end end - task 'dblib:env' do - ENV['ARCONN'] = 'dblib' + task "dblib:env" do + ENV["ARCONN"] = "dblib" end end -task 'test:dblib' => 'test:dblib:env' +task "test:dblib" => "test:dblib:env" namespace :profile do - ['dblib'].each do |mode| + ["dblib"].each do |mode| namespace mode.to_sym do - Dir.glob('test/profile/*_profile_case.rb').sort.each do |test_file| - profile_case = File.basename(test_file).sub('_profile_case.rb', '') + Dir.glob("test/profile/*_profile_case.rb").sort.each do |test_file| + profile_case = File.basename(test_file).sub("_profile_case.rb", "") Rake::TestTask.new(profile_case) do |t| t.libs = ARTest::SQLServer.test_load_paths t.test_files = [test_file] diff --git a/lib/active_record/connection_adapters/sqlserver/core_ext/attribute_methods.rb b/lib/active_record/connection_adapters/sqlserver/core_ext/attribute_methods.rb index 815da2914..715472c81 100644 --- a/lib/active_record/connection_adapters/sqlserver/core_ext/attribute_methods.rb +++ b/lib/active_record/connection_adapters/sqlserver/core_ext/attribute_methods.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'active_record/attribute_methods' +require "active_record/attribute_methods" module ActiveRecord module ConnectionAdapters diff --git a/lib/active_record/connection_adapters/sqlserver/core_ext/calculations.rb b/lib/active_record/connection_adapters/sqlserver/core_ext/calculations.rb index c17d77876..dc6e73360 100644 --- a/lib/active_record/connection_adapters/sqlserver/core_ext/calculations.rb +++ b/lib/active_record/connection_adapters/sqlserver/core_ext/calculations.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'active_record/relation' -require 'active_record/version' +require "active_record/relation" +require "active_record/version" module ActiveRecord module ConnectionAdapters diff --git a/lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb b/lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb index 76e1eb7a8..b71e7a0ad 100644 --- a/lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb +++ b/lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb @@ -6,7 +6,7 @@ module SQLServer module CoreExt module Explain - SQLSERVER_STATEMENT_PREFIX = 'EXEC sp_executesql ' + SQLSERVER_STATEMENT_PREFIX = "EXEC sp_executesql " SQLSERVER_STATEMENT_REGEXP = /N'(.+)', N'(.+)', (.+)/ def exec_explain(queries) diff --git a/lib/active_record/connection_adapters/sqlserver/core_ext/finder_methods.rb b/lib/active_record/connection_adapters/sqlserver/core_ext/finder_methods.rb index 7db8aaecc..8a37a27b6 100644 --- a/lib/active_record/connection_adapters/sqlserver/core_ext/finder_methods.rb +++ b/lib/active_record/connection_adapters/sqlserver/core_ext/finder_methods.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'active_record/relation' -require 'active_record/version' +require "active_record/relation" +require "active_record/version" module ActiveRecord module ConnectionAdapters diff --git a/lib/active_record/connection_adapters/sqlserver/core_ext/query_methods.rb b/lib/active_record/connection_adapters/sqlserver/core_ext/query_methods.rb index 31ed4fa79..ae89a12a0 100644 --- a/lib/active_record/connection_adapters/sqlserver/core_ext/query_methods.rb +++ b/lib/active_record/connection_adapters/sqlserver/core_ext/query_methods.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'active_record/relation' -require 'active_record/version' +require "active_record/relation" +require "active_record/version" module ActiveRecord module ConnectionAdapters diff --git a/lib/active_record/connection_adapters/sqlserver/database_statements.rb b/lib/active_record/connection_adapters/sqlserver/database_statements.rb index b7bf24b18..98a2b9efe 100644 --- a/lib/active_record/connection_adapters/sqlserver/database_statements.rb +++ b/lib/active_record/connection_adapters/sqlserver/database_statements.rb @@ -25,7 +25,7 @@ def execute(sql, name = nil) end end - def exec_query(sql, name = 'SQL', binds = [], prepare: false) + def exec_query(sql, name = "SQL", binds = [], prepare: false) if preventing_writes? && write_query?(sql) raise ActiveRecord::ReadOnlyError, "Write query attempted while in readonly mode: #{sql}" end @@ -44,17 +44,17 @@ def exec_insert(sql, name = nil, binds = [], pk = nil, _sequence_name = nil) end def exec_delete(sql, name, binds) - sql = sql.dup << '; SELECT @@ROWCOUNT AS AffectedRows' + sql = sql.dup << "; SELECT @@ROWCOUNT AS AffectedRows" super(sql, name, binds).rows.first.first end def exec_update(sql, name, binds) - sql = sql.dup << '; SELECT @@ROWCOUNT AS AffectedRows' + sql = sql.dup << "; SELECT @@ROWCOUNT AS AffectedRows" super(sql, name, binds).rows.first.first end def begin_db_transaction - do_execute 'BEGIN TRANSACTION' + do_execute "BEGIN TRANSACTION" end def transaction_isolation_levels @@ -71,11 +71,11 @@ def set_transaction_isolation_level(isolation_level) end def commit_db_transaction - do_execute 'COMMIT TRANSACTION' + do_execute "COMMIT TRANSACTION" end def exec_rollback_db_transaction - do_execute 'IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION' + do_execute "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION" end include Savepoints @@ -159,9 +159,9 @@ def execute_procedure(proc_name, *variables) variables.first.map { |k, v| "@#{k} = #{quote(v)}" } else variables.map { |v| quote(v) } - end.join(', ') + end.join(", ") sql = "EXEC #{proc_name} #{vars}".strip - name = 'Execute Procedure' + name = "Execute Procedure" log(sql, name) do case @connection_options[:mode] when :dblib @@ -192,14 +192,14 @@ def use_database(database = nil) def user_options return {} if sqlserver_azure? - rows = select_rows('DBCC USEROPTIONS WITH NO_INFOMSGS', 'SCHEMA') + rows = select_rows("DBCC USEROPTIONS WITH NO_INFOMSGS", "SCHEMA") rows = rows.first if rows.size == 2 && rows.last.empty? rows.reduce(HashWithIndifferentAccess.new) do |values, row| if row.instance_of? Hash - set_option = row.values[0].gsub(/\s+/, '_') + set_option = row.values[0].gsub(/\s+/, "_") user_value = row.values[1] elsif row.instance_of? Array - set_option = row[0].gsub(/\s+/, '_') + set_option = row[0].gsub(/\s+/, "_") user_value = row[1] end values[set_option] = user_value @@ -209,9 +209,9 @@ def user_options def user_options_dateformat if sqlserver_azure? - select_value 'SELECT [dateformat] FROM [sys].[syslanguages] WHERE [langid] = @@LANGID', 'SCHEMA' + select_value "SELECT [dateformat] FROM [sys].[syslanguages] WHERE [langid] = @@LANGID", "SCHEMA" else - user_options['dateformat'] + user_options["dateformat"] end end @@ -226,26 +226,26 @@ def user_options_isolation_level WHEN 5 THEN 'SNAPSHOT' END AS [isolation_level] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID).squish - select_value sql, 'SCHEMA' + select_value sql, "SCHEMA" else - user_options['isolation_level'] + user_options["isolation_level"] end end def user_options_language if sqlserver_azure? - select_value 'SELECT @@LANGUAGE AS [language]', 'SCHEMA' + select_value "SELECT @@LANGUAGE AS [language]", "SCHEMA" else - user_options['language'] + user_options["language"] end end def newid_function - select_value 'SELECT NEWID()' + select_value "SELECT NEWID()" end def newsequentialid_function - select_value 'SELECT NEWSEQUENTIALID()' + select_value "SELECT NEWSEQUENTIALID()" end @@ -263,7 +263,7 @@ def sql_for_insert(sql, pk, binds) exclude_output_inserted = exclude_output_inserted_table_name?(table_name, sql) if exclude_output_inserted - id_sql_type = exclude_output_inserted.is_a?(TrueClass) ? 'bigint' : exclude_output_inserted + id_sql_type = exclude_output_inserted.is_a?(TrueClass) ? "bigint" : exclude_output_inserted <<~SQL.squish DECLARE @ssaIdInsertTable table (#{quoted_pk} #{id_sql_type}); #{sql.dup.insert sql.index(/ (DEFAULT )?VALUES/), " OUTPUT INSERTED.#{quoted_pk} INTO @ssaIdInsertTable"} @@ -288,7 +288,7 @@ def set_identity_insert(table_name, enable = true) # === SQLServer Specific (Executing) ============================ # - def do_execute(sql, name = 'SQL') + def do_execute(sql, name = "SQL") materialize_transactions log(sql, name) { raw_connection_do(sql) } @@ -318,9 +318,9 @@ def sp_executesql_sql_type(attr) return attr.type.sqlserver_type if attr.type.respond_to?(:sqlserver_type) case value = attr.value_for_database when Numeric - value > 2_147_483_647 ? 'bigint'.freeze : 'int'.freeze + value > 2_147_483_647 ? "bigint".freeze : "int".freeze else - 'nvarchar(max)'.freeze + "nvarchar(max)".freeze end end @@ -335,14 +335,14 @@ def sp_executesql_sql_param(attr) end def sp_executesql_sql(sql, types, params, name) - if name == 'EXPLAIN' + if name == "EXPLAIN" params.each.with_index do |param, index| substitute_at_finder = /(@#{index})(?=(?:[^']|'[^']*')*$)/ # Finds unquoted @n values. sql = sql.sub substitute_at_finder, param.to_s end else - types = quote(types.join(', ')) - params = params.map.with_index{ |p, i| "@#{i} = #{p}" }.join(', ') # Only p is needed, but with @i helps explain regexp. + types = quote(types.join(", ")) + params = params.map.with_index{ |p, i| "@#{i} = #{p}" }.join(", ") # Only p is needed, but with @i helps explain regexp. sql = "EXEC sp_executesql #{quote(sql)}" sql += ", #{types}, #{params}" unless params.empty? end @@ -357,7 +357,7 @@ def raw_connection_do(sql) # TinyTDS returns false instead of raising an exception if connection fails. # Getting around this by raising an exception ourselves while this PR # https://github.com/rails-sqlserver/tiny_tds/pull/469 is not released. - raise TinyTds::Error, 'failed to execute statement' if result.is_a?(FalseClass) + raise TinyTds::Error, "failed to execute statement" if result.is_a?(FalseClass) result.do end @@ -407,7 +407,7 @@ def identity_columns(table_name) # === SQLServer Specific (Selecting) ============================ # - def raw_select(sql, name = 'SQL', binds = [], options = {}) + def raw_select(sql, name = "SQL", binds = [], options = {}) log(sql, name, binds) { _raw_select(sql, options) } end diff --git a/lib/active_record/connection_adapters/sqlserver/database_tasks.rb b/lib/active_record/connection_adapters/sqlserver/database_tasks.rb index 687773806..3e6c47fdb 100644 --- a/lib/active_record/connection_adapters/sqlserver/database_tasks.rb +++ b/lib/active_record/connection_adapters/sqlserver/database_tasks.rb @@ -19,7 +19,7 @@ def drop_database(database) end def current_database - select_value 'SELECT DB_NAME()' + select_value "SELECT DB_NAME()" end def charset @@ -41,7 +41,7 @@ def create_database_options(options={}) v.present? }.slice(*keys).map { |k,v| "#{k.to_s.upcase} #{v}" - }.join(' ') + }.join(" ") options end @@ -56,7 +56,7 @@ def create_database_edition_options(options={}) v.present? }.slice(*keys).map { |k,v| "#{k.to_s.upcase} = #{v}" - }.join(', ') + }.join(", ") edition_options = "( #{edition_options} )" if edition_options.present? edition_options end diff --git a/lib/active_record/connection_adapters/sqlserver/quoting.rb b/lib/active_record/connection_adapters/sqlserver/quoting.rb index ad11c4900..89583bbfb 100644 --- a/lib/active_record/connection_adapters/sqlserver/quoting.rb +++ b/lib/active_record/connection_adapters/sqlserver/quoting.rb @@ -5,9 +5,9 @@ module ConnectionAdapters module SQLServer module Quoting - QUOTED_TRUE = '1'.freeze - QUOTED_FALSE = '0'.freeze - QUOTED_STRING_PREFIX = 'N'.freeze + QUOTED_TRUE = "1".freeze + QUOTED_FALSE = "0".freeze + QUOTED_STRING_PREFIX = "N".freeze def fetch_type_metadata(sql_type, sqlserver_options = {}) cast_type = lookup_cast_type(sql_type) diff --git a/lib/active_record/connection_adapters/sqlserver/schema_dumper.rb b/lib/active_record/connection_adapters/sqlserver/schema_dumper.rb index bd5d746c9..198bc293a 100644 --- a/lib/active_record/connection_adapters/sqlserver/schema_dumper.rb +++ b/lib/active_record/connection_adapters/sqlserver/schema_dumper.rb @@ -6,11 +6,11 @@ module SQLServer class SchemaDumper < ConnectionAdapters::SchemaDumper SQLSEVER_NO_LIMIT_TYPES = [ - 'text', - 'ntext', - 'varchar(max)', - 'nvarchar(max)', - 'varbinary(max)' + "text", + "ntext", + "varchar(max)", + "nvarchar(max)", + "varbinary(max)" ].freeze private diff --git a/lib/active_record/connection_adapters/sqlserver/schema_statements.rb b/lib/active_record/connection_adapters/sqlserver/schema_statements.rb index cc0f87e1a..e50b21217 100644 --- a/lib/active_record/connection_adapters/sqlserver/schema_statements.rb +++ b/lib/active_record/connection_adapters/sqlserver/schema_statements.rb @@ -19,11 +19,11 @@ def drop_table(table_name, **options) # Mimic CASCADE option as best we can. if options[:force] == :cascade execute_procedure(:sp_fkeys, pktable_name: table_name).each do |fkdata| - fktable = fkdata['FKTABLE_NAME'] - fkcolmn = fkdata['FKCOLUMN_NAME'] - pktable = fkdata['PKTABLE_NAME'] - pkcolmn = fkdata['PKCOLUMN_NAME'] - remove_foreign_key fktable, name: fkdata['FK_NAME'] + fktable = fkdata["FKTABLE_NAME"] + fkcolmn = fkdata["FKCOLUMN_NAME"] + pktable = fkdata["PKTABLE_NAME"] + pkcolmn = fkdata["PKCOLUMN_NAME"] + remove_foreign_key fktable, name: fkdata["FK_NAME"] do_execute "DELETE FROM #{quote_table_name(fktable)} WHERE #{quote_column_name(fkcolmn)} IN ( SELECT #{quote_column_name(pkcolmn)} FROM #{quote_table_name(pktable)} )" end end @@ -49,11 +49,11 @@ def indexes(table_name) orders = {} columns = [] - index[:index_keys].split(',').each do |column| + index[:index_keys].split(",").each do |column| column.strip! - if column.ends_with?('(-)') - column.gsub! '(-)', '' + if column.ends_with?("(-)") + column.gsub! "(-)", "" orders[column] = :desc end @@ -117,12 +117,12 @@ def primary_keys_select(table_name) AND KCU.TABLE_SCHEMA = #{identifier.schema.blank? ? 'schema_name()' : (prepared_statements ? '@1' : quote(identifier.schema))} AND TC.CONSTRAINT_TYPE = N'PRIMARY KEY' ORDER BY KCU.ORDINAL_POSITION ASC - }.gsub(/[[:space:]]/, ' ') + }.gsub(/[[:space:]]/, " ") binds = [] nv128 = SQLServer::Type::UnicodeVarchar.new limit: 128 - binds << Relation::QueryAttribute.new('TABLE_NAME', identifier.object, nv128) - binds << Relation::QueryAttribute.new('TABLE_SCHEMA', identifier.schema, nv128) unless identifier.schema.blank? - sp_executesql(sql, 'SCHEMA', binds).map { |r| r['name'] } + binds << Relation::QueryAttribute.new("TABLE_NAME", identifier.object, nv128) + binds << Relation::QueryAttribute.new("TABLE_SCHEMA", identifier.schema, nv128) unless identifier.schema.blank? + sp_executesql(sql, "SCHEMA", binds).map { |r| r["name"] } end def rename_table(table_name, new_name) @@ -131,7 +131,7 @@ def rename_table(table_name, new_name) end def remove_column(table_name, column_name, type = nil, options = {}) - raise ArgumentError.new('You must specify at least one column name. Example: remove_column(:people, :first_name)') if column_name.is_a? Array + raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_name.is_a? Array remove_check_constraints(table_name, column_name) remove_default_constraint(table_name, column_name) remove_indexes(table_name, column_name) @@ -155,7 +155,7 @@ def change_column(table_name, column_name, type, options = {}) end sql_commands << "UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote_default_expression(options[:default], column_object)} WHERE #{quote_column_name(column_name)} IS NULL" if !options[:null].nil? && options[:null] == false && !options[:default].nil? alter_command = "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, limit: options[:limit], precision: options[:precision], scale: options[:scale])}" - alter_command += ' NOT NULL' if !options[:null].nil? && options[:null] == false + alter_command += " NOT NULL" if !options[:null].nil? && options[:null] == false sql_commands << alter_command if without_constraints default = quote_default_expression(default, column_object || column_for(table_name, column_name)) @@ -182,7 +182,7 @@ def change_column_default(table_name, column_name, default_or_changes) def rename_column(table_name, column_name, new_column_name) clear_cache! identifier = SQLServer::Utils.extract_identifiers("#{table_name}.#{column_name}") - execute_procedure :sp_rename, identifier.quoted, new_column_name, 'COLUMN' + execute_procedure :sp_rename, identifier.quoted, new_column_name, "COLUMN" rename_column_indexes(table_name, column_name, new_column_name) clear_cache! end @@ -190,7 +190,7 @@ def rename_column(table_name, column_name, new_column_name) def rename_index(table_name, old_name, new_name) raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters" if new_name.length > allowed_index_name_length identifier = SQLServer::Utils.extract_identifiers("#{table_name}.#{old_name}") - execute_procedure :sp_rename, identifier.quoted, new_name, 'INDEX' + execute_procedure :sp_rename, identifier.quoted, new_name, "INDEX" end def remove_index!(table_name, index_name) @@ -202,13 +202,13 @@ def foreign_keys(table_name) fk_info = execute_procedure :sp_fkeys, nil, identifier.schema, nil, identifier.object, identifier.schema fk_info.map do |row| from_table = identifier.object - to_table = row['PKTABLE_NAME'] + to_table = row["PKTABLE_NAME"] options = { - name: row['FK_NAME'], - column: row['FKCOLUMN_NAME'], - primary_key: row['PKCOLUMN_NAME'], - on_update: extract_foreign_key_action('update', row['FK_NAME']), - on_delete: extract_foreign_key_action('delete', row['FK_NAME']) + name: row["FK_NAME"], + column: row["FKCOLUMN_NAME"], + primary_key: row["PKCOLUMN_NAME"], + on_update: extract_foreign_key_action("update", row["FK_NAME"]), + on_delete: extract_foreign_key_action("delete", row["FK_NAME"]) } ForeignKeyDefinition.new from_table, to_table, options end @@ -216,8 +216,8 @@ def foreign_keys(table_name) def extract_foreign_key_action(action, fk_name) case select_value("SELECT #{action}_referential_action_desc FROM sys.foreign_keys WHERE name = '#{fk_name}'") - when 'CASCADE' then :cascade - when 'SET_NULL' then :nullify + when "CASCADE" then :cascade + when "SET_NULL" then :nullify end end @@ -225,15 +225,15 @@ def type_to_sql(type, limit: nil, precision: nil, scale: nil, **) type_limitable = %w(string integer float char nchar varchar nvarchar).include?(type.to_s) limit = nil unless type_limitable case type.to_s - when 'integer' + when "integer" case limit - when 1 then 'tinyint' - when 2 then 'smallint' - when 3..4, nil then 'integer' - when 5..8 then 'bigint' + when 1 then "tinyint" + when 2 then "smallint" + when 3..4, nil then "integer" + when 5..8 then "bigint" else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.") end - when 'datetime2' + when "datetime2" column_type_sql = super if precision if (0..7) === precision @@ -251,8 +251,8 @@ def type_to_sql(type, limit: nil, precision: nil, scale: nil, **) def columns_for_distinct(columns, orders) order_columns = orders.reject(&:blank?).map{ |s| s = s.to_sql unless s.is_a?(String) - s.gsub(/\s+(?:ASC|DESC)\b/i, '') - .gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, '') + s.gsub(/\s+(?:ASC|DESC)\b/i, "") + .gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, "") }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" } (order_columns << super).join(", ") @@ -270,7 +270,7 @@ def change_column_null(table_name, column_name, allow_null, default = nil) do_execute("UPDATE #{table_id} SET #{column_id}=#{quote(default)} WHERE #{column_id} IS NULL") end sql = "ALTER TABLE #{table_id} ALTER COLUMN #{column_id} #{type_to_sql column.type, limit: column.limit, precision: column.precision, scale: column.scale}" - sql += ' NOT NULL' if !allow_null.nil? && allow_null == false + sql += " NOT NULL" if !allow_null.nil? && allow_null == false do_execute sql end @@ -282,10 +282,10 @@ def create_schema_dumper(options) def data_source_sql(name = nil, type: nil) scope = quoted_scope name, type: type - table_name = lowercase_schema_reflection_sql 'TABLE_NAME' + table_name = lowercase_schema_reflection_sql "TABLE_NAME" sql = "SELECT #{table_name}" - sql += ' FROM INFORMATION_SCHEMA.TABLES WITH (NOLOCK)' - sql += ' WHERE TABLE_CATALOG = DB_NAME()' + sql += " FROM INFORMATION_SCHEMA.TABLES WITH (NOLOCK)" + sql += " WHERE TABLE_CATALOG = DB_NAME()" sql += " AND TABLE_SCHEMA = #{quote(scope[:schema])}" sql += " AND TABLE_NAME = #{quote(scope[:name])}" if scope[:name] sql += " AND TABLE_TYPE = #{quote(scope[:type])}" if scope[:type] @@ -296,7 +296,7 @@ def data_source_sql(name = nil, type: nil) def quoted_scope(name = nil, type: nil) identifier = SQLServer::Utils.extract_identifiers(name) {}.tap do |scope| - scope[:schema] = identifier.schema || 'dbo' + scope[:schema] = identifier.schema || "dbo" scope[:name] = identifier.object if identifier.object scope[:type] = type if type end @@ -306,37 +306,37 @@ def quoted_scope(name = nil, type: nil) def initialize_native_database_types { - primary_key: 'bigint NOT NULL IDENTITY(1,1) PRIMARY KEY', - primary_key_nonclustered: 'int NOT NULL IDENTITY(1,1) PRIMARY KEY NONCLUSTERED', - integer: { name: 'int', limit: 4 }, - bigint: { name: 'bigint' }, - boolean: { name: 'bit' }, - decimal: { name: 'decimal' }, - money: { name: 'money' }, - smallmoney: { name: 'smallmoney' }, - float: { name: 'float' }, - real: { name: 'real' }, - date: { name: 'date' }, - datetime: { name: 'datetime' }, - datetime2: { name: 'datetime2' }, - datetimeoffset: { name: 'datetimeoffset' }, - smalldatetime: { name: 'smalldatetime' }, - timestamp: { name: 'datetime' }, - time: { name: 'time' }, - char: { name: 'char' }, - varchar: { name: 'varchar', limit: 8000 }, - varchar_max: { name: 'varchar(max)' }, - text_basic: { name: 'text' }, - nchar: { name: 'nchar' }, - string: { name: 'nvarchar', limit: 4000 }, - text: { name: 'nvarchar(max)' }, - ntext: { name: 'ntext' }, - binary_basic: { name: 'binary' }, - varbinary: { name: 'varbinary', limit: 8000 }, - binary: { name: 'varbinary(max)' }, - uuid: { name: 'uniqueidentifier' }, - ss_timestamp: { name: 'timestamp' }, - json: { name: 'nvarchar(max)' } + primary_key: "bigint NOT NULL IDENTITY(1,1) PRIMARY KEY", + primary_key_nonclustered: "int NOT NULL IDENTITY(1,1) PRIMARY KEY NONCLUSTERED", + integer: { name: "int", limit: 4 }, + bigint: { name: "bigint" }, + boolean: { name: "bit" }, + decimal: { name: "decimal" }, + money: { name: "money" }, + smallmoney: { name: "smallmoney" }, + float: { name: "float" }, + real: { name: "real" }, + date: { name: "date" }, + datetime: { name: "datetime" }, + datetime2: { name: "datetime2" }, + datetimeoffset: { name: "datetimeoffset" }, + smalldatetime: { name: "smalldatetime" }, + timestamp: { name: "datetime" }, + time: { name: "time" }, + char: { name: "char" }, + varchar: { name: "varchar", limit: 8000 }, + varchar_max: { name: "varchar(max)" }, + text_basic: { name: "text" }, + nchar: { name: "nchar" }, + string: { name: "nvarchar", limit: 4000 }, + text: { name: "nvarchar(max)" }, + ntext: { name: "ntext" }, + binary_basic: { name: "binary" }, + varbinary: { name: "varbinary", limit: 8000 }, + binary: { name: "varbinary(max)" }, + uuid: { name: "uniqueidentifier" }, + ss_timestamp: { name: "timestamp" }, + json: { name: "nvarchar(max)" } } end @@ -350,9 +350,9 @@ def column_definitions(table_name) binds = [] nv128 = SQLServer::Type::UnicodeVarchar.new limit: 128 - binds << Relation::QueryAttribute.new('TABLE_NAME', identifier.object, nv128) - binds << Relation::QueryAttribute.new('TABLE_SCHEMA', identifier.schema, nv128) unless identifier.schema.blank? - results = sp_executesql(sql, 'SCHEMA', binds) + binds << Relation::QueryAttribute.new("TABLE_NAME", identifier.object, nv128) + binds << Relation::QueryAttribute.new("TABLE_SCHEMA", identifier.schema, nv128) unless identifier.schema.blank? + results = sp_executesql(sql, "SCHEMA", binds) results.map do |ci| ci = ci.symbolize_keys ci[:_type] = ci[:type] @@ -383,7 +383,7 @@ def column_definitions(table_name) WHERE c.TABLE_NAME = '#{view_tblnm}' AND c.COLUMN_NAME = '#{views_real_column_name(table_name, ci[:name])}' - }.squish, 'SCHEMA' + }.squish, "SCHEMA" end case default when nil @@ -402,7 +402,7 @@ def column_definitions(table_name) else ci[:type] end value = default.match(/\A\((.*)\)\Z/m)[1] - value = select_value("SELECT CAST(#{value} AS #{type}) AS value", 'SCHEMA') + value = select_value("SELECT CAST(#{value} AS #{type}) AS value", "SCHEMA") [value, nil] end end @@ -415,11 +415,11 @@ def column_definitions(table_name) end def column_definitions_sql(database, identifier) - object_name = prepared_statements ? '@0' : quote(identifier.object) + object_name = prepared_statements ? "@0" : quote(identifier.object) schema_name = if identifier.schema.blank? - 'schema_name()' + "schema_name()" else - prepared_statements ? '@1' : quote(identifier.schema) + prepared_statements ? "@1" : quote(identifier.schema) end %{ @@ -478,11 +478,11 @@ def column_definitions_sql(database, identifier) AND s.name = #{schema_name} ORDER BY c.column_id - }.gsub(/[ \t\r\n]+/, ' ').strip + }.gsub(/[ \t\r\n]+/, " ").strip end def remove_check_constraints(table_name, column_name) - constraints = select_values "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '#{quote_string(table_name)}' and COLUMN_NAME = '#{quote_string(column_name)}'", 'SCHEMA' + constraints = select_values "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '#{quote_string(table_name)}' and COLUMN_NAME = '#{quote_string(column_name)}'", "SCHEMA" constraints.each do |constraint| do_execute "ALTER TABLE #{quote_table_name(table_name)} DROP CONSTRAINT #{quote_column_name(constraint)}" end @@ -490,8 +490,8 @@ def remove_check_constraints(table_name, column_name) def remove_default_constraint(table_name, column_name) # If their are foreign keys in this table, we could still get back a 2D array, so flatten just in case. - execute_procedure(:sp_helpconstraint, table_name, 'nomsg').flatten.select do |row| - row['constraint_type'] == "DEFAULT on column #{column_name}" + execute_procedure(:sp_helpconstraint, table_name, "nomsg").flatten.select do |row| + row["constraint_type"] == "DEFAULT on column #{column_name}" end.each do |row| do_execute "ALTER TABLE #{quote_table_name(table_name)} DROP CONSTRAINT #{row['constraint_name']}" end @@ -528,19 +528,19 @@ def lowercase_schema_reflection_sql(node) def view_table_name(table_name) view_info = view_information(table_name) - view_info ? get_table_name(view_info['VIEW_DEFINITION']) : table_name + view_info ? get_table_name(view_info["VIEW_DEFINITION"]) : table_name end def view_information(table_name) @view_information ||= {} @view_information[table_name] ||= begin identifier = SQLServer::Utils.extract_identifiers(table_name) - view_info = select_one "SELECT * FROM INFORMATION_SCHEMA.VIEWS WITH (NOLOCK) WHERE TABLE_NAME = #{quote(identifier.object)}", 'SCHEMA' + view_info = select_one "SELECT * FROM INFORMATION_SCHEMA.VIEWS WITH (NOLOCK) WHERE TABLE_NAME = #{quote(identifier.object)}", "SCHEMA" if view_info view_info = view_info.with_indifferent_access if view_info[:VIEW_DEFINITION].blank? || view_info[:VIEW_DEFINITION].length == 4000 view_info[:VIEW_DEFINITION] = begin - select_values("EXEC sp_helptext #{identifier.object_quoted}", 'SCHEMA').join + select_values("EXEC sp_helptext #{identifier.object_quoted}", "SCHEMA").join rescue warn "No view definition found, possible permissions problem.\nPlease run GRANT VIEW DEFINITION TO your_user;" nil diff --git a/lib/active_record/connection_adapters/sqlserver/showplan.rb b/lib/active_record/connection_adapters/sqlserver/showplan.rb index 1891cb588..9c296a8ee 100644 --- a/lib/active_record/connection_adapters/sqlserver/showplan.rb +++ b/lib/active_record/connection_adapters/sqlserver/showplan.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require 'active_record/connection_adapters/sqlserver/showplan/printer_table' -require 'active_record/connection_adapters/sqlserver/showplan/printer_xml' +require "active_record/connection_adapters/sqlserver/showplan/printer_table" +require "active_record/connection_adapters/sqlserver/showplan/printer_xml" module ActiveRecord module ConnectionAdapters module SQLServer module Showplan - OPTION_ALL = 'SHOWPLAN_ALL' - OPTION_TEXT = 'SHOWPLAN_TEXT' - OPTION_XML = 'SHOWPLAN_XML' + OPTION_ALL = "SHOWPLAN_ALL" + OPTION_TEXT = "SHOWPLAN_TEXT" + OPTION_XML = "SHOWPLAN_XML" OPTIONS = [OPTION_ALL, OPTION_TEXT, OPTION_XML] def explain(arel, binds = []) sql = to_sql(arel) - result = with_showplan_on { sp_executesql(sql, 'EXPLAIN', binds) } + result = with_showplan_on { sp_executesql(sql, "EXPLAIN", binds) } printer = showplan_printer.new(result) printer.pp end diff --git a/lib/active_record/connection_adapters/sqlserver/showplan/printer_table.rb b/lib/active_record/connection_adapters/sqlserver/showplan/printer_table.rb index 4885d74cc..287e4efb7 100644 --- a/lib/active_record/connection_adapters/sqlserver/showplan/printer_table.rb +++ b/lib/active_record/connection_adapters/sqlserver/showplan/printer_table.rb @@ -43,7 +43,7 @@ def compute_column_widths end def build_separator - '+' + @widths.map { |w| '-' * (w + (cell_padding * 2)) }.join('+') + '+' + "+" + @widths.map { |w| "-" * (w + (cell_padding * 2)) }.join("+") + "+" end def build_cells(items) @@ -56,7 +56,7 @@ def build_cells(items) def cast_item(item) case item - when NilClass then 'NULL' + when NilClass then "NULL" when Float then item.to_s.to(9) else item.to_s.truncate(max_column_width) end diff --git a/lib/active_record/connection_adapters/sqlserver/showplan/printer_xml.rb b/lib/active_record/connection_adapters/sqlserver/showplan/printer_xml.rb index 00c268143..717eaf859 100644 --- a/lib/active_record/connection_adapters/sqlserver/showplan/printer_xml.rb +++ b/lib/active_record/connection_adapters/sqlserver/showplan/printer_xml.rb @@ -12,7 +12,7 @@ def initialize(result) def pp xml = @result.rows.first.first if defined?(Nokogiri) - Nokogiri::XML(xml).to_xml indent: 2, encoding: 'UTF-8' + Nokogiri::XML(xml).to_xml indent: 2, encoding: "UTF-8" else xml end diff --git a/lib/active_record/connection_adapters/sqlserver/table_definition.rb b/lib/active_record/connection_adapters/sqlserver/table_definition.rb index 244f33295..1027a6d97 100644 --- a/lib/active_record/connection_adapters/sqlserver/table_definition.rb +++ b/lib/active_record/connection_adapters/sqlserver/table_definition.rb @@ -10,7 +10,7 @@ def primary_key(name, type = :primary_key, **options) if [:integer, :bigint].include?(type) options[:is_identity] = true unless options.key?(:default) elsif type == :uuid - options[:default] = options.fetch(:default, 'NEWID()') + options[:default] = options.fetch(:default, "NEWID()") options[:primary_key] = true end super diff --git a/lib/active_record/connection_adapters/sqlserver/transaction.rb b/lib/active_record/connection_adapters/sqlserver/transaction.rb index baba63859..bdc8d78a2 100644 --- a/lib/active_record/connection_adapters/sqlserver/transaction.rb +++ b/lib/active_record/connection_adapters/sqlserver/transaction.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'active_record/connection_adapters/abstract/transaction' +require "active_record/connection_adapters/abstract/transaction" module ActiveRecord module ConnectionAdapters @@ -19,8 +19,8 @@ def current_isolation_level # When READ_COMMITTED_SNAPSHOT is set to ON, # user_options_isolation_level will be equal to 'read committed # snapshot' which is not a valid isolation level - if level.blank? || level == 'read committed snapshot' - 'READ COMMITTED' + if level.blank? || level == "read committed snapshot" + "READ COMMITTED" else level.upcase end diff --git a/lib/active_record/connection_adapters/sqlserver/type.rb b/lib/active_record/connection_adapters/sqlserver/type.rb index 59121074a..6c5d82b4d 100644 --- a/lib/active_record/connection_adapters/sqlserver/type.rb +++ b/lib/active_record/connection_adapters/sqlserver/type.rb @@ -1,48 +1,48 @@ # frozen_string_literal: true -require 'active_record/type' +require "active_record/type" # Behaviors -require 'active_record/connection_adapters/sqlserver/type/data' -require 'active_record/connection_adapters/sqlserver/type/time_value_fractional' +require "active_record/connection_adapters/sqlserver/type/data" +require "active_record/connection_adapters/sqlserver/type/time_value_fractional" # Exact Numerics -require 'active_record/connection_adapters/sqlserver/type/integer' -require 'active_record/connection_adapters/sqlserver/type/big_integer' -require 'active_record/connection_adapters/sqlserver/type/small_integer' -require 'active_record/connection_adapters/sqlserver/type/tiny_integer' -require 'active_record/connection_adapters/sqlserver/type/boolean' -require 'active_record/connection_adapters/sqlserver/type/decimal' -require 'active_record/connection_adapters/sqlserver/type/money' -require 'active_record/connection_adapters/sqlserver/type/small_money' +require "active_record/connection_adapters/sqlserver/type/integer" +require "active_record/connection_adapters/sqlserver/type/big_integer" +require "active_record/connection_adapters/sqlserver/type/small_integer" +require "active_record/connection_adapters/sqlserver/type/tiny_integer" +require "active_record/connection_adapters/sqlserver/type/boolean" +require "active_record/connection_adapters/sqlserver/type/decimal" +require "active_record/connection_adapters/sqlserver/type/money" +require "active_record/connection_adapters/sqlserver/type/small_money" # Approximate Numerics -require 'active_record/connection_adapters/sqlserver/type/float' -require 'active_record/connection_adapters/sqlserver/type/real' +require "active_record/connection_adapters/sqlserver/type/float" +require "active_record/connection_adapters/sqlserver/type/real" # Date and Time -require 'active_record/connection_adapters/sqlserver/type/date' -require 'active_record/connection_adapters/sqlserver/type/datetime' -require 'active_record/connection_adapters/sqlserver/type/datetime2' -require 'active_record/connection_adapters/sqlserver/type/datetimeoffset' -require 'active_record/connection_adapters/sqlserver/type/smalldatetime' -require 'active_record/connection_adapters/sqlserver/type/time' +require "active_record/connection_adapters/sqlserver/type/date" +require "active_record/connection_adapters/sqlserver/type/datetime" +require "active_record/connection_adapters/sqlserver/type/datetime2" +require "active_record/connection_adapters/sqlserver/type/datetimeoffset" +require "active_record/connection_adapters/sqlserver/type/smalldatetime" +require "active_record/connection_adapters/sqlserver/type/time" # Character Strings -require 'active_record/connection_adapters/sqlserver/type/string' -require 'active_record/connection_adapters/sqlserver/type/char' -require 'active_record/connection_adapters/sqlserver/type/varchar' -require 'active_record/connection_adapters/sqlserver/type/varchar_max' -require 'active_record/connection_adapters/sqlserver/type/text' +require "active_record/connection_adapters/sqlserver/type/string" +require "active_record/connection_adapters/sqlserver/type/char" +require "active_record/connection_adapters/sqlserver/type/varchar" +require "active_record/connection_adapters/sqlserver/type/varchar_max" +require "active_record/connection_adapters/sqlserver/type/text" # Unicode Character Strings -require 'active_record/connection_adapters/sqlserver/type/unicode_string' -require 'active_record/connection_adapters/sqlserver/type/unicode_char' -require 'active_record/connection_adapters/sqlserver/type/unicode_varchar' -require 'active_record/connection_adapters/sqlserver/type/unicode_varchar_max' -require 'active_record/connection_adapters/sqlserver/type/unicode_text' +require "active_record/connection_adapters/sqlserver/type/unicode_string" +require "active_record/connection_adapters/sqlserver/type/unicode_char" +require "active_record/connection_adapters/sqlserver/type/unicode_varchar" +require "active_record/connection_adapters/sqlserver/type/unicode_varchar_max" +require "active_record/connection_adapters/sqlserver/type/unicode_text" # Binary Strings -require 'active_record/connection_adapters/sqlserver/type/binary' -require 'active_record/connection_adapters/sqlserver/type/varbinary' -require 'active_record/connection_adapters/sqlserver/type/varbinary_max' +require "active_record/connection_adapters/sqlserver/type/binary" +require "active_record/connection_adapters/sqlserver/type/varbinary" +require "active_record/connection_adapters/sqlserver/type/varbinary_max" # Other Data Types -require 'active_record/connection_adapters/sqlserver/type/uuid' -require 'active_record/connection_adapters/sqlserver/type/timestamp' -require 'active_record/connection_adapters/sqlserver/type/json' +require "active_record/connection_adapters/sqlserver/type/uuid" +require "active_record/connection_adapters/sqlserver/type/timestamp" +require "active_record/connection_adapters/sqlserver/type/json" module ActiveRecord module Type diff --git a/lib/active_record/connection_adapters/sqlserver/type/date.rb b/lib/active_record/connection_adapters/sqlserver/type/date.rb index 845f2b6db..43896458d 100644 --- a/lib/active_record/connection_adapters/sqlserver/type/date.rb +++ b/lib/active_record/connection_adapters/sqlserver/type/date.rb @@ -7,7 +7,7 @@ module Type class Date < ActiveRecord::Type::Date def sqlserver_type - 'date' + "date" end def serialize(value) diff --git a/lib/active_record/connection_adapters/sqlserver/type/datetime.rb b/lib/active_record/connection_adapters/sqlserver/type/datetime.rb index 59429cdc0..36c861f27 100644 --- a/lib/active_record/connection_adapters/sqlserver/type/datetime.rb +++ b/lib/active_record/connection_adapters/sqlserver/type/datetime.rb @@ -36,7 +36,7 @@ def quoted(value) private def fast_string_to_time(string) - time = ActiveSupport::TimeZone['UTC'].strptime(string, fast_string_to_time_format) + time = ActiveSupport::TimeZone["UTC"].strptime(string, fast_string_to_time_format) new_time(time.year, time.month, time.day, time.hour, time.min, time.sec, Rational(time.nsec, 1_000)) rescue ArgumentError diff --git a/lib/active_record/connection_adapters/sqlserver/type/time_value_fractional.rb b/lib/active_record/connection_adapters/sqlserver/type/time_value_fractional.rb index aa0b0ed73..45933248c 100644 --- a/lib/active_record/connection_adapters/sqlserver/type/time_value_fractional.rb +++ b/lib/active_record/connection_adapters/sqlserver/type/time_value_fractional.rb @@ -25,7 +25,7 @@ def quote_fractional(value) return 0 if fractional_scale == 0 frac_seconds = seconds_precision(value) seconds = (frac_seconds.to_f / fractional_operator.to_f).round(fractional_scale) - seconds.to_d.to_s.split('.').last.to(fractional_scale-1) + seconds.to_d.to_s.split(".").last.to(fractional_scale-1) end def fractional_property @@ -82,7 +82,7 @@ def fractional_max end def fractional_scale_max - ('9' * fractional_scale) + ('0' * (fractional_digits - fractional_scale)) + ("9" * fractional_scale) + ("0" * (fractional_digits - fractional_scale)) end end diff --git a/lib/active_record/connection_adapters/sqlserver/type/unicode_char.rb b/lib/active_record/connection_adapters/sqlserver/type/unicode_char.rb index 26ad415aa..0eb364234 100644 --- a/lib/active_record/connection_adapters/sqlserver/type/unicode_char.rb +++ b/lib/active_record/connection_adapters/sqlserver/type/unicode_char.rb @@ -11,7 +11,7 @@ def type end def sqlserver_type - 'nchar'.yield_self do |type| + "nchar".yield_self do |type| type += "(#{limit})" if limit type end diff --git a/lib/active_record/connection_adapters/sqlserver/type/varbinary.rb b/lib/active_record/connection_adapters/sqlserver/type/varbinary.rb index 6ae0af9cd..c00473dd5 100644 --- a/lib/active_record/connection_adapters/sqlserver/type/varbinary.rb +++ b/lib/active_record/connection_adapters/sqlserver/type/varbinary.rb @@ -16,7 +16,7 @@ def type end def sqlserver_type - 'varbinary'.yield_self do |type| + "varbinary".yield_self do |type| type += "(#{limit})" if limit type end diff --git a/lib/active_record/connection_adapters/sqlserver/type/varchar.rb b/lib/active_record/connection_adapters/sqlserver/type/varchar.rb index a19216696..0e08c4e75 100644 --- a/lib/active_record/connection_adapters/sqlserver/type/varchar.rb +++ b/lib/active_record/connection_adapters/sqlserver/type/varchar.rb @@ -16,7 +16,7 @@ def type end def sqlserver_type - 'varchar'.yield_self do |type| + "varchar".yield_self do |type| type += "(#{limit})" if limit type end diff --git a/lib/active_record/connection_adapters/sqlserver/utils.rb b/lib/active_record/connection_adapters/sqlserver/utils.rb index bd2a6fdf9..a5b74faa0 100644 --- a/lib/active_record/connection_adapters/sqlserver/utils.rb +++ b/lib/active_record/connection_adapters/sqlserver/utils.rb @@ -1,13 +1,13 @@ # frozen_string_literal: true -require 'strscan' +require "strscan" module ActiveRecord module ConnectionAdapters module SQLServer module Utils - QUOTED_STRING_PREFIX = 'N' + QUOTED_STRING_PREFIX = "N" # Value object to return identifiers from SQL Server names http://bit.ly/1CZ3EiL # Inspiried from Rails PostgreSQL::Name adapter object in their own Utils. @@ -93,7 +93,7 @@ def parse_raw_name @schema = @parts.first end rest = scanner.rest - rest = rest.starts_with?('.') ? rest[1..-1] : rest[0..-1] + rest = rest.starts_with?(".") ? rest[1..-1] : rest[0..-1] @object = unquote(rest) @parts << @object end @@ -103,7 +103,7 @@ def quote(part) end def unquote(part) - if part && part.start_with?('[') + if part && part.start_with?("[") part[1..-2] else part diff --git a/lib/active_record/connection_adapters/sqlserver_adapter.rb b/lib/active_record/connection_adapters/sqlserver_adapter.rb index d22cb238e..2f58eb5c2 100644 --- a/lib/active_record/connection_adapters/sqlserver_adapter.rb +++ b/lib/active_record/connection_adapters/sqlserver_adapter.rb @@ -1,35 +1,35 @@ # frozen_string_literal: true -require 'base64' -require 'active_record' -require 'arel_sqlserver' -require 'active_record/connection_adapters/abstract_adapter' -require 'active_record/connection_adapters/sqlserver/core_ext/active_record' -require 'active_record/connection_adapters/sqlserver/core_ext/calculations' -require 'active_record/connection_adapters/sqlserver/core_ext/explain' -require 'active_record/connection_adapters/sqlserver/core_ext/explain_subscriber' -require 'active_record/connection_adapters/sqlserver/core_ext/attribute_methods' -require 'active_record/connection_adapters/sqlserver/core_ext/finder_methods' -require 'active_record/connection_adapters/sqlserver/core_ext/query_methods' -require 'active_record/connection_adapters/sqlserver/core_ext/preloader' -require 'active_record/connection_adapters/sqlserver/version' -require 'active_record/connection_adapters/sqlserver/type' -require 'active_record/connection_adapters/sqlserver/database_limits' -require 'active_record/connection_adapters/sqlserver/database_statements' -require 'active_record/connection_adapters/sqlserver/database_tasks' -require 'active_record/connection_adapters/sqlserver/transaction' -require 'active_record/connection_adapters/sqlserver/errors' -require 'active_record/connection_adapters/sqlserver/schema_creation' -require 'active_record/connection_adapters/sqlserver/schema_dumper' -require 'active_record/connection_adapters/sqlserver/schema_statements' -require 'active_record/connection_adapters/sqlserver/sql_type_metadata' -require 'active_record/connection_adapters/sqlserver/showplan' -require 'active_record/connection_adapters/sqlserver/table_definition' -require 'active_record/connection_adapters/sqlserver/quoting' -require 'active_record/connection_adapters/sqlserver/utils' -require 'active_record/sqlserver_base' -require 'active_record/connection_adapters/sqlserver_column' -require 'active_record/tasks/sqlserver_database_tasks' +require "base64" +require "active_record" +require "arel_sqlserver" +require "active_record/connection_adapters/abstract_adapter" +require "active_record/connection_adapters/sqlserver/core_ext/active_record" +require "active_record/connection_adapters/sqlserver/core_ext/calculations" +require "active_record/connection_adapters/sqlserver/core_ext/explain" +require "active_record/connection_adapters/sqlserver/core_ext/explain_subscriber" +require "active_record/connection_adapters/sqlserver/core_ext/attribute_methods" +require "active_record/connection_adapters/sqlserver/core_ext/finder_methods" +require "active_record/connection_adapters/sqlserver/core_ext/query_methods" +require "active_record/connection_adapters/sqlserver/core_ext/preloader" +require "active_record/connection_adapters/sqlserver/version" +require "active_record/connection_adapters/sqlserver/type" +require "active_record/connection_adapters/sqlserver/database_limits" +require "active_record/connection_adapters/sqlserver/database_statements" +require "active_record/connection_adapters/sqlserver/database_tasks" +require "active_record/connection_adapters/sqlserver/transaction" +require "active_record/connection_adapters/sqlserver/errors" +require "active_record/connection_adapters/sqlserver/schema_creation" +require "active_record/connection_adapters/sqlserver/schema_dumper" +require "active_record/connection_adapters/sqlserver/schema_statements" +require "active_record/connection_adapters/sqlserver/sql_type_metadata" +require "active_record/connection_adapters/sqlserver/showplan" +require "active_record/connection_adapters/sqlserver/table_definition" +require "active_record/connection_adapters/sqlserver/quoting" +require "active_record/connection_adapters/sqlserver/utils" +require "active_record/sqlserver_base" +require "active_record/connection_adapters/sqlserver_column" +require "active_record/tasks/sqlserver_database_tasks" module ActiveRecord module ConnectionAdapters @@ -43,7 +43,7 @@ class SQLServerAdapter < AbstractAdapter SQLServer::DatabaseLimits, SQLServer::DatabaseTasks - ADAPTER_NAME = 'SQLServer'.freeze + ADAPTER_NAME = "SQLServer".freeze # Default precision for 'time' (See https://docs.microsoft.com/en-us/sql/t-sql/data-types/time-transact-sql) DEFAULT_TIME_PRECISION = 7 @@ -56,7 +56,7 @@ class SQLServerAdapter < AbstractAdapter cattr_accessor :showplan_option, instance_accessor: false cattr_accessor :lowercase_schema_reflection - self.cs_equality_operator = 'COLLATE Latin1_General_CS_AS_WS' + self.cs_equality_operator = "COLLATE Latin1_General_CS_AS_WS" self.use_output_inserted = true self.exclude_output_inserted_table_names = Concurrent::Map.new { false } @@ -189,7 +189,7 @@ def disable_referential_integrity def active? return false unless @connection - raw_connection_do 'SELECT 1' + raw_connection_do "SELECT 1" true rescue *connection_errors false @@ -219,7 +219,7 @@ def clear_cache! def reset! reset_transaction - do_execute 'IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION' + do_execute "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION" end # === Abstract Adapter (Misc Support) =========================== # @@ -296,29 +296,29 @@ def get_database_version # :nodoc: def initialize_type_map(m = type_map) m.register_type %r{.*}, SQLServer::Type::UnicodeString.new # Exact Numerics - register_class_with_limit m, 'bigint(8)', SQLServer::Type::BigInteger - m.alias_type 'bigint', 'bigint(8)' - register_class_with_limit m, 'int(4)', SQLServer::Type::Integer - m.alias_type 'integer', 'int(4)' - m.alias_type 'int', 'int(4)' - register_class_with_limit m, 'smallint(2)', SQLServer::Type::SmallInteger - m.alias_type 'smallint', 'smallint(2)' - register_class_with_limit m, 'tinyint(1)', SQLServer::Type::TinyInteger - m.alias_type 'tinyint', 'tinyint(1)' - m.register_type 'bit', SQLServer::Type::Boolean.new + register_class_with_limit m, "bigint(8)", SQLServer::Type::BigInteger + m.alias_type "bigint", "bigint(8)" + register_class_with_limit m, "int(4)", SQLServer::Type::Integer + m.alias_type "integer", "int(4)" + m.alias_type "int", "int(4)" + register_class_with_limit m, "smallint(2)", SQLServer::Type::SmallInteger + m.alias_type "smallint", "smallint(2)" + register_class_with_limit m, "tinyint(1)", SQLServer::Type::TinyInteger + m.alias_type "tinyint", "tinyint(1)" + m.register_type "bit", SQLServer::Type::Boolean.new m.register_type %r{\Adecimal}i do |sql_type| scale = extract_scale(sql_type) precision = extract_precision(sql_type) SQLServer::Type::Decimal.new precision: precision, scale: scale end - m.alias_type %r{\Anumeric}i, 'decimal' - m.register_type 'money', SQLServer::Type::Money.new - m.register_type 'smallmoney', SQLServer::Type::SmallMoney.new + m.alias_type %r{\Anumeric}i, "decimal" + m.register_type "money", SQLServer::Type::Money.new + m.register_type "smallmoney", SQLServer::Type::SmallMoney.new # Approximate Numerics - m.register_type 'float', SQLServer::Type::Float.new - m.register_type 'real', SQLServer::Type::Real.new + m.register_type "float", SQLServer::Type::Float.new + m.register_type "real", SQLServer::Type::Real.new # Date and Time - m.register_type 'date', SQLServer::Type::Date.new + m.register_type "date", SQLServer::Type::Date.new m.register_type %r{\Adatetime} do |sql_type| precision = extract_precision(sql_type) if precision @@ -331,7 +331,7 @@ def initialize_type_map(m = type_map) precision = extract_precision(sql_type) SQLServer::Type::DateTimeOffset.new precision: precision end - m.register_type 'smalldatetime', SQLServer::Type::SmallDateTime.new + m.register_type "smalldatetime", SQLServer::Type::SmallDateTime.new m.register_type %r{\Atime}i do |sql_type| precision = extract_precision(sql_type) || DEFAULT_TIME_PRECISION SQLServer::Type::Time.new precision: precision @@ -339,22 +339,22 @@ def initialize_type_map(m = type_map) # Character Strings register_class_with_limit m, %r{\Achar}i, SQLServer::Type::Char register_class_with_limit m, %r{\Avarchar}i, SQLServer::Type::Varchar - m.register_type 'varchar(max)', SQLServer::Type::VarcharMax.new - m.register_type 'text', SQLServer::Type::Text.new + m.register_type "varchar(max)", SQLServer::Type::VarcharMax.new + m.register_type "text", SQLServer::Type::Text.new # Unicode Character Strings register_class_with_limit m, %r{\Anchar}i, SQLServer::Type::UnicodeChar register_class_with_limit m, %r{\Anvarchar}i, SQLServer::Type::UnicodeVarchar - m.alias_type 'string', 'nvarchar(4000)' - m.register_type 'nvarchar(max)', SQLServer::Type::UnicodeVarcharMax.new - m.register_type 'nvarchar(max)', SQLServer::Type::UnicodeVarcharMax.new - m.register_type 'ntext', SQLServer::Type::UnicodeText.new + m.alias_type "string", "nvarchar(4000)" + m.register_type "nvarchar(max)", SQLServer::Type::UnicodeVarcharMax.new + m.register_type "nvarchar(max)", SQLServer::Type::UnicodeVarcharMax.new + m.register_type "ntext", SQLServer::Type::UnicodeText.new # Binary Strings register_class_with_limit m, %r{\Abinary}i, SQLServer::Type::Binary register_class_with_limit m, %r{\Avarbinary}i, SQLServer::Type::Varbinary - m.register_type 'varbinary(max)', SQLServer::Type::VarbinaryMax.new + m.register_type "varbinary(max)", SQLServer::Type::VarbinaryMax.new # Other Data Types - m.register_type 'uniqueidentifier', SQLServer::Type::Uuid.new - m.register_type 'timestamp', SQLServer::Type::Timestamp.new + m.register_type "uniqueidentifier", SQLServer::Type::Uuid.new + m.register_type "timestamp", SQLServer::Type::Timestamp.new end def translate_exception(e, message:, sql:, binds:) @@ -398,7 +398,7 @@ def connect when :dblib dblib_connect(config) end - @spid = _raw_select('SELECT @@SPID', fetch: :rows).first.first + @spid = _raw_select("SELECT @@SPID", fetch: :rows).first.first @version_year = version_year configure_connection end @@ -417,7 +417,7 @@ def dblib_connect(config) username: config[:username], password: config[:password], database: config[:database], - tds_version: config[:tds_version] || '7.3', + tds_version: config[:tds_version] || "7.3", appname: config_appname(config), login_timeout: config_login_timeout(config), timeout: config_timeout(config), @@ -426,23 +426,23 @@ def dblib_connect(config) contained: config[:contained] ).tap do |client| if config[:azure] - client.execute('SET ANSI_NULLS ON').do - client.execute('SET ANSI_NULL_DFLT_ON ON').do - client.execute('SET ANSI_PADDING ON').do - client.execute('SET ANSI_WARNINGS ON').do + client.execute("SET ANSI_NULLS ON").do + client.execute("SET ANSI_NULL_DFLT_ON ON").do + client.execute("SET ANSI_PADDING ON").do + client.execute("SET ANSI_WARNINGS ON").do else - client.execute('SET ANSI_DEFAULTS ON').do + client.execute("SET ANSI_DEFAULTS ON").do end - client.execute('SET QUOTED_IDENTIFIER ON').do - client.execute('SET CURSOR_CLOSE_ON_COMMIT OFF').do - client.execute('SET IMPLICIT_TRANSACTIONS OFF').do - client.execute('SET TEXTSIZE 2147483647').do - client.execute('SET CONCAT_NULL_YIELDS_NULL ON').do + client.execute("SET QUOTED_IDENTIFIER ON").do + client.execute("SET CURSOR_CLOSE_ON_COMMIT OFF").do + client.execute("SET IMPLICIT_TRANSACTIONS OFF").do + client.execute("SET TEXTSIZE 2147483647").do + client.execute("SET CONCAT_NULL_YIELDS_NULL ON").do end end def config_appname(config) - config[:appname] || configure_application_name || Rails.application.class.name.split('::').first rescue nil + config[:appname] || configure_application_name || Rails.application.class.name.split("::").first rescue nil end def config_login_timeout(config) @@ -464,11 +464,11 @@ def configure_application_name ; end def initialize_dateformatter @database_dateformat = user_options_dateformat a, b, c = @database_dateformat.each_char.to_a - [a, b, c].each { |f| f.upcase! if f == 'y' } + [a, b, c].each { |f| f.upcase! if f == "y" } dateformat = "%#{a}-%#{b}-%#{c}" ::Date::DATE_FORMATS[:_sqlserver_dateformat] = dateformat ::Time::DATE_FORMATS[:_sqlserver_dateformat] = dateformat - ::Time::DATE_FORMATS[:_sqlserver_time] = '%H:%M:%S' + ::Time::DATE_FORMATS[:_sqlserver_time] = "%H:%M:%S" ::Time::DATE_FORMATS[:_sqlserver_datetime] = "#{dateformat} %H:%M:%S" ::Time::DATE_FORMATS[:_sqlserver_datetimeoffset] = lambda { |time| time.strftime "#{dateformat} %H:%M:%S.%9N #{time.formatted_offset}" @@ -483,7 +483,7 @@ def version_year end def sqlserver_version - @sqlserver_version ||= _raw_select('SELECT @@version', fetch: :rows).first.first.to_s + @sqlserver_version ||= _raw_select("SELECT @@version", fetch: :rows).first.first.to_s end end end diff --git a/lib/active_record/sqlserver_base.rb b/lib/active_record/sqlserver_base.rb index 7dcf2765d..8f2150ced 100644 --- a/lib/active_record/sqlserver_base.rb +++ b/lib/active_record/sqlserver_base.rb @@ -8,7 +8,7 @@ def sqlserver_connection(config) #:nodoc: mode = config[:mode].to_s.downcase.underscore.to_sym case mode when :dblib - require 'tiny_tds' + require "tiny_tds" else raise ArgumentError, "Unknown connection mode in #{config.inspect}." end diff --git a/lib/active_record/tasks/sqlserver_database_tasks.rb b/lib/active_record/tasks/sqlserver_database_tasks.rb index 0e7231dda..b95297b28 100644 --- a/lib/active_record/tasks/sqlserver_database_tasks.rb +++ b/lib/active_record/tasks/sqlserver_database_tasks.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'active_record/tasks/database_tasks' -require 'shellwords' -require 'ipaddr' -require 'socket' +require "active_record/tasks/database_tasks" +require "shellwords" +require "ipaddr" +require "socket" module ActiveRecord module Tasks class SQLServerDatabaseTasks - DEFAULT_COLLATION = 'SQL_Latin1_General_CP1_CI_AS' + DEFAULT_COLLATION = "SQL_Latin1_General_CP1_CI_AS" delegate :connection, :establish_connection, :clear_active_connections!, to: ActiveRecord::Base @@ -21,7 +21,7 @@ def initialize(configuration) def create(master_established = false) establish_master_connection unless master_established - connection.create_database configuration['database'], configuration.merge('collation' => default_collation) + connection.create_database configuration["database"], configuration.merge("collation" => default_collation) establish_connection configuration rescue ActiveRecord::StatementInvalid => error if /database .* already exists/i === error.message @@ -33,7 +33,7 @@ def create(master_established = false) def drop establish_master_connection - connection.drop_database configuration['database'] + connection.drop_database configuration["database"] end def charset @@ -52,7 +52,7 @@ def purge def structure_dump(filename, extra_flags) server_arg = "-S #{Shellwords.escape(configuration['host'])}" - server_arg += ":#{Shellwords.escape(configuration['port'])}" if configuration['port'] + server_arg += ":#{Shellwords.escape(configuration['port'])}" if configuration["port"] command = [ "defncopy-ttds", server_arg, @@ -65,13 +65,13 @@ def structure_dump(filename, extra_flags) command.concat(table_args) view_args = connection.views.map { |v| Shellwords.escape(v) } command.concat(view_args) - raise 'Error dumping database' unless Kernel.system(command.join(' ')) + raise "Error dumping database" unless Kernel.system(command.join(" ")) dump = File.read(filename) - dump.gsub!(/^USE .*$\nGO\n/, '') # Strip db USE statements - dump.gsub!(/^GO\n/, '') # Strip db GO statements - dump.gsub!(/nvarchar\(8000\)/, 'nvarchar(4000)') # Fix nvarchar(8000) column defs - dump.gsub!(/nvarchar\(-1\)/, 'nvarchar(max)') # Fix nvarchar(-1) column defs - dump.gsub!(/text\(\d+\)/, 'text') # Fix text(16) column defs + dump.gsub!(/^USE .*$\nGO\n/, "") # Strip db USE statements + dump.gsub!(/^GO\n/, "") # Strip db GO statements + dump.gsub!(/nvarchar\(8000\)/, "nvarchar(4000)") # Fix nvarchar(8000) column defs + dump.gsub!(/nvarchar\(-1\)/, "nvarchar(max)") # Fix nvarchar(-1) column defs + dump.gsub!(/text\(\d+\)/, "text") # Fix text(16) column defs File.open(filename, "w") { |file| file.puts dump } end @@ -87,11 +87,11 @@ def configuration end def default_collation - configuration['collation'] || DEFAULT_COLLATION + configuration["collation"] || DEFAULT_COLLATION end def establish_master_connection - establish_connection configuration.merge('database' => 'master') + establish_connection configuration.merge("database" => "master") end end @@ -103,9 +103,9 @@ module DatabaseTasksSQLServer module ClassMethods LOCAL_IPADDR = [ - IPAddr.new('192.168.0.0/16'), - IPAddr.new('10.0.0.0/8'), - IPAddr.new('172.16.0.0/12') + IPAddr.new("192.168.0.0/16"), + IPAddr.new("10.0.0.0/8"), + IPAddr.new("172.16.0.0/12") ] private @@ -115,8 +115,8 @@ def local_database?(configuration) end def configuration_host_ip(configuration) - return nil unless configuration['host'] - Socket::getaddrinfo(configuration['host'], 'echo', Socket::AF_INET)[0][3] + return nil unless configuration["host"] + Socket::getaddrinfo(configuration["host"], "echo", Socket::AF_INET)[0][3] end def local_ipaddr?(host_ip) diff --git a/lib/activerecord-sqlserver-adapter.rb b/lib/activerecord-sqlserver-adapter.rb index bfcdd0347..ab2363641 100644 --- a/lib/activerecord-sqlserver-adapter.rb +++ b/lib/activerecord-sqlserver-adapter.rb @@ -1,3 +1,3 @@ # frozen_string_literal: true -require 'active_record/connection_adapters/sqlserver_adapter' +require "active_record/connection_adapters/sqlserver_adapter" diff --git a/lib/arel/visitors/sqlserver.rb b/lib/arel/visitors/sqlserver.rb index 82b77d99e..04daae5da 100644 --- a/lib/arel/visitors/sqlserver.rb +++ b/lib/arel/visitors/sqlserver.rb @@ -38,7 +38,7 @@ def visit_Arel_Nodes_UpdateStatement(o, a) end def visit_Arel_Nodes_Lock o, collector - o.expr = Arel.sql('WITH(UPDLOCK)') if o.expr.to_s =~ /FOR UPDATE/ + o.expr = Arel.sql("WITH(UPDLOCK)") if o.expr.to_s =~ /FOR UPDATE/ collector << " " visit o.expr, collector end @@ -109,7 +109,7 @@ def visit_Arel_Nodes_JoinSource o, collector end if o.right.any? collector << " " if o.left - collector = inject_join o.right, collector, ' ' + collector = inject_join o.right, collector, " " end collector end diff --git a/lib/arel_sqlserver.rb b/lib/arel_sqlserver.rb index f271dbb02..e6c7760ac 100644 --- a/lib/arel_sqlserver.rb +++ b/lib/arel_sqlserver.rb @@ -1,4 +1,4 @@ # frozen_string_literal: true -require 'arel' -require 'arel/visitors/sqlserver' +require "arel" +require "arel/visitors/sqlserver" diff --git a/test/cases/adapter_test_sqlserver.rb b/test/cases/adapter_test_sqlserver.rb index 366c42302..7e2161513 100644 --- a/test/cases/adapter_test_sqlserver.rb +++ b/test/cases/adapter_test_sqlserver.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/topic' -require 'models/task' -require 'models/post' -require 'models/subscriber' -require 'models/minimalistic' +require "cases/helper_sqlserver" +require "models/topic" +require "models/task" +require "models/post" +require "models/subscriber" +require "models/minimalistic" class AdapterTestSQLServer < ActiveRecord::TestCase @@ -15,7 +15,7 @@ class AdapterTestSQLServer < ActiveRecord::TestCase let(:basic_update_sql) { "UPDATE [customers] SET [address_street] = NULL WHERE [id] = 2" } let(:basic_select_sql) { "SELECT * FROM [customers] WHERE ([customers].[id] = 1)" } - it 'has basic and non-sensitive information in the adapters inspect method' do + it "has basic and non-sensitive information in the adapters inspect method" do string = connection.inspect _(string).must_match %r{ActiveRecord::ConnectionAdapters::SQLServerAdapter} _(string).must_match %r{version\: \d.\d} @@ -27,66 +27,66 @@ class AdapterTestSQLServer < ActiveRecord::TestCase _(string).wont_match %r{port} end - it 'has a 128 max #table_alias_length' do + it "has a 128 max #table_alias_length" do assert connection.table_alias_length <= 128 end - it 'raises invalid statement error for bad SQL' do + it "raises invalid statement error for bad SQL" do assert_raise(ActiveRecord::StatementInvalid) { Topic.connection.update("UPDATE XXX") } end - it 'is has our adapter_name' do - assert_equal 'SQLServer', connection.adapter_name + it "is has our adapter_name" do + assert_equal "SQLServer", connection.adapter_name end - it 'support DDL in transactions' do + it "support DDL in transactions" do assert connection.supports_ddl_transactions? end - it 'allow owner table name prefixs like dbo to still allow table exists to return true' do + it "allow owner table name prefixs like dbo to still allow table exists to return true" do begin - assert_equal 'topics', Topic.table_name + assert_equal "topics", Topic.table_name assert Topic.table_exists? - Topic.table_name = 'dbo.topics' - assert Topic.table_exists?, 'Tasks table name of dbo.topics should return true for exists.' + Topic.table_name = "dbo.topics" + assert Topic.table_exists?, "Tasks table name of dbo.topics should return true for exists." ensure - Topic.table_name = 'topics' + Topic.table_name = "topics" end end - it 'return true to insert sql query for inserts only' do - assert connection.send(:insert_sql?,'INSERT...') + it "return true to insert sql query for inserts only" do + assert connection.send(:insert_sql?,"INSERT...") assert connection.send(:insert_sql?, "EXEC sp_executesql N'INSERT INTO [fk_test_has_fks] ([fk_id]) VALUES (@0); SELECT CAST(SCOPE_IDENTITY() AS bigint) AS Ident', N'@0 int', @0 = 0") - assert !connection.send(:insert_sql?,'UPDATE...') - assert !connection.send(:insert_sql?,'SELECT...') + assert !connection.send(:insert_sql?,"UPDATE...") + assert !connection.send(:insert_sql?,"SELECT...") end - it 'return unquoted table name object from basic INSERT UPDATE and SELECT statements' do - assert_equal 'funny_jokes', connection.send(:get_table_name, basic_insert_sql) - assert_equal 'customers', connection.send(:get_table_name, basic_update_sql) - assert_equal 'customers', connection.send(:get_table_name, basic_select_sql) + it "return unquoted table name object from basic INSERT UPDATE and SELECT statements" do + assert_equal "funny_jokes", connection.send(:get_table_name, basic_insert_sql) + assert_equal "customers", connection.send(:get_table_name, basic_update_sql) + assert_equal "customers", connection.send(:get_table_name, basic_select_sql) end - it 'test bad connection' do + it "test bad connection" do assert_raise ActiveRecord::NoDatabaseError do - config = ActiveRecord::Base.configurations['arunit'].merge(database: 'inexistent_activerecord_unittest') + config = ActiveRecord::Base.configurations["arunit"].merge(database: "inexistent_activerecord_unittest") ActiveRecord::Base.sqlserver_connection config end end - it 'test database exists returns false if database does not exist' do - config = ActiveRecord::Base.configurations['arunit'].merge(database: 'inexistent_activerecord_unittest') + it "test database exists returns false if database does not exist" do + config = ActiveRecord::Base.configurations["arunit"].merge(database: "inexistent_activerecord_unittest") assert_not ActiveRecord::ConnectionAdapters::SQLServerAdapter.database_exists?(config), - 'expected database to not exist' + "expected database to not exist" end - it 'test database exists returns true when the database exists' do - config = ActiveRecord::Base.configurations['arunit'] + it "test database exists returns true when the database exists" do + config = ActiveRecord::Base.configurations["arunit"] assert ActiveRecord::ConnectionAdapters::SQLServerAdapter.database_exists?(config), "expected database #{config[:database]} to exist" end - describe 'with different language' do + describe "with different language" do before do @default_language = connection.user_options_language @@ -97,18 +97,18 @@ class AdapterTestSQLServer < ActiveRecord::TestCase connection.send :initialize_dateformatter end - it 'memos users dateformat' do + it "memos users dateformat" do connection.execute("SET LANGUAGE us_english") rescue nil dateformat = connection.instance_variable_get(:@database_dateformat) - assert_equal 'mdy', dateformat + assert_equal "mdy", dateformat end - it 'has a dateformatter' do + it "has a dateformatter" do assert Date::DATE_FORMATS[:_sqlserver_dateformat] assert Time::DATE_FORMATS[:_sqlserver_dateformat] end - it 'does a datetime insertion when language is german' do + it "does a datetime insertion when language is german" do connection.execute("SET LANGUAGE deutsch") connection.send :initialize_dateformatter assert_nothing_raised do @@ -120,36 +120,36 @@ class AdapterTestSQLServer < ActiveRecord::TestCase end - describe 'testing #lowercase_schema_reflection' do + describe "testing #lowercase_schema_reflection" do before do SSTestUpper.delete_all - SSTestUpper.create COLUMN1: 'Got a minute?', COLUMN2: 419 - SSTestUpper.create COLUMN1: 'Favorite number?', COLUMN2: 69 + SSTestUpper.create COLUMN1: "Got a minute?", COLUMN2: 419 + SSTestUpper.create COLUMN1: "Favorite number?", COLUMN2: 69 end after do connection.lowercase_schema_reflection = false end - it 'not lowercase schema reflection by default' do - assert SSTestUpper.columns_hash['COLUMN1'] - assert_equal 'Got a minute?', SSTestUpper.first.COLUMN1 - assert_equal 'Favorite number?', SSTestUpper.last.COLUMN1 - assert SSTestUpper.columns_hash['COLUMN2'] + it "not lowercase schema reflection by default" do + assert SSTestUpper.columns_hash["COLUMN1"] + assert_equal "Got a minute?", SSTestUpper.first.COLUMN1 + assert_equal "Favorite number?", SSTestUpper.last.COLUMN1 + assert SSTestUpper.columns_hash["COLUMN2"] end - it 'lowercase schema reflection when set' do + it "lowercase schema reflection when set" do connection.lowercase_schema_reflection = true - assert SSTestUppered.columns_hash['column1'] - assert_equal 'Got a minute?', SSTestUppered.first.column1 - assert_equal 'Favorite number?', SSTestUppered.last.column1 - assert SSTestUppered.columns_hash['column2'] + assert SSTestUppered.columns_hash["column1"] + assert_equal "Got a minute?", SSTestUppered.first.column1 + assert_equal "Favorite number?", SSTestUppered.last.column1 + assert SSTestUppered.columns_hash["column2"] end end - describe 'identity inserts' do + describe "identity inserts" do before do @identity_insert_sql = "INSERT INTO [funny_jokes] ([id],[name]) VALUES(420,'Knock knock')" @@ -160,62 +160,62 @@ class AdapterTestSQLServer < ActiveRecord::TestCase @identity_insert_sql_unordered_sp = "EXEC sp_executesql N'INSERT INTO [funny_jokes] ([name],[id]) VALUES (@0, @1)', N'@0 nvarchar(255), @1 int', @0 = N'Knock knock', @1 = 420" end - it 'return quoted table_name to #query_requires_identity_insert? when INSERT sql contains id column' do - assert_equal 'funny_jokes', connection.send(:query_requires_identity_insert?,@identity_insert_sql) - assert_equal 'funny_jokes', connection.send(:query_requires_identity_insert?,@identity_insert_sql_unquoted) - assert_equal 'funny_jokes', connection.send(:query_requires_identity_insert?,@identity_insert_sql_unordered) - assert_equal 'funny_jokes', connection.send(:query_requires_identity_insert?,@identity_insert_sql_sp) - assert_equal 'funny_jokes', connection.send(:query_requires_identity_insert?,@identity_insert_sql_unquoted_sp) - assert_equal 'funny_jokes', connection.send(:query_requires_identity_insert?,@identity_insert_sql_unordered_sp) + it "return quoted table_name to #query_requires_identity_insert? when INSERT sql contains id column" do + assert_equal "funny_jokes", connection.send(:query_requires_identity_insert?,@identity_insert_sql) + assert_equal "funny_jokes", connection.send(:query_requires_identity_insert?,@identity_insert_sql_unquoted) + assert_equal "funny_jokes", connection.send(:query_requires_identity_insert?,@identity_insert_sql_unordered) + assert_equal "funny_jokes", connection.send(:query_requires_identity_insert?,@identity_insert_sql_sp) + assert_equal "funny_jokes", connection.send(:query_requires_identity_insert?,@identity_insert_sql_unquoted_sp) + assert_equal "funny_jokes", connection.send(:query_requires_identity_insert?,@identity_insert_sql_unordered_sp) end - it 'return false to #query_requires_identity_insert? for normal SQL' do + it "return false to #query_requires_identity_insert? for normal SQL" do [basic_insert_sql, basic_update_sql, basic_select_sql].each do |sql| assert !connection.send(:query_requires_identity_insert?,sql), "SQL was #{sql}" end end - it 'find identity column using #identity_columns' do - task_id_column = Task.columns_hash['id'] + it "find identity column using #identity_columns" do + task_id_column = Task.columns_hash["id"] assert_equal task_id_column.name, connection.send(:identity_columns, Task.table_name).first.name assert_equal task_id_column.sql_type, connection.send(:identity_columns, Task.table_name).first.sql_type end - it 'return an empty array when calling #identity_columns for a table_name with no identity' do + it "return an empty array when calling #identity_columns for a table_name with no identity" do _(connection.send(:identity_columns, Subscriber.table_name)).must_equal [] end end - describe 'quoting' do + describe "quoting" do - it 'return 1 for #quoted_true' do - assert_equal '1', connection.quoted_true + it "return 1 for #quoted_true" do + assert_equal "1", connection.quoted_true end - it 'return 0 for #quoted_false' do - assert_equal '0', connection.quoted_false + it "return 0 for #quoted_false" do + assert_equal "0", connection.quoted_false end - it 'not escape backslash characters like abstract adapter' do + it "not escape backslash characters like abstract adapter" do string_with_backslashs = "\\n" assert_equal string_with_backslashs, connection.quote_string(string_with_backslashs) end - it 'quote column names with brackets' do - assert_equal '[foo]', connection.quote_column_name(:foo) - assert_equal '[foo]', connection.quote_column_name('foo') - assert_equal '[foo].[bar]', connection.quote_column_name('foo.bar') + it "quote column names with brackets" do + assert_equal "[foo]", connection.quote_column_name(:foo) + assert_equal "[foo]", connection.quote_column_name("foo") + assert_equal "[foo].[bar]", connection.quote_column_name("foo.bar") end - it 'not quote already quoted column names with brackets' do - assert_equal '[foo]', connection.quote_column_name('[foo]') - assert_equal '[foo].[bar]', connection.quote_column_name('[foo].[bar]') + it "not quote already quoted column names with brackets" do + assert_equal "[foo]", connection.quote_column_name("[foo]") + assert_equal "[foo].[bar]", connection.quote_column_name("[foo].[bar]") end - it 'quote table names like columns' do - assert_equal '[foo].[bar]', connection.quote_column_name('foo.bar') - assert_equal '[foo].[bar].[baz]', connection.quote_column_name('foo.bar.baz') + it "quote table names like columns" do + assert_equal "[foo].[bar]", connection.quote_column_name("foo.bar") + assert_equal "[foo].[bar].[baz]", connection.quote_column_name("foo.bar.baz") end it "surround string with national prefix" do @@ -228,7 +228,7 @@ class AdapterTestSQLServer < ActiveRecord::TestCase end - describe 'disabling referential integrity' do + describe "disabling referential integrity" do before do connection.disable_referential_integrity { SSTestHasPk.delete_all; SSTestHasFk.delete_all } @@ -236,33 +236,33 @@ class AdapterTestSQLServer < ActiveRecord::TestCase @member = SSTestHasFk.create!(fk_id: @parent.id) end - it 'NOT ALLOW by default the deletion of a referenced parent' do + it "NOT ALLOW by default the deletion of a referenced parent" do SSTestHasPk.connection.disable_referential_integrity { } assert_raise(ActiveRecord::StatementInvalid) { @parent.destroy } end - it 'ALLOW deletion of referenced parent using #disable_referential_integrity block' do + it "ALLOW deletion of referenced parent using #disable_referential_integrity block" do SSTestHasPk.connection.disable_referential_integrity { @parent.destroy } end - it 'again NOT ALLOW deletion of referenced parent after #disable_referential_integrity block' do + it "again NOT ALLOW deletion of referenced parent after #disable_referential_integrity block" do assert_raise(ActiveRecord::StatementInvalid) do SSTestHasPk.connection.disable_referential_integrity { } @parent.destroy end end - it 'not disable referential integrity for the same table twice' do + it "not disable referential integrity for the same table twice" do tables = SSTestHasPk.connection.tables_with_referential_integrity assert_equal tables.size, tables.uniq.size end end - describe 'database statements' do + describe "database statements" do it "run the database consistency checker useroptions command" do - skip 'on azure' if connection_sqlserver_azure? + skip "on azure" if connection_sqlserver_azure? keys = [:textsize, :language, :isolation_level, :dateformat] user_options = connection.user_options keys.each do |key| @@ -272,89 +272,89 @@ class AdapterTestSQLServer < ActiveRecord::TestCase end it "return a underscored key hash with indifferent access of the results" do - skip 'on azure' if connection_sqlserver_azure? + skip "on azure" if connection_sqlserver_azure? user_options = connection.user_options - assert_equal 'read committed', user_options['isolation_level'] - assert_equal 'read committed', user_options[:isolation_level] + assert_equal "read committed", user_options["isolation_level"] + assert_equal "read committed", user_options[:isolation_level] end end - describe 'schema statements' do + describe "schema statements" do - it 'create integers when no limit supplied' do - assert_equal 'integer', connection.type_to_sql(:integer) + it "create integers when no limit supplied" do + assert_equal "integer", connection.type_to_sql(:integer) end - it 'create integers when limit is 4' do - assert_equal 'integer', connection.type_to_sql(:integer, limit: 4) + it "create integers when limit is 4" do + assert_equal "integer", connection.type_to_sql(:integer, limit: 4) end - it 'create integers when limit is 3' do - assert_equal 'integer', connection.type_to_sql(:integer, limit: 3) + it "create integers when limit is 3" do + assert_equal "integer", connection.type_to_sql(:integer, limit: 3) end - it 'create smallints when limit is 2' do - assert_equal 'smallint', connection.type_to_sql(:integer, limit: 2) + it "create smallints when limit is 2" do + assert_equal "smallint", connection.type_to_sql(:integer, limit: 2) end - it 'create tinyints when limit is 1' do - assert_equal 'tinyint', connection.type_to_sql(:integer, limit: 1) + it "create tinyints when limit is 1" do + assert_equal "tinyint", connection.type_to_sql(:integer, limit: 1) end - it 'create bigints when limit is greateer than 4' do - assert_equal 'bigint', connection.type_to_sql(:integer, limit: 5) - assert_equal 'bigint', connection.type_to_sql(:integer, limit: 6) - assert_equal 'bigint', connection.type_to_sql(:integer, limit: 7) - assert_equal 'bigint', connection.type_to_sql(:integer, limit: 8) + it "create bigints when limit is greateer than 4" do + assert_equal "bigint", connection.type_to_sql(:integer, limit: 5) + assert_equal "bigint", connection.type_to_sql(:integer, limit: 6) + assert_equal "bigint", connection.type_to_sql(:integer, limit: 7) + assert_equal "bigint", connection.type_to_sql(:integer, limit: 8) end - it 'create floats when no limit supplied' do - assert_equal 'float', connection.type_to_sql(:float) + it "create floats when no limit supplied" do + assert_equal "float", connection.type_to_sql(:float) end end - describe 'views' do + describe "views" do # Using connection.views - it 'return an array' do + it "return an array" do assert_instance_of Array, connection.views end - it 'find SSTestCustomersView table name' do - _(connection.views).must_include 'sst_customers_view' + it "find SSTestCustomersView table name" do + _(connection.views).must_include "sst_customers_view" end - it 'work with dynamic finders' do - name = 'MetaSkills' + it "work with dynamic finders" do + name = "MetaSkills" customer = SSTestCustomersView.create! name: name assert_equal customer, SSTestCustomersView.find_by_name(name) end - it 'not contain system views' do - systables = ['sysconstraints','syssegments'] + it "not contain system views" do + systables = ["sysconstraints","syssegments"] systables.each do |systable| assert !connection.views.include?(systable), "This systable #{systable} should not be in the views array." end end - it 'allow the connection#view_information method to return meta data on the view' do - view_info = connection.send(:view_information,'sst_customers_view') - assert_equal('sst_customers_view', view_info['TABLE_NAME']) - assert_match(/CREATE VIEW sst_customers_view/, view_info['VIEW_DEFINITION']) + it "allow the connection#view_information method to return meta data on the view" do + view_info = connection.send(:view_information,"sst_customers_view") + assert_equal("sst_customers_view", view_info["TABLE_NAME"]) + assert_match(/CREATE VIEW sst_customers_view/, view_info["VIEW_DEFINITION"]) end - it 'allow the connection#view_table_name method to return true table_name for the view' do - assert_equal 'customers', connection.send(:view_table_name,'sst_customers_view') - assert_equal 'topics', connection.send(:view_table_name,'topics'), 'No view here, the same table name should come back.' + it "allow the connection#view_table_name method to return true table_name for the view" do + assert_equal "customers", connection.send(:view_table_name,"sst_customers_view") + assert_equal "topics", connection.send(:view_table_name,"topics"), "No view here, the same table name should come back." end # With same column names - it 'have matching column objects' do - columns = ['id','name','balance'] + it "have matching column objects" do + columns = ["id","name","balance"] assert !SSTestCustomersView.columns.blank? assert_equal columns.size, SSTestCustomersView.columns.size columns.each do |colname| @@ -364,24 +364,24 @@ class AdapterTestSQLServer < ActiveRecord::TestCase end end - it 'find identity column' do - _(SSTestCustomersView.primary_key).must_equal 'id' - _(connection.primary_key(SSTestCustomersView.table_name)).must_equal 'id' - _(SSTestCustomersView.columns_hash['id']).must_be :is_identity? + it "find identity column" do + _(SSTestCustomersView.primary_key).must_equal "id" + _(connection.primary_key(SSTestCustomersView.table_name)).must_equal "id" + _(SSTestCustomersView.columns_hash["id"]).must_be :is_identity? end - it 'find default values' do + it "find default values" do assert_equal 0, SSTestCustomersView.new.balance end - it 'respond true to data_source_exists?' do + it "respond true to data_source_exists?" do assert SSTestCustomersView.connection.data_source_exists?(SSTestCustomersView.table_name) end # With aliased column names - it 'have matching column objects' do - columns = ['id','pretend_null'] + it "have matching column objects" do + columns = ["id","pretend_null"] assert !SSTestStringDefaultsView.columns.blank? assert_equal columns.size, SSTestStringDefaultsView.columns.size columns.each do |colname| @@ -391,66 +391,66 @@ class AdapterTestSQLServer < ActiveRecord::TestCase end end - it 'find identity column' do - _(SSTestStringDefaultsView.primary_key).must_equal 'id' - _(connection.primary_key(SSTestStringDefaultsView.table_name)).must_equal 'id' - _(SSTestStringDefaultsView.columns_hash['id']).must_be :is_identity? + it "find identity column" do + _(SSTestStringDefaultsView.primary_key).must_equal "id" + _(connection.primary_key(SSTestStringDefaultsView.table_name)).must_equal "id" + _(SSTestStringDefaultsView.columns_hash["id"]).must_be :is_identity? end - it 'find default values' do - assert_equal 'null', SSTestStringDefaultsView.new.pretend_null, - SSTestStringDefaultsView.columns_hash['pretend_null'].inspect + it "find default values" do + assert_equal "null", SSTestStringDefaultsView.new.pretend_null, + SSTestStringDefaultsView.columns_hash["pretend_null"].inspect end - it 'respond true to data_source_exists?' do + it "respond true to data_source_exists?" do assert SSTestStringDefaultsView.connection.data_source_exists?(SSTestStringDefaultsView.table_name) end # That have more than 4000 chars for their defintion - it 'cope with null returned for the defintion' do + it "cope with null returned for the defintion" do assert_nothing_raised() { SSTestStringDefaultsBigView.columns } end - it 'using alternate view defintion still be able to find real default' do - assert_equal 'null', SSTestStringDefaultsBigView.new.pretend_null, - SSTestStringDefaultsBigView.columns_hash['pretend_null'].inspect + it "using alternate view defintion still be able to find real default" do + assert_equal "null", SSTestStringDefaultsBigView.new.pretend_null, + SSTestStringDefaultsBigView.columns_hash["pretend_null"].inspect end end - describe 'database_prefix_remote_server?' do + describe "database_prefix_remote_server?" do after do connection_options.delete(:database_prefix) end - it 'returns false if database_prefix is not configured' do + it "returns false if database_prefix is not configured" do assert_equal false, connection.database_prefix_remote_server? end - it 'returns true if database_prefix has been set' do + it "returns true if database_prefix has been set" do connection_options[:database_prefix] = "server.database.schema." assert_equal true, connection.database_prefix_remote_server? end - it 'returns false if database_prefix has been set incorrectly' do + it "returns false if database_prefix has been set incorrectly" do connection_options[:database_prefix] = "server.database.schema" assert_equal false, connection.database_prefix_remote_server? end end - it 'in_memory_oltp' do - if ENV['IN_MEMORY_OLTP'] && connection.supports_in_memory_oltp? - _(SSTMemory.primary_key).must_equal 'id' - _(SSTMemory.columns_hash['id']).must_be :is_identity? + it "in_memory_oltp" do + if ENV["IN_MEMORY_OLTP"] && connection.supports_in_memory_oltp? + _(SSTMemory.primary_key).must_equal "id" + _(SSTMemory.columns_hash["id"]).must_be :is_identity? else - skip 'supports_in_memory_oltp? => false' + skip "supports_in_memory_oltp? => false" end end - describe 'block writes to a database' do + describe "block writes to a database" do def setup @conn = ActiveRecord::Base.connection @connection_handler = ActiveRecord::Base.connection_handler diff --git a/test/cases/change_column_null_test_sqlserver.rb b/test/cases/change_column_null_test_sqlserver.rb index a4267f263..1cd47de87 100644 --- a/test/cases/change_column_null_test_sqlserver.rb +++ b/test/cases/change_column_null_test_sqlserver.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'migrations/create_clients_and_change_column_null' +require "cases/helper_sqlserver" +require "migrations/create_clients_and_change_column_null" class ChangeColumnNullTestSqlServer < ActiveRecord::TestCase before do @@ -19,25 +19,25 @@ def find_column(table, name) table.find { |column| column.name == name } end - let(:clients_table) { connection.columns('clients') } - let(:name_column) { find_column(clients_table, 'name') } - let(:code_column) { find_column(clients_table, 'code') } - let(:value_column) { find_column(clients_table, 'value') } + let(:clients_table) { connection.columns("clients") } + let(:name_column) { find_column(clients_table, "name") } + let(:code_column) { find_column(clients_table, "code") } + let(:value_column) { find_column(clients_table, "value") } - describe '#change_column_null' do - it 'does not change the column limit' do + describe "#change_column_null" do + it "does not change the column limit" do _(name_column.limit).must_equal 15 end - it 'does not change the column default' do - _(code_column.default).must_equal 'n/a' + it "does not change the column default" do + _(code_column.default).must_equal "n/a" end - it 'does not change the column precision' do + it "does not change the column precision" do _(value_column.precision).must_equal 32 end - it 'does not change the column scale' do + it "does not change the column scale" do _(value_column.scale).must_equal 8 end end diff --git a/test/cases/coerced_tests.rb b/test/cases/coerced_tests.rb index 0e38cd068..0c52cd88b 100644 --- a/test/cases/coerced_tests.rb +++ b/test/cases/coerced_tests.rb @@ -1,10 +1,10 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" -require 'models/event' +require "models/event" class UniquenessValidationTest < ActiveRecord::TestCase # So sp_executesql swallows this exception. Run without prepared to see it. coerce_tests! :test_validate_uniqueness_with_limit @@ -30,7 +30,7 @@ def test_validate_uniqueness_with_limit_and_utf8_coerced coerce_tests! :test_validate_case_sensitive_uniqueness_by_default def test_validate_case_sensitive_uniqueness_by_default_coerced database_collation = connection.select_one("SELECT collation_name FROM sys.databases WHERE name = 'activerecord_unittest'").values.first - skip if database_collation.include?('_CI_') + skip if database_collation.include?("_CI_") original_test_validate_case_sensitive_uniqueness_by_default_coerced end @@ -39,7 +39,7 @@ def test_validate_case_sensitive_uniqueness_by_default_coerced -require 'models/event' +require "models/event" module ActiveRecord class AdapterTest < ActiveRecord::TestCase # I really don`t think we can support legacy binds. @@ -54,7 +54,7 @@ class AdapterTest < ActiveRecord::TestCase def test_value_limit_violations_are_translated_to_specific_exception_coerced connection.unprepared_statement do error = assert_raises(ActiveRecord::ValueTooLong) do - Event.create(title: 'abcdefgh') + Event.create(title: "abcdefgh") end assert_not_nil error.cause end @@ -128,12 +128,12 @@ def test_truncate_tables_with_query_cache -require 'models/topic' +require "models/topic" class AttributeMethodsTest < ActiveRecord::TestCase # Use IFF for boolean statement in SELECT coerce_tests! %r{typecast attribute from select to false} def test_typecast_attribute_from_select_to_false_coerced - Topic.create(:title => 'Budget') + Topic.create(:title => "Budget") topic = Topic.all.merge!(:select => "topics.*, IIF (1 = 2, 1, 0) as is_test").first assert_not_predicate topic, :is_test? end @@ -141,7 +141,7 @@ def test_typecast_attribute_from_select_to_false_coerced # Use IFF for boolean statement in SELECT coerce_tests! %r{typecast attribute from select to true} def test_typecast_attribute_from_select_to_true_coerced - Topic.create(:title => 'Budget') + Topic.create(:title => "Budget") topic = Topic.all.merge!(:select => "topics.*, IIF (1 = 1, 1, 0) as is_test").first assert_predicate topic, :is_test? end @@ -155,7 +155,7 @@ class BasicsTest < ActiveRecord::TestCase coerce_tests! :test_column_names_are_escaped def test_column_names_are_escaped_coerced conn = ActiveRecord::Base.connection - assert_equal '[t]]]', conn.quote_column_name('t]') + assert_equal "[t]]]", conn.quote_column_name("t]") end # Just like PostgreSQLAdapter does. @@ -175,7 +175,7 @@ def test_update_date_time_attributes end def test_update_date_time_attributes_with_default_timezone_local - with_env_tz 'America/New_York' do + with_env_tz "America/New_York" do with_timezone_config default: :local do Time.use_zone("Eastern Time (US & Canada)") do topic = Topic.find(1) @@ -286,7 +286,7 @@ def test_offset_is_kept_coerced coerce_tests! :test_should_return_decimal_average_of_integer_field def test_should_return_decimal_average_of_integer_field_coerced value = Account.average(:id) - assert_equal BigDecimal('3.0').to_s, BigDecimal(value).to_s + assert_equal BigDecimal("3.0").to_s, BigDecimal(value).to_s end # Match SQL Server limit implementation @@ -400,7 +400,7 @@ class ColumnsTest < ActiveRecord::TestCase # Our defaults are real 70000 integers vs '70000' strings. coerce_tests! :test_rename_column_preserves_default_value_not_null def test_rename_column_preserves_default_value_not_null_coerced - add_column 'test_models', 'salary', :integer, :default => 70000 + add_column "test_models", "salary", :integer, :default => 70000 default_before = connection.columns("test_models").find { |c| c.name == "salary" }.default assert_equal 70000, default_before rename_column "test_models", "salary", "annual_salary" @@ -416,9 +416,9 @@ def test_remove_column_with_multi_column_index_coerced add_column "test_models", :hat_size, :integer add_column "test_models", :hat_style, :string, :limit => 100 add_index "test_models", ["hat_style", "hat_size"], :unique => true - assert_equal 1, connection.indexes('test_models').size + assert_equal 1, connection.indexes("test_models").size remove_column("test_models", "hat_size") - assert_equal [], connection.indexes('test_models').map(&:name) + assert_equal [], connection.indexes("test_models").map(&:name) end # Choose `StatementInvalid` vs `ActiveRecordError`. @@ -459,7 +459,7 @@ def test_add_table_with_decimals_coerced assert_not_nil b.my_house_population assert_not_nil b.value_of_e assert_kind_of BigDecimal, b.world_population - assert_equal '6000000000.0', b.world_population.to_s + assert_equal "6000000000.0", b.world_population.to_s assert_kind_of Integer, b.my_house_population assert_equal 3, b.my_house_population assert_kind_of BigDecimal, b.bank_balance @@ -631,7 +631,7 @@ def test_sqlserver_structure_load class DatabaseTasksDumpSchemaCacheTest < ActiveRecord::TestCase # Skip this test with /tmp/my_schema_cache.yml path on Windows. - coerce_tests! :test_dump_schema_cache if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ + coerce_tests! :test_dump_schema_cache if RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ end class DatabaseTasksCreateAllTest < ActiveRecord::TestCase @@ -664,8 +664,8 @@ def test_with_abstract_class_scope_should_be_executed_in_correct_context_coerced -require 'models/post' -require 'models/subscriber' +require "models/post" +require "models/subscriber" class EachTest < ActiveRecord::TestCase # Quoting in tests does not cope with bracket quoting. coerce_tests! :test_find_in_batches_should_quote_batch_order @@ -709,7 +709,7 @@ def test_count_with_include_coerced -require 'models/topic' +require "models/topic" class FinderTest < ActiveRecord::TestCase # We have implicit ordering, via FETCH. coerce_tests! %r{doesn't have implicit ordering}, @@ -737,7 +737,7 @@ def test_take_and_first_and_last_with_integer_should_use_sql_limit_coerced # Can not use array condition due to not finding right type and hence fractional second quoting. coerce_tests! :test_condition_utc_time_interpolation_with_default_timezone_local def test_condition_utc_time_interpolation_with_default_timezone_local_coerced - with_env_tz 'America/New_York' do + with_env_tz "America/New_York" do with_timezone_config default: :local do topic = Topic.first assert_equal topic, Topic.where(written_on: topic.written_on.getutc).first @@ -748,7 +748,7 @@ def test_condition_utc_time_interpolation_with_default_timezone_local_coerced # Can not use array condition due to not finding right type and hence fractional second quoting. coerce_tests! :test_condition_local_time_interpolation_with_default_timezone_utc def test_condition_local_time_interpolation_with_default_timezone_utc_coerced - with_env_tz 'America/New_York' do + with_env_tz "America/New_York" do with_timezone_config default: :utc do topic = Topic.first assert_equal topic, Topic.where(written_on: topic.written_on.getlocal).first @@ -814,12 +814,12 @@ def test_has_one_through_executes_limited_query_coerced -require 'models/company' +require "models/company" class InheritanceTest < ActiveRecord::TestCase # Rails test required inserting to a identity column. coerce_tests! :test_a_bad_type_column def test_a_bad_type_column_coerced - Company.connection.with_identity_insert_enabled('companies') do + Company.connection.with_identity_insert_enabled("companies") do Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')" end assert_raise(ActiveRecord::SubclassNotFound) { Company.find(100) } @@ -846,18 +846,18 @@ class LeftOuterJoinAssociationTest < ActiveRecord::TestCase -require 'models/developer' -require 'models/computer' +require "models/developer" +require "models/computer" class NestedRelationScopingTest < ActiveRecord::TestCase # Assert SQL Server limit implementation coerce_tests! :test_merge_options def test_merge_options_coerced - Developer.where('salary = 80000').scoping do + Developer.where("salary = 80000").scoping do Developer.limit(10).scoping do devs = Developer.all sql = devs.to_sql - assert_match '(salary = 80000)', sql - assert_match 'FETCH NEXT 10 ROWS ONLY', sql + assert_match "(salary = 80000)", sql + assert_match "FETCH NEXT 10 ROWS ONLY", sql end end end @@ -866,7 +866,7 @@ def test_merge_options_coerced -require 'models/topic' +require "models/topic" class PersistenceTest < ActiveRecord::TestCase # Rails test required updating a identity column. coerce_tests! :test_update_columns_changing_id @@ -893,7 +893,7 @@ def test_update_coerced -require 'models/author' +require "models/author" class UpdateAllTest < ActiveRecord::TestCase # Rails test required updating a identity column. coerce_tests! :test_update_all_doesnt_ignore_order @@ -903,17 +903,17 @@ def test_update_all_doesnt_ignore_order_coerced _(mary.id).must_equal 2 _(david.name).wont_equal mary.name assert_sql(/UPDATE.*\(SELECT \[authors\].\[id\] FROM \[authors\].*ORDER BY \[authors\].\[id\]/i) do - Author.where('[id] > 1').order(:id).update_all(name: 'Test') + Author.where("[id] > 1").order(:id).update_all(name: "Test") end - _(david.reload.name).must_equal 'David' - _(mary.reload.name).must_equal 'Test' + _(david.reload.name).must_equal "David" + _(mary.reload.name).must_equal "Test" end end -require 'models/topic' +require "models/topic" module ActiveRecord class PredicateBuilderTest < ActiveRecord::TestCase # Same as original test except string has `N` prefix to indicate unicode string. @@ -948,7 +948,7 @@ def test_create_without_primary_key_no_extra_query_coerced -require 'models/task' +require "models/task" class QueryCacheTest < ActiveRecord::TestCase # SQL Server adapter not in list of supported adapters in original test. coerce_tests! :test_cache_does_not_wrap_results_in_arrays @@ -988,7 +988,7 @@ def test_query_cached_even_when_types_are_reset_coerced -require 'models/post' +require "models/post" class RelationTest < ActiveRecord::TestCase # Use LEN vs LENGTH function. coerce_tests! :test_reverse_order_with_function @@ -1055,7 +1055,7 @@ def test_relations_dont_load_all_records_in_inspect_coerced # Can't apply offset without ORDER coerce_tests! %r{using a custom table affects the wheres} - test 'using a custom table affects the wheres coerced' do + test "using a custom table affects the wheres coerced" do post = posts(:welcome) assert_equal post, custom_post_relation.where!(title: post.title).order(:id).take @@ -1063,7 +1063,7 @@ def test_relations_dont_load_all_records_in_inspect_coerced # Can't apply offset without ORDER coerce_tests! %r{using a custom table with joins affects the joins} - test 'using a custom table with joins affects the joins coerced' do + test "using a custom table with joins affects the joins coerced" do post = posts(:welcome) assert_equal post, custom_post_relation.joins(:author).where!(title: post.title).order(:id).take @@ -1080,7 +1080,7 @@ def test_reverse_arel_assoc_order_with_function_coerced -require 'models/post' +require "models/post" class SanitizeTest < ActiveRecord::TestCase # Use nvarchar string (N'') in assert coerce_tests! :test_sanitize_sql_like_example_use_case @@ -1153,7 +1153,7 @@ class TestAdapterWithInvalidConnection < ActiveRecord::TestCase -require 'models/topic' +require "models/topic" class TransactionTest < ActiveRecord::TestCase # SQL Server does not have query for release_savepoint coerce_tests! :test_releasing_named_savepoints @@ -1170,7 +1170,7 @@ def test_releasing_named_savepoints_coerced -require 'models/tag' +require "models/tag" class TransactionIsolationTest < ActiveRecord::TestCase # SQL Server will lock the table for counts even when both # connections are `READ COMMITTED`. So we bypass with `READPAST`. @@ -1180,7 +1180,7 @@ class TransactionIsolationTest < ActiveRecord::TestCase assert_equal 0, Tag.count Tag2.transaction do Tag2.create - assert_equal 0, Tag.lock('WITH(READPAST)').count + assert_equal 0, Tag.lock("WITH(READPAST)").count end end assert_equal 1, Tag.count @@ -1193,7 +1193,7 @@ class TransactionIsolationTest < ActiveRecord::TestCase -require 'models/book' +require "models/book" class ViewWithPrimaryKeyTest < ActiveRecord::TestCase # We have a few view tables. use includes vs equality. coerce_tests! :test_views @@ -1205,7 +1205,7 @@ def test_views_coerced coerce_tests! :test_does_not_assume_id_column_as_primary_key def test_does_not_assume_id_column_as_primary_key_coerced model = Class.new(ActiveRecord::Base) { self.table_name = "ebooks" } - assert_equal 'id', model.primary_key + assert_equal "id", model.primary_key end end @@ -1223,11 +1223,11 @@ def test_views_coerced -require 'models/author' +require "models/author" class YamlSerializationTest < ActiveRecord::TestCase coerce_tests! :test_types_of_virtual_columns_are_not_changed_on_round_trip def test_types_of_virtual_columns_are_not_changed_on_round_trip_coerced - author = Author.select('authors.*, 5 as posts_count').first + author = Author.select("authors.*, 5 as posts_count").first dumped = YAML.load(YAML.dump(author)) assert_equal 5, author.posts_count assert_equal 5, dumped.posts_count @@ -1379,7 +1379,7 @@ class SchemaCacheTest < ActiveRecord::TestCase private # We need to give the full path for this to work. def schema_dump_path - File.join ARTest::SQLServer.root_activerecord, 'test/assets/schema_dump_5_1.yml' + File.join ARTest::SQLServer.root_activerecord, "test/assets/schema_dump_5_1.yml" end end end @@ -1391,7 +1391,7 @@ def schema_dump_path class UnsafeRawSqlTest < ActiveRecord::TestCase # Use LEN() vs length() function. coerce_tests! %r{order: always allows Arel} - test 'order: always allows Arel' do + test "order: always allows Arel" do ids_depr = with_unsafe_raw_sql_deprecated { Post.order(Arel.sql("len(title)")).pluck(:title) } ids_disabled = with_unsafe_raw_sql_disabled { Post.order(Arel.sql("len(title)")).pluck(:title) } @@ -1441,18 +1441,18 @@ class OptimisticLockingTest < ActiveRecord::TestCase coerce_tests! :test_update_with_dirty_primary_key def test_update_with_dirty_primary_key_coerced assert_raises(ActiveRecord::RecordNotUnique) do - record = StringKeyObject.find('record1') - record.id = 'record2' + record = StringKeyObject.find("record1") + record.id = "record2" record.save! end - record = StringKeyObject.find('record1') - record.id = 'record42' + record = StringKeyObject.find("record1") + record.id = "record42" record.save! - assert StringKeyObject.find('record42') + assert StringKeyObject.find("record42") assert_raises(ActiveRecord::RecordNotFound) do - StringKeyObject.find('record1') + StringKeyObject.find("record1") end end end @@ -1531,7 +1531,7 @@ class EnumTest < ActiveRecord::TestCase -require 'models/task' +require "models/task" class QueryCacheExpiryTest < ActiveRecord::TestCase # SQL Server does not support skipping or upserting duplicates. @@ -1565,7 +1565,7 @@ def test_insert_all_coerced -require 'models/citation' +require "models/citation" class EagerLoadingTooManyIdsTest < ActiveRecord::TestCase # Original Rails test fails with SQL Server error message "The query processor ran out of internal resources and # could not produce a query plan". This error goes away if you change database compatibility level to 110 (SQL 2012) @@ -1627,7 +1627,7 @@ class ReaperTest < ActiveRecord::TestCase class FixturesTest < ActiveRecord::TestCase # Skip test on Windows. Skip can be removed when Rails PR https://github.com/rails/rails/pull/39234 has been merged. - coerce_tests! :test_binary_in_fixtures if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ + coerce_tests! :test_binary_in_fixtures if RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ end @@ -1636,5 +1636,5 @@ class FixturesTest < ActiveRecord::TestCase class ReloadModelsTest < ActiveRecord::TestCase # Skip test on Windows. The number of arguements passed to `IO.popen` in # `activesupport/lib/active_support/testing/isolation.rb` exceeds what Windows can handle. - coerce_tests! :test_has_one_with_reload if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ + coerce_tests! :test_has_one_with_reload if RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ end diff --git a/test/cases/column_test_sqlserver.rb b/test/cases/column_test_sqlserver.rb index 8d74c2908..6b57c7479 100644 --- a/test/cases/column_test_sqlserver.rb +++ b/test/cases/column_test_sqlserver.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class ColumnTestSQLServer < ActiveRecord::TestCase - it '#table_name' do - assert SSTestDatatype.columns.all? { |c| c.table_name == 'sst_datatypes' } - assert SSTestCustomersView.columns.all? { |c| c.table_name == 'customers' } + it "#table_name" do + assert SSTestDatatype.columns.all? { |c| c.table_name == "sst_datatypes" } + assert SSTestCustomersView.columns.all? { |c| c.table_name == "customers" } end - describe 'ActiveRecord::ConnectionAdapters::SQLServer::Type' do + describe "ActiveRecord::ConnectionAdapters::SQLServer::Type" do let(:obj) { SSTestDatatype.new } @@ -28,15 +28,15 @@ def assert_obj_set_and_save(attribute, value) # Exact Numerics - it 'int(4) PRIMARY KEY' do - col = column('id') - _(col.sql_type).must_equal 'int(4)' + it "int(4) PRIMARY KEY" do + col = column("id") + _(col.sql_type).must_equal "int(4)" _(col.null).must_equal false end - it 'bigint(8)' do - col = column('bigint') - _(col.sql_type).must_equal 'bigint(8)' + it "bigint(8)" do + col = column("bigint") + _(col.sql_type).must_equal "bigint(8)" _(col.type).must_equal :integer _(col.null).must_equal true _(col.default).must_equal 42 @@ -49,9 +49,9 @@ def assert_obj_set_and_save(attribute, value) assert_obj_set_and_save :bigint, 9_223_372_036_854_775_807 end - it 'int(4)' do - col = column('int') - _(col.sql_type).must_equal 'int(4)' + it "int(4)" do + col = column("int") + _(col.sql_type).must_equal "int(4)" _(col.type).must_equal :integer _(col.null).must_equal true _(col.default).must_equal 42 @@ -64,9 +64,9 @@ def assert_obj_set_and_save(attribute, value) assert_obj_set_and_save :int, 2_147_483_647 end - it 'smallint(2)' do - col = column('smallint') - _(col.sql_type).must_equal 'smallint(2)' + it "smallint(2)" do + col = column("smallint") + _(col.sql_type).must_equal "smallint(2)" _(col.type).must_equal :integer _(col.null).must_equal true _(col.default).must_equal 42 @@ -79,9 +79,9 @@ def assert_obj_set_and_save(attribute, value) assert_obj_set_and_save :smallint, 32_767 end - it 'tinyint(1)' do - col = column('tinyint') - _(col.sql_type).must_equal 'tinyint(1)' + it "tinyint(1)" do + col = column("tinyint") + _(col.sql_type).must_equal "tinyint(1)" _(col.type).must_equal :integer _(col.null).must_equal true _(col.default).must_equal 42 @@ -94,9 +94,9 @@ def assert_obj_set_and_save(attribute, value) assert_obj_set_and_save :tinyint, 255 end - it 'bit' do - col = column('bit') - _(col.sql_type).must_equal 'bit' + it "bit" do + col = column("bit") + _(col.sql_type).must_equal "bit" _(col.type).must_equal :boolean _(col.null).must_equal true _(col.default).must_equal true @@ -109,129 +109,129 @@ def assert_obj_set_and_save(attribute, value) _(obj.bit).must_equal false obj.save! _(obj.reload.bit).must_equal false - obj.bit = '1' + obj.bit = "1" _(obj.bit).must_equal true obj.save! _(obj.reload.bit).must_equal true end - it 'decimal(9,2)' do - col = column('decimal_9_2') - _(col.sql_type).must_equal 'decimal(9,2)' + it "decimal(9,2)" do + col = column("decimal_9_2") + _(col.sql_type).must_equal "decimal(9,2)" _(col.type).must_equal :decimal _(col.null).must_equal true - _(col.default).must_equal BigDecimal('12345.01') - _(obj.decimal_9_2).must_equal BigDecimal('12345.01') + _(col.default).must_equal BigDecimal("12345.01") + _(obj.decimal_9_2).must_equal BigDecimal("12345.01") _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::Decimal _(type.limit).must_be_nil _(type.precision).must_equal 9 _(type.scale).must_equal 2 - obj.decimal_9_2 = '1234567.8901' - _(obj.decimal_9_2).must_equal BigDecimal('1234567.89') + obj.decimal_9_2 = "1234567.8901" + _(obj.decimal_9_2).must_equal BigDecimal("1234567.89") obj.save! - _(obj.reload.decimal_9_2).must_equal BigDecimal('1234567.89') + _(obj.reload.decimal_9_2).must_equal BigDecimal("1234567.89") end - it 'decimal(16,4)' do - col = column('decimal_16_4') - _(col.sql_type).must_equal 'decimal(16,4)' - _(col.default).must_equal BigDecimal('1234567.89') - _(obj.decimal_16_4).must_equal BigDecimal('1234567.89') + it "decimal(16,4)" do + col = column("decimal_16_4") + _(col.sql_type).must_equal "decimal(16,4)" + _(col.default).must_equal BigDecimal("1234567.89") + _(obj.decimal_16_4).must_equal BigDecimal("1234567.89") _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type.precision).must_equal 16 _(type.scale).must_equal 4 - obj.decimal_16_4 = '1234567.8901001' - _(obj.decimal_16_4).must_equal BigDecimal('1234567.8901') + obj.decimal_16_4 = "1234567.8901001" + _(obj.decimal_16_4).must_equal BigDecimal("1234567.8901") obj.save! - _(obj.reload.decimal_16_4).must_equal BigDecimal('1234567.8901') + _(obj.reload.decimal_16_4).must_equal BigDecimal("1234567.8901") end - it 'numeric(18,0)' do - col = column('numeric_18_0') - _(col.sql_type).must_equal 'numeric(18,0)' + it "numeric(18,0)" do + col = column("numeric_18_0") + _(col.sql_type).must_equal "numeric(18,0)" _(col.type).must_equal :decimal _(col.null).must_equal true - _(col.default).must_equal BigDecimal('191') - _(obj.numeric_18_0).must_equal BigDecimal('191') + _(col.default).must_equal BigDecimal("191") + _(obj.numeric_18_0).must_equal BigDecimal("191") _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::Decimal _(type.limit).must_be_nil _(type.precision).must_equal 18 _(type.scale).must_equal 0 - obj.numeric_18_0 = '192.1' - _(obj.numeric_18_0).must_equal BigDecimal('192') + obj.numeric_18_0 = "192.1" + _(obj.numeric_18_0).must_equal BigDecimal("192") obj.save! - _(obj.reload.numeric_18_0).must_equal BigDecimal('192') + _(obj.reload.numeric_18_0).must_equal BigDecimal("192") end - it 'numeric(36,2)' do - col = column('numeric_36_2') - _(col.sql_type).must_equal 'numeric(36,2)' + it "numeric(36,2)" do + col = column("numeric_36_2") + _(col.sql_type).must_equal "numeric(36,2)" _(col.type).must_equal :decimal _(col.null).must_equal true - _(col.default).must_equal BigDecimal('12345678901234567890.01') - _(obj.numeric_36_2).must_equal BigDecimal('12345678901234567890.01') + _(col.default).must_equal BigDecimal("12345678901234567890.01") + _(obj.numeric_36_2).must_equal BigDecimal("12345678901234567890.01") _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::Decimal _(type.limit).must_be_nil _(type.precision).must_equal 36 _(type.scale).must_equal 2 - obj.numeric_36_2 = '192.123' - _(obj.numeric_36_2).must_equal BigDecimal('192.12') + obj.numeric_36_2 = "192.123" + _(obj.numeric_36_2).must_equal BigDecimal("192.12") obj.save! - _(obj.reload.numeric_36_2).must_equal BigDecimal('192.12') + _(obj.reload.numeric_36_2).must_equal BigDecimal("192.12") end - it 'money' do - col = column('money') - _(col.sql_type).must_equal 'money' + it "money" do + col = column("money") + _(col.sql_type).must_equal "money" _(col.type).must_equal :money _(col.null).must_equal true - _(col.default).must_equal BigDecimal('4.20') - _(obj.money).must_equal BigDecimal('4.20') + _(col.default).must_equal BigDecimal("4.20") + _(obj.money).must_equal BigDecimal("4.20") _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::Money _(type.limit).must_be_nil _(type.precision).must_equal 19 _(type.scale).must_equal 4 - obj.money = '922337203685477.58061' - _(obj.money).must_equal BigDecimal('922337203685477.5806') + obj.money = "922337203685477.58061" + _(obj.money).must_equal BigDecimal("922337203685477.5806") obj.save! - _(obj.reload.money).must_equal BigDecimal('922337203685477.5806') + _(obj.reload.money).must_equal BigDecimal("922337203685477.5806") end - it 'smallmoney' do - col = column('smallmoney') - _(col.sql_type).must_equal 'smallmoney' + it "smallmoney" do + col = column("smallmoney") + _(col.sql_type).must_equal "smallmoney" _(col.type).must_equal :smallmoney _(col.null).must_equal true - _(col.default).must_equal BigDecimal('4.20') - _(obj.smallmoney).must_equal BigDecimal('4.20') + _(col.default).must_equal BigDecimal("4.20") + _(obj.smallmoney).must_equal BigDecimal("4.20") _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::SmallMoney _(type.limit).must_be_nil _(type.precision).must_equal 10 _(type.scale).must_equal 4 - obj.smallmoney = '214748.36461' - _(obj.smallmoney).must_equal BigDecimal('214748.3646') + obj.smallmoney = "214748.36461" + _(obj.smallmoney).must_equal BigDecimal("214748.3646") obj.save! - _(obj.reload.smallmoney).must_equal BigDecimal('214748.3646') + _(obj.reload.smallmoney).must_equal BigDecimal("214748.3646") end # Approximate Numerics # Float limits are adjusted to 24 or 53 by the database as per http://msdn.microsoft.com/en-us/library/ms173773.aspx # Floats with a limit of <= 24 are reduced to reals by sqlserver on creation. - it 'float' do - col = column('float') - _(col.sql_type).must_equal 'float' + it "float" do + col = column("float") + _(col.sql_type).must_equal "float" _(col.type).must_equal :float _(col.null).must_equal true _(col.default).must_equal 123.00000001 @@ -242,15 +242,15 @@ def assert_obj_set_and_save(attribute, value) _(type.limit).must_be_nil _(type.precision).must_be_nil _(type.scale).must_be_nil - obj.float = '214748.36461' + obj.float = "214748.36461" _(obj.float).must_equal 214748.36461 obj.save! _(obj.reload.float).must_equal 214748.36461 end - it 'real' do - col = column('real') - _(col.sql_type).must_equal 'real' + it "real" do + col = column("real") + _(col.sql_type).must_equal "real" _(col.type).must_equal :real _(col.null).must_equal true _(col.default).must_be_close_to 123.45, 0.01 @@ -261,7 +261,7 @@ def assert_obj_set_and_save(attribute, value) _(type.limit).must_be_nil _(type.precision).must_be_nil _(type.scale).must_be_nil - obj.real = '214748.36461' + obj.real = "214748.36461" _(obj.real).must_be_close_to 214748.36461, 0.01 obj.save! _(obj.reload.real).must_be_close_to 214748.36461, 0.01 @@ -269,12 +269,12 @@ def assert_obj_set_and_save(attribute, value) # Date and Time - it 'date' do - col = column('date') - _(col.sql_type).must_equal 'date' + it "date" do + col = column("date") + _(col.sql_type).must_equal "date" _(col.type).must_equal :date _(col.null).must_equal true - _(col.default).must_equal connection_dblib_73? ? Date.civil(0001, 1, 1) : '0001-01-01' + _(col.default).must_equal connection_dblib_73? ? Date.civil(0001, 1, 1) : "0001-01-01" _(obj.date).must_equal Date.civil(0001, 1, 1) _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) @@ -283,14 +283,14 @@ def assert_obj_set_and_save(attribute, value) _(type.precision).must_be_nil _(type.scale).must_be_nil # Can cast strings. SQL Server format. - obj.date = '04-01-0001' + obj.date = "04-01-0001" _(obj.date).must_equal Date.civil(0001, 4, 1) obj.save! _(obj.date).must_equal Date.civil(0001, 4, 1) obj.reload _(obj.date).must_equal Date.civil(0001, 4, 1) # Can cast strings. ISO format. - obj.date = '0001-04-01' + obj.date = "0001-04-01" _(obj.date).must_equal Date.civil(0001, 4, 1) obj.save! _(obj.date).must_equal Date.civil(0001, 4, 1) @@ -305,9 +305,9 @@ def assert_obj_set_and_save(attribute, value) _(obj.reload.date).must_equal Date.civil(2010, 4, 14) end - it 'datetime' do - col = column('datetime') - _(col.sql_type).must_equal 'datetime' + it "datetime" do + col = column("datetime") + _(col.sql_type).must_equal "datetime" _(col.type).must_equal :datetime _(col.null).must_equal true time = Time.utc 1753, 01, 01, 00, 00, 00, 123000 @@ -349,10 +349,10 @@ def assert_obj_set_and_save(attribute, value) _(obj).must_equal obj.class.where(datetime: nil).first end - it 'datetime2' do - skip 'datetime2 not supported in this protocol version' unless connection_dblib_73? - col = column('datetime2_7') - _(col.sql_type).must_equal 'datetime2(7)' + it "datetime2" do + skip "datetime2 not supported in this protocol version" unless connection_dblib_73? + col = column("datetime2_7") + _(col.sql_type).must_equal "datetime2(7)" _(col.type).must_equal :datetime _(col.null).must_equal true time = Time.utc 9999, 12, 31, 23, 59, 59, Rational(999999900, 1000) @@ -388,7 +388,7 @@ def assert_obj_set_and_save(attribute, value) _(obj).must_equal obj.class.where(datetime2_7: time2).first # datetime2_3 time = Time.utc 9999, 12, 31, 23, 59, 59, Rational(123456789, 1000) - col = column('datetime2_3') + col = column("datetime2_3") _(connection.lookup_cast_type_from_column(col).precision).must_equal 3 obj.datetime2_3 = time _(obj.datetime2_3).must_equal time.change(nsec: 123000000), "Nanoseconds were <#{obj.datetime2_3.nsec}> vs <123000000>" @@ -396,7 +396,7 @@ def assert_obj_set_and_save(attribute, value) _(obj.datetime2_3).must_equal time.change(nsec: 123000000), "Nanoseconds were <#{obj.datetime2_3.nsec}> vs <123000000>" _(obj).must_equal obj.class.where(datetime2_3: time).first # datetime2_1 - col = column('datetime2_1') + col = column("datetime2_1") _(connection.lookup_cast_type_from_column(col).precision).must_equal 1 obj.datetime2_1 = time _(obj.datetime2_1).must_equal time.change(nsec: 100000000), "Nanoseconds were <#{obj.datetime2_1.nsec}> vs <100000000>" @@ -404,7 +404,7 @@ def assert_obj_set_and_save(attribute, value) _(obj.datetime2_1).must_equal time.change(nsec: 100000000), "Nanoseconds were <#{obj.datetime2_1.nsec}> vs <100000000>" _(obj).must_equal obj.class.where(datetime2_1: time).first # datetime2_0 - col = column('datetime2_0') + col = column("datetime2_0") _(connection.lookup_cast_type_from_column(col).precision).must_equal 0 time = Time.utc 2016, 4, 19, 16, 45, 40, 771036 obj.datetime2_0 = time @@ -414,10 +414,10 @@ def assert_obj_set_and_save(attribute, value) _(obj).must_equal obj.class.where(datetime2_0: time).first end - it 'datetimeoffset' do - skip 'datetimeoffset not supported in this protocol version' unless connection_dblib_73? - col = column('datetimeoffset_7') - _(col.sql_type).must_equal 'datetimeoffset(7)' + it "datetimeoffset" do + skip "datetimeoffset not supported in this protocol version" unless connection_dblib_73? + col = column("datetimeoffset_7") + _(col.sql_type).must_equal "datetimeoffset(7)" _(col.type).must_equal :datetimeoffset _(col.null).must_equal true _(col.default).must_equal Time.new(1984, 01, 24, 04, 20, 00, -28800).change(nsec: 123456700), "Nanoseconds <#{col.default.nsec}> vs <123456700>" @@ -436,21 +436,21 @@ def assert_obj_set_and_save(attribute, value) obj.reload _(obj.datetimeoffset_7).must_equal Time.new(2010, 04, 01, 12, 34, 56, +18000).change(nsec: 123456800), "Nanoseconds were <#{obj.datetimeoffset_7.nsec}> vs <123456800>" # Maintains the timezone - time = ActiveSupport::TimeZone['America/Los_Angeles'].local 2010, 12, 31, 23, 59, 59, Rational(123456800, 1000) + time = ActiveSupport::TimeZone["America/Los_Angeles"].local 2010, 12, 31, 23, 59, 59, Rational(123456800, 1000) obj.datetimeoffset_7 = time _(obj.datetimeoffset_7).must_equal time obj.save! _(obj.datetimeoffset_7).must_equal time _(obj.reload.datetimeoffset_7).must_equal time # With other precisions. - time = ActiveSupport::TimeZone['America/Los_Angeles'].local 2010, 12, 31, 23, 59, 59, Rational(123456755, 1000) - col = column('datetimeoffset_3') + time = ActiveSupport::TimeZone["America/Los_Angeles"].local 2010, 12, 31, 23, 59, 59, Rational(123456755, 1000) + col = column("datetimeoffset_3") _(connection.lookup_cast_type_from_column(col).precision).must_equal 3 obj.datetimeoffset_3 = time _(obj.datetimeoffset_3).must_equal time.change(nsec: 123000000), "Nanoseconds were <#{obj.datetimeoffset_3.nsec}> vs <123000000>" obj.save! _(obj.datetimeoffset_3).must_equal time.change(nsec: 123000000), "Nanoseconds were <#{obj.datetimeoffset_3.nsec}> vs <123000000>" - col = column('datetime2_1') + col = column("datetime2_1") _(connection.lookup_cast_type_from_column(col).precision).must_equal 1 obj.datetime2_1 = time _(obj.datetime2_1).must_equal time.change(nsec: 100000000), "Nanoseconds were <#{obj.datetime2_1.nsec}> vs <100000000>" @@ -458,9 +458,9 @@ def assert_obj_set_and_save(attribute, value) _(obj.datetime2_1).must_equal time.change(nsec: 100000000), "Nanoseconds were <#{obj.datetime2_1.nsec}> vs <100000000>" end - it 'smalldatetime' do - col = column('smalldatetime') - _(col.sql_type).must_equal 'smalldatetime' + it "smalldatetime" do + col = column("smalldatetime") + _(col.sql_type).must_equal "smalldatetime" _(col.type).must_equal :smalldatetime _(col.null).must_equal true _(col.default).must_equal Time.utc(1901, 01, 01, 15, 45, 00, 000) @@ -480,10 +480,10 @@ def assert_obj_set_and_save(attribute, value) _(obj.smalldatetime).must_equal Time.utc(2078, 06, 05, 4, 20, 00, 0), "Microseconds were <#{obj.reload.smalldatetime.usec}> vs <0>" end - it 'time(7)' do - skip 'time() not supported in this protocol version' unless connection_dblib_73? - col = column('time_7') - _(col.sql_type).must_equal 'time(7)' + it "time(7)" do + skip "time() not supported in this protocol version" unless connection_dblib_73? + col = column("time_7") + _(col.sql_type).must_equal "time(7)" _(col.type).must_equal :time _(col.null).must_equal true _(col.default).must_equal Time.utc(1900, 01, 01, 04, 20, 00, Rational(288321500, 1000)), "Nanoseconds were <#{col.default.nsec}> vs <288321500>" @@ -512,10 +512,10 @@ def assert_obj_set_and_save(attribute, value) _(obj.time_7).must_equal Time.utc(2000, 01, 01, 15, 45, 00, Rational(288321500, 1000)), "Nanoseconds were <#{obj.time_7.nsec}> vs <288321500>" end - it 'time(2)' do - skip 'time() not supported in this protocol version' unless connection_dblib_73? - col = column('time_2') - _(col.sql_type).must_equal 'time(2)' + it "time(2)" do + skip "time() not supported in this protocol version" unless connection_dblib_73? + col = column("time_2") + _(col.sql_type).must_equal "time(2)" _(col.type).must_equal :time _(col.null).must_equal true _(col.default).must_be_nil @@ -542,10 +542,10 @@ def assert_obj_set_and_save(attribute, value) _(obj.time_2).must_equal Time.utc(2000, 01, 01, 15, 45, 00, 0), "Microseconds were <#{obj.time_2.usec}> vs <0>" end - it 'time using default precision' do - skip 'time() not supported in this protocol version' unless connection_dblib_73? - col = column('time_default') - _(col.sql_type).must_equal 'time(7)' + it "time using default precision" do + skip "time() not supported in this protocol version" unless connection_dblib_73? + col = column("time_default") + _(col.sql_type).must_equal "time(7)" _(col.type).must_equal :time _(col.null).must_equal true _(col.default).must_equal Time.utc(1900, 01, 01, 15, 03, 42, Rational(62197800, 1000)), "Nanoseconds were <#{col.default.nsec}> vs <62197800>" @@ -576,13 +576,13 @@ def assert_obj_set_and_save(attribute, value) # Character Strings - it 'char(10)' do - col = column('char_10') - _(col.sql_type).must_equal 'char(10)' + it "char(10)" do + col = column("char_10") + _(col.sql_type).must_equal "char(10)" _(col.type).must_equal :char _(col.null).must_equal true - _(col.default).must_equal '1234567890' - _(obj.char_10).must_equal '1234567890' + _(col.default).must_equal "1234567890" + _(obj.char_10).must_equal "1234567890" _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::Char @@ -590,19 +590,19 @@ def assert_obj_set_and_save(attribute, value) _(type.precision).must_be_nil _(type.scale).must_be_nil # Basic set and save. - obj.char_10 = '012345' - _(obj.char_10.strip).must_equal '012345' + obj.char_10 = "012345" + _(obj.char_10.strip).must_equal "012345" obj.save! - _(obj.reload.char_10.strip).must_equal '012345' + _(obj.reload.char_10.strip).must_equal "012345" end - it 'varchar(50)' do - col = column('varchar_50') - _(col.sql_type).must_equal 'varchar(50)' + it "varchar(50)" do + col = column("varchar_50") + _(col.sql_type).must_equal "varchar(50)" _(col.type).must_equal :varchar _(col.null).must_equal true - _(col.default).must_equal 'test varchar_50' - _(obj.varchar_50).must_equal 'test varchar_50' + _(col.default).must_equal "test varchar_50" + _(obj.varchar_50).must_equal "test varchar_50" _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::Varchar @@ -610,16 +610,16 @@ def assert_obj_set_and_save(attribute, value) _(type.precision).must_be_nil _(type.scale).must_be_nil # Basic set and save. - assert_obj_set_and_save :varchar_50, 'Hello World' + assert_obj_set_and_save :varchar_50, "Hello World" end - it 'varchar(max)' do - col = column('varchar_max') - _(col.sql_type).must_equal 'varchar(max)' + it "varchar(max)" do + col = column("varchar_max") + _(col.sql_type).must_equal "varchar(max)" _(col.type).must_equal :varchar_max _(col.null).must_equal true - _(col.default).must_equal 'test varchar_max' - _(obj.varchar_max).must_equal 'test varchar_max' + _(col.default).must_equal "test varchar_max" + _(obj.varchar_max).must_equal "test varchar_max" _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::VarcharMax @@ -627,16 +627,16 @@ def assert_obj_set_and_save(attribute, value) _(type.precision).must_be_nil _(type.scale).must_be_nil # Basic set and save. - assert_obj_set_and_save :varchar_max, 'Hello World' + assert_obj_set_and_save :varchar_max, "Hello World" end - it 'text' do - col = column('text') - _(col.sql_type).must_equal 'text' + it "text" do + col = column("text") + _(col.sql_type).must_equal "text" _(col.type).must_equal :text_basic _(col.null).must_equal true - _(col.default).must_equal 'test text' - _(obj.text).must_equal 'test text' + _(col.default).must_equal "test text" + _(obj.text).must_equal "test text" _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::Text @@ -644,18 +644,18 @@ def assert_obj_set_and_save(attribute, value) _(type.precision).must_be_nil _(type.scale).must_be_nil # Basic set and save. - assert_obj_set_and_save :text, 'Hello World' + assert_obj_set_and_save :text, "Hello World" end # Unicode Character Strings - it 'nchar(10)' do - col = column('nchar_10') - _(col.sql_type).must_equal 'nchar(10)' + it "nchar(10)" do + col = column("nchar_10") + _(col.sql_type).must_equal "nchar(10)" _(col.type).must_equal :nchar _(col.null).must_equal true - _(col.default).must_equal '12345678åå' - _(obj.nchar_10).must_equal '12345678åå' + _(col.default).must_equal "12345678åå" + _(obj.nchar_10).must_equal "12345678åå" _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::UnicodeChar @@ -669,13 +669,13 @@ def assert_obj_set_and_save(attribute, value) _(obj.reload.nchar_10.strip).must_equal "五六" end - it 'nvarchar(50)' do - col = column('nvarchar_50') - _(col.sql_type).must_equal 'nvarchar(50)' + it "nvarchar(50)" do + col = column("nvarchar_50") + _(col.sql_type).must_equal "nvarchar(50)" _(col.type).must_equal :string _(col.null).must_equal true - _(col.default).must_equal 'test nvarchar_50 åå' - _(obj.nvarchar_50).must_equal 'test nvarchar_50 åå' + _(col.default).must_equal "test nvarchar_50 åå" + _(obj.nvarchar_50).must_equal "test nvarchar_50 åå" _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::UnicodeVarchar @@ -686,13 +686,13 @@ def assert_obj_set_and_save(attribute, value) assert_obj_set_and_save :nvarchar_50, "一二34五六" end - it 'nvarchar(max)' do - col = column('nvarchar_max') - _(col.sql_type).must_equal 'nvarchar(max)' + it "nvarchar(max)" do + col = column("nvarchar_max") + _(col.sql_type).must_equal "nvarchar(max)" _(col.type).must_equal :text _(col.null).must_equal true - _(col.default).must_equal 'test nvarchar_max åå' - _(obj.nvarchar_max).must_equal 'test nvarchar_max åå' + _(col.default).must_equal "test nvarchar_max åå" + _(obj.nvarchar_max).must_equal "test nvarchar_max åå" _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::UnicodeVarcharMax @@ -703,13 +703,13 @@ def assert_obj_set_and_save(attribute, value) assert_obj_set_and_save :nvarchar_max, "一二34五六" end - it 'ntext' do - col = column('ntext') - _(col.sql_type).must_equal 'ntext' + it "ntext" do + col = column("ntext") + _(col.sql_type).must_equal "ntext" _(col.type).must_equal :ntext _(col.null).must_equal true - _(col.default).must_equal 'test ntext åå' - _(obj.ntext).must_equal 'test ntext åå' + _(col.default).must_equal "test ntext åå" + _(obj.ntext).must_equal "test ntext åå" _(col.default_function).must_be_nil type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::UnicodeText @@ -722,12 +722,12 @@ def assert_obj_set_and_save(attribute, value) # Binary Strings - let(:binary_file) { File.join ARTest::SQLServer.test_root_sqlserver, 'fixtures', '1px.gif' } - let(:binary_data) { File.open(binary_file, 'rb') { |f| f.read } } + let(:binary_file) { File.join ARTest::SQLServer.test_root_sqlserver, "fixtures", "1px.gif" } + let(:binary_data) { File.open(binary_file, "rb") { |f| f.read } } - it 'binary(49)' do - col = column('binary_49') - _(col.sql_type).must_equal 'binary(49)' + it "binary(49)" do + col = column("binary_49") + _(col.sql_type).must_equal "binary(49)" _(col.type).must_equal :binary_basic _(col.null).must_equal true _(col.default).must_be_nil @@ -746,9 +746,9 @@ def assert_obj_set_and_save(attribute, value) _(obj.reload.binary_49).must_equal binary_data end - it 'varbinary(49)' do - col = column('varbinary_49') - _(col.sql_type).must_equal 'varbinary(49)' + it "varbinary(49)" do + col = column("varbinary_49") + _(col.sql_type).must_equal "varbinary(49)" _(col.type).must_equal :varbinary _(col.null).must_equal true _(col.default).must_be_nil @@ -767,9 +767,9 @@ def assert_obj_set_and_save(attribute, value) _(obj.reload.varbinary_49).must_equal binary_data_20 end - it 'varbinary(max)' do - col = column('varbinary_max') - _(col.sql_type).must_equal 'varbinary(max)' + it "varbinary(max)" do + col = column("varbinary_max") + _(col.sql_type).must_equal "varbinary(max)" _(col.type).must_equal :binary _(col.null).must_equal true _(col.default).must_be_nil @@ -786,13 +786,13 @@ def assert_obj_set_and_save(attribute, value) # Other Data Types - it 'uniqueidentifier' do - col = column('uniqueidentifier') - _(col.sql_type).must_equal 'uniqueidentifier' + it "uniqueidentifier" do + col = column("uniqueidentifier") + _(col.sql_type).must_equal "uniqueidentifier" _(col.type).must_equal :uuid _(col.null).must_equal true _(col.default).must_be_nil - _(col.default_function).must_equal 'newid()' + _(col.default_function).must_equal "newid()" type = connection.lookup_cast_type_from_column(col) _(type).must_be_instance_of Type::Uuid _(type.limit).must_be_nil @@ -809,9 +809,9 @@ def assert_obj_set_and_save(attribute, value) _(obj.uniqueidentifier).must_equal "6F9619FF-8B86-D011-B42D-00C04FC964FF" end - it 'timestamp' do - col = column('timestamp') - _(col.sql_type).must_equal 'timestamp' + it "timestamp" do + col = column("timestamp") + _(col.sql_type).must_equal "timestamp" _(col.type).must_equal :ss_timestamp _(col.null).must_equal true _(col.default).must_be_nil @@ -831,7 +831,7 @@ def assert_obj_set_and_save(attribute, value) obj.save! end - it 'does not mark object as changed after save' do + it "does not mark object as changed after save" do obj.save! obj.attributes _(obj.changed?).must_equal false diff --git a/test/cases/connection_test_sqlserver.rb b/test/cases/connection_test_sqlserver.rb index 56e691ff4..7309506c4 100644 --- a/test/cases/connection_test_sqlserver.rb +++ b/test/cases/connection_test_sqlserver.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/reply' -require 'models/topic' +require "cases/helper_sqlserver" +require "models/reply" +require "models/topic" class ConnectionTestSQLServer < ActiveRecord::TestCase @@ -15,7 +15,7 @@ class ConnectionTestSQLServer < ActiveRecord::TestCase assert connection.active? end - it 'affect rows' do + it "affect rows" do topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } } updated = Topic.update(topic_data.keys, topic_data.values) assert_equal 2, updated.size @@ -24,34 +24,34 @@ class ConnectionTestSQLServer < ActiveRecord::TestCase assert_equal 2, Topic.delete([1, 2]) end - it 'allow usage of :database connection option to remove setting from dsn' do - assert_equal 'activerecord_unittest', connection.current_database + it "allow usage of :database connection option to remove setting from dsn" do + assert_equal "activerecord_unittest", connection.current_database begin - connection.use_database('activerecord_unittest2') - assert_equal 'activerecord_unittest2', connection.current_database + connection.use_database("activerecord_unittest2") + assert_equal "activerecord_unittest2", connection.current_database ensure connection.use_database - assert_equal 'activerecord_unittest', connection.current_database, 'Would default back to connection options' + assert_equal "activerecord_unittest", connection.current_database, "Would default back to connection options" end end unless connection_sqlserver_azure? - describe 'Connection management' do + describe "Connection management" do - it 'set spid on connect' do - _(['Fixnum', 'Integer']).must_include connection.spid.class.name + it "set spid on connect" do + _(["Fixnum", "Integer"]).must_include connection.spid.class.name end - it 'reset spid on disconnect!' do + it "reset spid on disconnect!" do connection.disconnect! assert connection.spid.nil? end - it 'reset the connection' do + it "reset the connection" do connection.disconnect! _(connection.raw_connection).must_be_nil end - it 'be able to disconnect and reconnect at will' do + it "be able to disconnect and reconnect at will" do disconnect_raw_connection! assert !connection.active? connection.reconnect! diff --git a/test/cases/execute_procedure_test_sqlserver.rb b/test/cases/execute_procedure_test_sqlserver.rb index 7cdfa984f..46d1774c3 100644 --- a/test/cases/execute_procedure_test_sqlserver.rb +++ b/test/cases/execute_procedure_test_sqlserver.rb @@ -1,45 +1,45 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class ExecuteProcedureTestSQLServer < ActiveRecord::TestCase - it 'execute a simple procedure' do + it "execute a simple procedure" do tables = ActiveRecord::Base.execute_procedure :sp_tables assert_instance_of Array, tables assert tables.first.respond_to?(:keys) end - it 'take parameter arguments' do - tables = ActiveRecord::Base.execute_procedure :sp_tables, 'sst_datatypes' + it "take parameter arguments" do + tables = ActiveRecord::Base.execute_procedure :sp_tables, "sst_datatypes" table_info = tables.first assert_equal 1, tables.size - assert_equal (ENV['ARUNIT_DB_NAME'] || 'activerecord_unittest'), table_info['TABLE_QUALIFIER'], "Table Info: #{table_info.inspect}" - assert_equal 'TABLE', table_info['TABLE_TYPE'], "Table Info: #{table_info.inspect}" + assert_equal (ENV["ARUNIT_DB_NAME"] || "activerecord_unittest"), table_info["TABLE_QUALIFIER"], "Table Info: #{table_info.inspect}" + assert_equal "TABLE", table_info["TABLE_TYPE"], "Table Info: #{table_info.inspect}" end - it 'allow multiple result sets to be returned' do - results1, results2 = ActiveRecord::Base.execute_procedure('sp_helpconstraint','accounts') + it "allow multiple result sets to be returned" do + results1, results2 = ActiveRecord::Base.execute_procedure("sp_helpconstraint","accounts") assert_instance_of Array, results1 assert results1.first.respond_to?(:keys) - assert results1.first['Object Name'] + assert results1.first["Object Name"] assert_instance_of Array, results2 assert results2.first.respond_to?(:keys) - assert results2.first['constraint_name'] - assert results2.first['constraint_type'] + assert results2.first["constraint_name"] + assert results2.first["constraint_type"] end - it 'take named parameter arguments' do - tables = ActiveRecord::Base.execute_procedure :sp_tables, table_name: 'tables', table_owner: 'sys' + it "take named parameter arguments" do + tables = ActiveRecord::Base.execute_procedure :sp_tables, table_name: "tables", table_owner: "sys" table_info = tables.first assert_equal 1, tables.size - assert_equal (ENV['ARUNIT_DB_NAME'] || 'activerecord_unittest'), table_info['TABLE_QUALIFIER'], "Table Info: #{table_info.inspect}" - assert_equal 'VIEW', table_info['TABLE_TYPE'], "Table Info: #{table_info.inspect}" + assert_equal (ENV["ARUNIT_DB_NAME"] || "activerecord_unittest"), table_info["TABLE_QUALIFIER"], "Table Info: #{table_info.inspect}" + assert_equal "VIEW", table_info["TABLE_TYPE"], "Table Info: #{table_info.inspect}" end - it 'uses the proper timezone' do - date_proc = connection.execute_procedure('my_getutcdate').first['utcdate'] - date_base = connection.select_value('select GETUTCDATE()') + it "uses the proper timezone" do + date_proc = connection.execute_procedure("my_getutcdate").first["utcdate"] + date_base = connection.select_value("select GETUTCDATE()") assert_equal date_base.change(usec: 0), date_proc.change(usec: 0) end diff --git a/test/cases/fetch_test_sqlserver.rb b/test/cases/fetch_test_sqlserver.rb index 5650a5f55..4f32b9db2 100755 --- a/test/cases/fetch_test_sqlserver.rb +++ b/test/cases/fetch_test_sqlserver.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/book' +require "cases/helper_sqlserver" +require "models/book" class FetchTestSqlserver < ActiveRecord::TestCase @@ -9,14 +9,14 @@ class FetchTestSqlserver < ActiveRecord::TestCase before { create_10_books } - it 'work with fully qualified table and columns in select' do - books = Book.select('books.id, books.name').limit(3).offset(5) + it "work with fully qualified table and columns in select" do + books = Book.select("books.id, books.name").limit(3).offset(5) assert_equal Book.all[5,3].map(&:id), books.map(&:id) end - describe 'count' do + describe "count" do - it 'gauntlet' do + it "gauntlet" do books[0].destroy books[1].destroy books[2].destroy @@ -34,14 +34,14 @@ class FetchTestSqlserver < ActiveRecord::TestCase end - describe 'order' do + describe "order" do - it 'gauntlet' do - Book.where(name:'Name-10').delete_all - _(Book.order(:name).limit(1).offset(1).map(&:name)).must_equal ['Name-2'] - _(Book.order(:name).limit(2).offset(2).map(&:name)).must_equal ['Name-3', 'Name-4'] - _(Book.order(:name).limit(2).offset(7).map(&:name)).must_equal ['Name-8', 'Name-9'] - _(Book.order(:name).limit(3).offset(7).map(&:name)).must_equal ['Name-8', 'Name-9'] + it "gauntlet" do + Book.where(name:"Name-10").delete_all + _(Book.order(:name).limit(1).offset(1).map(&:name)).must_equal ["Name-2"] + _(Book.order(:name).limit(2).offset(2).map(&:name)).must_equal ["Name-3", "Name-4"] + _(Book.order(:name).limit(2).offset(7).map(&:name)).must_equal ["Name-8", "Name-9"] + _(Book.order(:name).limit(3).offset(7).map(&:name)).must_equal ["Name-8", "Name-9"] _(Book.order(:name).limit(3).offset(9).map(&:name)).must_equal [] end diff --git a/test/cases/fully_qualified_identifier_test_sqlserver.rb b/test/cases/fully_qualified_identifier_test_sqlserver.rb index f3ecc2786..33d042330 100644 --- a/test/cases/fully_qualified_identifier_test_sqlserver.rb +++ b/test/cases/fully_qualified_identifier_test_sqlserver.rb @@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class FullyQualifiedIdentifierTestSQLServer < ActiveRecord::TestCase - describe 'local server' do + describe "local server" do - it 'should use table name in select projections' do + it "should use table name in select projections" do table = Arel::Table.new(:table) expected_sql = "SELECT [table].[name] FROM [table]" assert_equal expected_sql, table.project(table[:name]).to_sql @@ -14,7 +14,7 @@ class FullyQualifiedIdentifierTestSQLServer < ActiveRecord::TestCase end - describe 'remote server' do + describe "remote server" do before do connection_options[:database_prefix] = "[my.server].db.schema." @@ -24,39 +24,39 @@ class FullyQualifiedIdentifierTestSQLServer < ActiveRecord::TestCase connection_options.delete :database_prefix end - it 'should use fully qualified table name in select from clause' do + it "should use fully qualified table name in select from clause" do table = Arel::Table.new(:table) expected_sql = "SELECT * FROM [my.server].[db].[schema].[table]" assert_equal expected_sql, table.project(Arel.star).to_sql end - it 'should not use fully qualified table name in select projections' do + it "should not use fully qualified table name in select projections" do table = Arel::Table.new(:table) expected_sql = "SELECT [table].[name] FROM [my.server].[db].[schema].[table]" assert_equal expected_sql, table.project(table[:name]).to_sql end - it 'should not use fully qualified table name in where clause' do + it "should not use fully qualified table name in where clause" do table = Arel::Table.new(:table) expected_sql = "SELECT * FROM [my.server].[db].[schema].[table] WHERE [table].[id] = 42" quietly { assert_equal expected_sql, table.project(Arel.star).where(table[:id].eq(42)).to_sql } end - it 'should not use fully qualified table name in order clause' do + it "should not use fully qualified table name in order clause" do table = Arel::Table.new(:table) expected_sql = "SELECT * FROM [my.server].[db].[schema].[table] ORDER BY [table].[name]" assert_equal expected_sql, table.project(Arel.star).order(table[:name]).to_sql end - it 'should use fully qualified table name in insert statement' do + it "should use fully qualified table name in insert statement" do manager = Arel::InsertManager.new manager.into Arel::Table.new(:table) - manager.values = manager.create_values [Arel.sql('*')] + manager.values = manager.create_values [Arel.sql("*")] expected_sql = "INSERT INTO [my.server].[db].[schema].[table] VALUES (*)" quietly { assert_equal expected_sql, manager.to_sql } end - it 'should use fully qualified table name in update statement' do + it "should use fully qualified table name in update statement" do table = Arel::Table.new(:table) manager = Arel::UpdateManager.new manager.table(table).where(table[:id].eq(42)) @@ -65,7 +65,7 @@ class FullyQualifiedIdentifierTestSQLServer < ActiveRecord::TestCase quietly { assert_equal expected_sql, manager.to_sql } end - it 'should use fully qualified table name in delete statement' do + it "should use fully qualified table name in delete statement" do table = Arel::Table.new(:table) manager = Arel::DeleteManager.new manager.from(table).where(table[:id].eq(42)) diff --git a/test/cases/helper_sqlserver.rb b/test/cases/helper_sqlserver.rb index 41da2e52f..4c1d3dcfd 100644 --- a/test/cases/helper_sqlserver.rb +++ b/test/cases/helper_sqlserver.rb @@ -1,18 +1,18 @@ # frozen_string_literal: true -require 'support/paths_sqlserver' -require 'bundler/setup' +require "support/paths_sqlserver" +require "bundler/setup" Bundler.require :default, :development -require 'pry' -require 'support/core_ext/query_cache' -require 'support/minitest_sqlserver' -require 'support/test_in_memory_oltp' -require 'cases/helper' -require 'support/load_schema_sqlserver' -require 'support/coerceable_test_sqlserver' -require 'support/sql_counter_sqlserver' -require 'support/connection_reflection' -require 'mocha/minitest' +require "pry" +require "support/core_ext/query_cache" +require "support/minitest_sqlserver" +require "support/test_in_memory_oltp" +require "cases/helper" +require "support/load_schema_sqlserver" +require "support/coerceable_test_sqlserver" +require "support/sql_counter_sqlserver" +require "support/connection_reflection" +require "mocha/minitest" module ActiveRecord class TestCase < ActiveSupport::TestCase @@ -40,7 +40,7 @@ def remove_backtrace_silencers end def host_windows? - RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ + RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ end def with_use_output_inserted_disabled diff --git a/test/cases/in_clause_test_sqlserver.rb b/test/cases/in_clause_test_sqlserver.rb index b32639bde..360bf6003 100644 --- a/test/cases/in_clause_test_sqlserver.rb +++ b/test/cases/in_clause_test_sqlserver.rb @@ -1,14 +1,14 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/post' -require 'models/author' +require "cases/helper_sqlserver" +require "models/post" +require "models/author" class InClauseTestSQLServer < ActiveRecord::TestCase fixtures :posts, :authors - it 'removes ordering from subqueries' do - authors_subquery = Author.where(name: ['David', 'Mary', 'Bob']).order(:name) + it "removes ordering from subqueries" do + authors_subquery = Author.where(name: ["David", "Mary", "Bob"]).order(:name) posts = Post.where(author: authors_subquery) assert_includes authors_subquery.to_sql, "ORDER BY [authors].[name]" @@ -16,8 +16,8 @@ class InClauseTestSQLServer < ActiveRecord::TestCase assert_equal 10, posts.length end - it 'does not remove ordering from subquery that includes a limit' do - authors_subquery = Author.where(name: ['David', 'Mary', 'Bob']).order(:name).limit(2) + it "does not remove ordering from subquery that includes a limit" do + authors_subquery = Author.where(name: ["David", "Mary", "Bob"]).order(:name).limit(2) posts = Post.where(author: authors_subquery) assert_includes authors_subquery.to_sql, "ORDER BY [authors].[name]" @@ -25,8 +25,8 @@ class InClauseTestSQLServer < ActiveRecord::TestCase assert_equal 7, posts.length end - it 'does not remove ordering from subquery that includes an offset' do - authors_subquery = Author.where(name: ['David', 'Mary', 'Bob']).order(:name).offset(1) + it "does not remove ordering from subquery that includes an offset" do + authors_subquery = Author.where(name: ["David", "Mary", "Bob"]).order(:name).offset(1) posts = Post.where(author: authors_subquery) assert_includes authors_subquery.to_sql, "ORDER BY [authors].[name]" diff --git a/test/cases/index_test_sqlserver.rb b/test/cases/index_test_sqlserver.rb index a1cebaa9e..fbea49b73 100644 --- a/test/cases/index_test_sqlserver.rb +++ b/test/cases/index_test_sqlserver.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class IndexTestSQLServer < ActiveRecord::TestCase @@ -19,31 +19,31 @@ class IndexTestSQLServer < ActiveRecord::TestCase connection.drop_table :testings rescue nil end - it 'add index with order' do + it "add index with order" do assert_sql(/CREATE.*INDEX.*\(\[last_name\] DESC\)/i) do - connection.add_index 'testings', ['last_name'], order: { last_name: :desc } - connection.remove_index 'testings', ['last_name'] + connection.add_index "testings", ["last_name"], order: { last_name: :desc } + connection.remove_index "testings", ["last_name"] end assert_sql(/CREATE.*INDEX.*\(\[last_name\] DESC, \[first_name\]\)/i) do - connection.add_index 'testings', ['last_name', 'first_name'], order: { last_name: :desc } - connection.remove_index 'testings', ['last_name', 'first_name'] + connection.add_index "testings", ["last_name", "first_name"], order: { last_name: :desc } + connection.remove_index "testings", ["last_name", "first_name"] end assert_sql(/CREATE.*INDEX.*\(\[last_name\] DESC, \[first_name\] ASC\)/i) do - connection.add_index 'testings', ['last_name', 'first_name'], order: { last_name: :desc, first_name: :asc } - connection.remove_index 'testings', ['last_name', 'first_name'] + connection.add_index "testings", ["last_name", "first_name"], order: { last_name: :desc, first_name: :asc } + connection.remove_index "testings", ["last_name", "first_name"] end end - it 'add index with where' do + it "add index with where" do assert_sql(/CREATE.*INDEX.*\(\[last_name\]\) WHERE \[first_name\] = N'john doe'/i) do - connection.add_index 'testings', 'last_name', where: "[first_name] = N'john doe'" - connection.remove_index 'testings', 'last_name' + connection.add_index "testings", "last_name", where: "[first_name] = N'john doe'" + connection.remove_index "testings", "last_name" end end - it 'add index with expression' do + it "add index with expression" do connection.execute "ALTER TABLE [testings] ADD [first_name_upper] AS UPPER([first_name])" - connection.add_index 'testings', 'first_name_upper' + connection.add_index "testings", "first_name_upper" end end diff --git a/test/cases/json_test_sqlserver.rb b/test/cases/json_test_sqlserver.rb index c47b55794..66ab4180d 100644 --- a/test/cases/json_test_sqlserver.rb +++ b/test/cases/json_test_sqlserver.rb @@ -1,32 +1,32 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" if ActiveRecord::Base.connection.supports_json? class JsonTestSQLServer < ActiveRecord::TestCase before do - @o1 = SSTestDatatypeMigrationJson.create! json_col: { 'a' => 'a', 'b' => 'b', 'c' => 'c' } - @o2 = SSTestDatatypeMigrationJson.create! json_col: { 'a' => nil, 'b' => 'b', 'c' => 'c' } - @o3 = SSTestDatatypeMigrationJson.create! json_col: { 'x' => 1, 'y' => 2, 'z' => 3 } - @o4 = SSTestDatatypeMigrationJson.create! json_col: { 'array' => [1, 2, 3] } + @o1 = SSTestDatatypeMigrationJson.create! json_col: { "a" => "a", "b" => "b", "c" => "c" } + @o2 = SSTestDatatypeMigrationJson.create! json_col: { "a" => nil, "b" => "b", "c" => "c" } + @o3 = SSTestDatatypeMigrationJson.create! json_col: { "x" => 1, "y" => 2, "z" => 3 } + @o4 = SSTestDatatypeMigrationJson.create! json_col: { "array" => [1, 2, 3] } @o5 = SSTestDatatypeMigrationJson.create! json_col: nil end - it 'can return and save JSON data' do - _(SSTestDatatypeMigrationJson.find(@o1.id).json_col).must_equal({ 'a' => 'a', 'b' => 'b', 'c' => 'c' }) - @o1.json_col = { 'a' => 'a' } - _(@o1.json_col).must_equal({ 'a' => 'a' }) + it "can return and save JSON data" do + _(SSTestDatatypeMigrationJson.find(@o1.id).json_col).must_equal({ "a" => "a", "b" => "b", "c" => "c" }) + @o1.json_col = { "a" => "a" } + _(@o1.json_col).must_equal({ "a" => "a" }) @o1.save! - _(@o1.reload.json_col).must_equal({ 'a' => 'a' }) + _(@o1.reload.json_col).must_equal({ "a" => "a" }) end - it 'can use ISJSON function' do - _(SSTestDatatypeMigrationJson.where('ISJSON(json_col) > 0').count).must_equal 4 - _(SSTestDatatypeMigrationJson.where('ISJSON(json_col) IS NULL').count).must_equal 1 + it "can use ISJSON function" do + _(SSTestDatatypeMigrationJson.where("ISJSON(json_col) > 0").count).must_equal 4 + _(SSTestDatatypeMigrationJson.where("ISJSON(json_col) IS NULL").count).must_equal 1 end - it 'can use JSON_VALUE function' do + it "can use JSON_VALUE function" do _(SSTestDatatypeMigrationJson.where("JSON_VALUE(json_col, '$.b') = 'b'").count).must_equal 2 end diff --git a/test/cases/migration_test_sqlserver.rb b/test/cases/migration_test_sqlserver.rb index 3aa02406e..1e54b831d 100644 --- a/test/cases/migration_test_sqlserver.rb +++ b/test/cases/migration_test_sqlserver.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/person' +require "cases/helper_sqlserver" +require "models/person" class MigrationTestSQLServer < ActiveRecord::TestCase - describe 'For transactions' do + describe "For transactions" do before do - @trans_test_table1 = 'sqlserver_trans_table1' - @trans_test_table2 = 'sqlserver_trans_table2' + @trans_test_table1 = "sqlserver_trans_table1" + @trans_test_table2 = "sqlserver_trans_table2" @trans_tables = [@trans_test_table1,@trans_test_table2] end @@ -19,9 +19,9 @@ class MigrationTestSQLServer < ActiveRecord::TestCase end end - it 'not create a tables if error in migrations' do + it "not create a tables if error in migrations" do begin - migrations_dir = File.join ARTest::SQLServer.migrations_root, 'transaction_table' + migrations_dir = File.join ARTest::SQLServer.migrations_root, "transaction_table" quietly { ActiveRecord::MigrationContext.new(migrations_dir, ActiveRecord::SchemaMigration).up } rescue Exception => e assert_match %r|this and all later migrations canceled|, e.message @@ -32,39 +32,39 @@ class MigrationTestSQLServer < ActiveRecord::TestCase end - describe 'For changing column' do + describe "For changing column" do - it 'not raise exception when column contains default constraint' do - lock_version_column = Person.columns_hash['lock_version'] + it "not raise exception when column contains default constraint" do + lock_version_column = Person.columns_hash["lock_version"] assert_equal :integer, lock_version_column.type assert lock_version_column.default.present? - assert_nothing_raised { connection.change_column 'people', 'lock_version', :string } + assert_nothing_raised { connection.change_column "people", "lock_version", :string } Person.reset_column_information - lock_version_column = Person.columns_hash['lock_version'] + lock_version_column = Person.columns_hash["lock_version"] assert_equal :string, lock_version_column.type assert lock_version_column.default.nil? - assert_nothing_raised { connection.change_column 'people', 'lock_version', :integer } + assert_nothing_raised { connection.change_column "people", "lock_version", :integer } Person.reset_column_information end - it 'not drop the default constraint if just renaming' do + it "not drop the default constraint if just renaming" do find_default = lambda do - connection.execute_procedure(:sp_helpconstraint, 'sst_string_defaults', 'nomsg').select do |row| - row['constraint_type'] == "DEFAULT on column string_with_pretend_paren_three" + connection.execute_procedure(:sp_helpconstraint, "sst_string_defaults", "nomsg").select do |row| + row["constraint_type"] == "DEFAULT on column string_with_pretend_paren_three" end.last end default_before = find_default.call connection.change_column :sst_string_defaults, :string_with_pretend_paren_three, :string, limit: 255 default_after = find_default.call assert default_after - assert_equal default_before['constraint_keys'], default_after['constraint_keys'] + assert_equal default_before["constraint_keys"], default_after["constraint_keys"] end - it 'change limit' do + it "change limit" do assert_nothing_raised { connection.change_column :people, :lock_version, :integer, limit: 8 } end - it 'change null and default' do + it "change null and default" do assert_nothing_raised { connection.change_column :people, :first_name, :text, null: true, default: nil } end diff --git a/test/cases/order_test_sqlserver.rb b/test/cases/order_test_sqlserver.rb index f48a1fad1..ae8bcd6ed 100644 --- a/test/cases/order_test_sqlserver.rb +++ b/test/cases/order_test_sqlserver.rb @@ -1,146 +1,146 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/post' +require "cases/helper_sqlserver" +require "models/post" class OrderTestSQLServer < ActiveRecord::TestCase fixtures :posts - it 'not mangel complex order clauses' do + it "not mangel complex order clauses" do xyz_order = "CASE WHEN [title] LIKE N'XYZ%' THEN 0 ELSE 1 END" - xyz_post = Post.create title: 'XYZ Post', body: 'Test cased orders.' + xyz_post = Post.create title: "XYZ Post", body: "Test cased orders." assert_equal xyz_post, Post.order(Arel.sql(xyz_order)).first end - it 'support column' do + it "support column" do order = "title" - post1 = Post.create title: 'AAA Post', body: 'Test cased orders.' + post1 = Post.create title: "AAA Post", body: "Test cased orders." assert_equal post1, Post.order(order).first end - it 'support column ASC' do + it "support column ASC" do order = "title ASC" - post1 = Post.create title: 'AAA Post', body: 'Test cased orders.' + post1 = Post.create title: "AAA Post", body: "Test cased orders." assert_equal post1, Post.order(order).first end - it 'support column DESC' do + it "support column DESC" do order = "title DESC" - post1 = Post.create title: 'ZZZ Post', body: 'Test cased orders.' + post1 = Post.create title: "ZZZ Post", body: "Test cased orders." assert_equal post1, Post.order(order).first end - it 'support column as symbol' do + it "support column as symbol" do order = :title - post1 = Post.create title: 'AAA Post', body: 'Test cased orders.' + post1 = Post.create title: "AAA Post", body: "Test cased orders." assert_equal post1, Post.order(order).first end - it 'support table and column' do + it "support table and column" do order = "posts.title" - post1 = Post.create title: 'AAA Post', body: 'Test cased orders.' + post1 = Post.create title: "AAA Post", body: "Test cased orders." assert_equal post1, Post.order(order).first end - it 'support quoted column' do + it "support quoted column" do order = "[title]" - post1 = Post.create title: 'AAA Post', body: 'Test cased orders.' + post1 = Post.create title: "AAA Post", body: "Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first end - it 'support quoted table and column' do + it "support quoted table and column" do order = "[posts].[title]" - post1 = Post.create title: 'AAA Post', body: 'Test cased orders.' + post1 = Post.create title: "AAA Post", body: "Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first end - it 'support primary: column, secondary: column' do + it "support primary: column, secondary: column" do order = "title DESC, body" - post1 = Post.create title: 'ZZZ Post', body: 'Test cased orders.' - post2 = Post.create title: 'ZZZ Post', body: 'ZZZ Test cased orders.' + post1 = Post.create title: "ZZZ Post", body: "Test cased orders." + post2 = Post.create title: "ZZZ Post", body: "ZZZ Test cased orders." assert_equal post1, Post.order(order).first assert_equal post2, Post.order(order).second end - it 'support primary: table and column, secondary: column' do + it "support primary: table and column, secondary: column" do order = "posts.title DESC, body" - post1 = Post.create title: 'ZZZ Post', body: 'Test cased orders.' - post2 = Post.create title: 'ZZZ Post', body: 'ZZZ Test cased orders.' + post1 = Post.create title: "ZZZ Post", body: "Test cased orders." + post2 = Post.create title: "ZZZ Post", body: "ZZZ Test cased orders." assert_equal post1, Post.order(order).first assert_equal post2, Post.order(order).second end - it 'support primary: case expression, secondary: column' do + it "support primary: case expression, secondary: column" do order = "(CASE WHEN [title] LIKE N'ZZZ%' THEN title ELSE '' END) DESC, body" - post1 = Post.create title: 'ZZZ Post', body: 'Test cased orders.' - post2 = Post.create title: 'ZZZ Post', body: 'ZZZ Test cased orders.' + post1 = Post.create title: "ZZZ Post", body: "Test cased orders." + post2 = Post.create title: "ZZZ Post", body: "ZZZ Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first assert_equal post2, Post.order(Arel.sql(order)).second end - it 'support primary: quoted table and column, secondary: case expresion' do + it "support primary: quoted table and column, secondary: case expresion" do order = "[posts].[body] DESC, (CASE WHEN [title] LIKE N'ZZZ%' THEN title ELSE '' END) DESC" - post1 = Post.create title: 'ZZZ Post', body: 'ZZZ Test cased orders.' - post2 = Post.create title: 'ZZY Post', body: 'ZZZ Test cased orders.' + post1 = Post.create title: "ZZZ Post", body: "ZZZ Test cased orders." + post2 = Post.create title: "ZZY Post", body: "ZZZ Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first assert_equal post2, Post.order(Arel.sql(order)).second end - it 'support inline function' do + it "support inline function" do order = "LEN(title)" - post1 = Post.create title: 'A', body: 'AAA Test cased orders.' + post1 = Post.create title: "A", body: "AAA Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first end - it 'support inline function with parameters' do + it "support inline function with parameters" do order = "SUBSTRING(title, 1, 3)" - post1 = Post.create title: 'AAA Post', body: 'Test cased orders.' + post1 = Post.create title: "AAA Post", body: "Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first end - it 'support inline function with parameters DESC' do + it "support inline function with parameters DESC" do order = "SUBSTRING(title, 1, 3) DESC" - post1 = Post.create title: 'ZZZ Post', body: 'Test cased orders.' + post1 = Post.create title: "ZZZ Post", body: "Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first end - it 'support primary: inline function, secondary: column' do + it "support primary: inline function, secondary: column" do order = "LEN(title), body" - post1 = Post.create title: 'A', body: 'AAA Test cased orders.' - post2 = Post.create title: 'A', body: 'Test cased orders.' + post1 = Post.create title: "A", body: "AAA Test cased orders." + post2 = Post.create title: "A", body: "Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first assert_equal post2, Post.order(Arel.sql(order)).second end - it 'support primary: inline function, secondary: column with direction' do + it "support primary: inline function, secondary: column with direction" do order = "LEN(title) ASC, body DESC" - post1 = Post.create title: 'A', body: 'ZZZ Test cased orders.' - post2 = Post.create title: 'A', body: 'Test cased orders.' + post1 = Post.create title: "A", body: "ZZZ Test cased orders." + post2 = Post.create title: "A", body: "Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first assert_equal post2, Post.order(Arel.sql(order)).second end - it 'support primary: column, secondary: inline function' do + it "support primary: column, secondary: inline function" do order = "body DESC, LEN(title)" - post1 = Post.create title: 'Post', body: 'ZZZ Test cased orders.' - post2 = Post.create title: 'Longer Post', body: 'ZZZ Test cased orders.' + post1 = Post.create title: "Post", body: "ZZZ Test cased orders." + post2 = Post.create title: "Longer Post", body: "ZZZ Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first assert_equal post2, Post.order(Arel.sql(order)).second end - it 'support primary: case expression, secondary: inline function' do + it "support primary: case expression, secondary: inline function" do order = "CASE WHEN [title] LIKE N'ZZZ%' THEN title ELSE '' END DESC, LEN(body) ASC" - post1 = Post.create title: 'ZZZ Post', body: 'Z' - post2 = Post.create title: 'ZZZ Post', body: 'Test cased orders.' + post1 = Post.create title: "ZZZ Post", body: "Z" + post2 = Post.create title: "ZZZ Post", body: "Test cased orders." assert_equal post1, Post.order(Arel.sql(order)).first assert_equal post2, Post.order(Arel.sql(order)).second end - it 'support primary: inline function, secondary: case expression' do + it "support primary: inline function, secondary: case expression" do order = "LEN(body), CASE WHEN [title] LIKE N'ZZZ%' THEN title ELSE '' END DESC" - post1 = Post.create title: 'ZZZ Post', body: 'Z' - post2 = Post.create title: 'Post', body: 'Z' + post1 = Post.create title: "ZZZ Post", body: "Z" + post2 = Post.create title: "Post", body: "Z" assert_equal post1, Post.order(Arel.sql(order)).first assert_equal post2, Post.order(Arel.sql(order)).second end diff --git a/test/cases/pessimistic_locking_test_sqlserver.rb b/test/cases/pessimistic_locking_test_sqlserver.rb index 45160f156..b7bfadc8a 100644 --- a/test/cases/pessimistic_locking_test_sqlserver.rb +++ b/test/cases/pessimistic_locking_test_sqlserver.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/person' -require 'models/reader' +require "cases/helper_sqlserver" +require "models/person" +require "models/reader" class PessimisticLockingTestSQLServer < ActiveRecord::TestCase @@ -13,15 +13,15 @@ class PessimisticLockingTestSQLServer < ActiveRecord::TestCase Reader.columns end - it 'uses with updlock by default' do + it "uses with updlock by default" do assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(UPDLOCK\)| do _(Person.lock(true).to_a).must_equal Person.all.to_a end end - describe 'For simple finds with default lock option' do + describe "For simple finds with default lock option" do - it 'lock with simple find' do + it "lock with simple find" do assert_nothing_raised do Person.transaction do _(Person.lock(true).find(1)).must_equal Person.find(1) @@ -29,7 +29,7 @@ class PessimisticLockingTestSQLServer < ActiveRecord::TestCase end end - it 'lock with scoped find' do + it "lock with scoped find" do assert_nothing_raised do Person.transaction do Person.lock(true).scoping do @@ -39,7 +39,7 @@ class PessimisticLockingTestSQLServer < ActiveRecord::TestCase end end - it 'lock with eager find' do + it "lock with eager find" do assert_nothing_raised do Person.transaction do person = Person.lock(true).includes(:readers).find(1) @@ -48,35 +48,35 @@ class PessimisticLockingTestSQLServer < ActiveRecord::TestCase end end - it 'can add a custom lock directive' do + it "can add a custom lock directive" do assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(HOLDLOCK, ROWLOCK\)| do - Person.lock('WITH(HOLDLOCK, ROWLOCK)').load + Person.lock("WITH(HOLDLOCK, ROWLOCK)").load end end - describe 'joining tables' do + describe "joining tables" do - it 'joined tables use updlock by default' do + it "joined tables use updlock by default" do assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(UPDLOCK\) INNER JOIN \[readers\] WITH\(UPDLOCK\)\s+ON \[readers\]\.\[person_id\] = \[people\]\.\[id\]| do Person.lock(true).joins(:readers).load end end - it 'joined tables can use custom lock directive' do + it "joined tables can use custom lock directive" do assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(NOLOCK\) INNER JOIN \[readers\] WITH\(NOLOCK\)\s+ON \[readers\]\.\[person_id\] = \[people\]\.\[id\]| do - Person.lock('WITH(NOLOCK)').joins(:readers).load + Person.lock("WITH(NOLOCK)").joins(:readers).load end end - it 'left joined tables use updlock by default' do + it "left joined tables use updlock by default" do assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(UPDLOCK\) LEFT OUTER JOIN \[readers\] WITH\(UPDLOCK\)\s+ON \[readers\]\.\[person_id\] = \[people\]\.\[id\]| do Person.lock(true).left_joins(:readers).load end end - it 'left joined tables can use custom lock directive' do + it "left joined tables can use custom lock directive" do assert_sql %r|SELECT \[people\]\.\* FROM \[people\] WITH\(NOLOCK\) LEFT OUTER JOIN \[readers\] WITH\(NOLOCK\)\s+ON \[readers\]\.\[person_id\] = \[people\]\.\[id\]| do - Person.lock('WITH(NOLOCK)').left_joins(:readers).load + Person.lock("WITH(NOLOCK)").left_joins(:readers).load end end @@ -84,23 +84,23 @@ class PessimisticLockingTestSQLServer < ActiveRecord::TestCase end - describe 'For paginated finds' do + describe "For paginated finds" do before do Person.delete_all 20.times { |n| Person.create!(first_name: "Thing_#{n}") } end - it 'copes with eager loading un-locked paginated' do + it "copes with eager loading un-locked paginated" do eager_ids_sql = /SELECT\s+DISTINCT \[people\].\[id\] FROM \[people\] WITH\(UPDLOCK\) LEFT OUTER JOIN \[readers\] WITH\(UPDLOCK\)\s+ON \[readers\].\[person_id\] = \[people\].\[id\]\s+ORDER BY \[people\].\[id\] ASC OFFSET @0 ROWS FETCH NEXT @1 ROWS ONLY/ loader_sql = /SELECT.*FROM \[people\] WITH\(UPDLOCK\).*WHERE \[people\]\.\[id\] IN/ assert_sql(eager_ids_sql, loader_sql) do people = Person.lock(true).limit(5).offset(10).includes(:readers).references(:readers).to_a - _(people[0].first_name).must_equal 'Thing_10' - _(people[1].first_name).must_equal 'Thing_11' - _(people[2].first_name).must_equal 'Thing_12' - _(people[3].first_name).must_equal 'Thing_13' - _(people[4].first_name).must_equal 'Thing_14' + _(people[0].first_name).must_equal "Thing_10" + _(people[1].first_name).must_equal "Thing_11" + _(people[2].first_name).must_equal "Thing_12" + _(people[3].first_name).must_equal "Thing_13" + _(people[4].first_name).must_equal "Thing_14" end end diff --git a/test/cases/rake_test_sqlserver.rb b/test/cases/rake_test_sqlserver.rb index 431497e00..bb5fa8b1b 100644 --- a/test/cases/rake_test_sqlserver.rb +++ b/test/cases/rake_test_sqlserver.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class SQLServerRakeTest < ActiveRecord::TestCase @@ -10,11 +10,11 @@ class SQLServerRakeTest < ActiveRecord::TestCase self.azure_skip = connection_sqlserver_azure? let(:db_tasks) { ActiveRecord::Tasks::DatabaseTasks } - let(:new_database) { 'activerecord_unittest_tasks' } - let(:default_configuration) { ARTest.connection_config['arunit'] } - let(:configuration) { default_configuration.merge('database' => new_database) } + let(:new_database) { "activerecord_unittest_tasks" } + let(:default_configuration) { ARTest.connection_config["arunit"] } + let(:configuration) { default_configuration.merge("database" => new_database) } - before { skip 'on azure' if azure_skip } + before { skip "on azure" if azure_skip } before { disconnect! unless azure_skip } after { reconnect unless azure_skip } @@ -27,7 +27,7 @@ def disconnect! def reconnect config = default_configuration if connection_sqlserver_azure? - ActiveRecord::Base.establish_connection(config.merge('database' => 'master')) + ActiveRecord::Base.establish_connection(config.merge("database" => "master")) connection.drop_database(new_database) rescue nil disconnect! ActiveRecord::Base.establish_connection(config) @@ -43,22 +43,22 @@ class SQLServerRakeCreateTest < SQLServerRakeTest self.azure_skip = false - it 'establishes connection to database after create ' do + it "establishes connection to database after create " do quietly { db_tasks.create configuration } _(connection.current_database).must_equal(new_database) end - it 'creates database with default collation' do + it "creates database with default collation" do quietly { db_tasks.create configuration } - _(connection.collation).must_equal 'SQL_Latin1_General_CP1_CI_AS' + _(connection.collation).must_equal "SQL_Latin1_General_CP1_CI_AS" end - it 'creates database with given collation' do - quietly { db_tasks.create configuration.merge('collation' => 'Latin1_General_CI_AS') } - _(connection.collation).must_equal 'Latin1_General_CI_AS' + it "creates database with given collation" do + quietly { db_tasks.create configuration.merge("collation" => "Latin1_General_CI_AS") } + _(connection.collation).must_equal "Latin1_General_CI_AS" end - it 'prints error message when database exists' do + it "prints error message when database exists" do quietly { db_tasks.create configuration } message = capture(:stderr) { db_tasks.create configuration } _(message).must_match %r{activerecord_unittest_tasks.*already exists} @@ -70,16 +70,16 @@ class SQLServerRakeDropTest < SQLServerRakeTest self.azure_skip = false - it 'drops database and uses master' do + it "drops database and uses master" do quietly do db_tasks.create configuration db_tasks.drop configuration end - _(connection.current_database).must_equal 'master' + _(connection.current_database).must_equal "master" end - it 'prints error message when database does not exist' do - message = capture(:stderr) { db_tasks.drop configuration.merge('database' => 'doesnotexist') } + it "prints error message when database does not exist" do + message = capture(:stderr) { db_tasks.drop configuration.merge("database" => "doesnotexist") } _(message).must_match %r{'doesnotexist' does not exist} end @@ -95,12 +95,12 @@ class SQLServerRakePurgeTest < SQLServerRakeTest end end - it 'clears active connections, drops database, and recreates with established connection' do + it "clears active connections, drops database, and recreates with established connection" do _(connection.current_database).must_equal(new_database) - _(connection.tables).must_include 'users' + _(connection.tables).must_include "users" quietly { db_tasks.purge(configuration) } _(connection.current_database).must_equal(new_database) - _(connection.tables).wont_include 'users' + _(connection.tables).wont_include "users" end end @@ -111,8 +111,8 @@ class SQLServerRakeCharsetTest < SQLServerRakeTest quietly { db_tasks.create(configuration) } end - it 'retrieves charset' do - _(db_tasks.charset(configuration)).must_equal 'iso_1' + it "retrieves charset" do + _(db_tasks.charset(configuration)).must_equal "iso_1" end end @@ -123,15 +123,15 @@ class SQLServerRakeCollationTest < SQLServerRakeTest quietly { db_tasks.create(configuration) } end - it 'retrieves collation' do - _(db_tasks.collation(configuration)).must_equal 'SQL_Latin1_General_CP1_CI_AS' + it "retrieves collation" do + _(db_tasks.collation(configuration)).must_equal "SQL_Latin1_General_CP1_CI_AS" end end class SQLServerRakeStructureDumpLoadTest < SQLServerRakeTest - let(:filename) { File.join ARTest::SQLServer.migrations_root, 'structure.sql' } + let(:filename) { File.join ARTest::SQLServer.migrations_root, "structure.sql" } let(:filedata) { File.read(filename) } before do @@ -148,8 +148,8 @@ class SQLServerRakeStructureDumpLoadTest < SQLServerRakeTest FileUtils.rm_rf(filename) end - it 'dumps structure and accounts for defncopy oddities' do - skip 'debug defncopy on windows later' if host_windows? + it "dumps structure and accounts for defncopy oddities" do + skip "debug defncopy on windows later" if host_windows? quietly { db_tasks.structure_dump configuration, filename } _(filedata).wont_match %r{\AUSE.*\z} _(filedata).wont_match %r{\AGO.*\z} @@ -158,14 +158,14 @@ class SQLServerRakeStructureDumpLoadTest < SQLServerRakeTest _(filedata).must_match %r{background2\s+text\s+} end - it 'can load dumped structure' do - skip 'debug defncopy on windows later' if host_windows? + it "can load dumped structure" do + skip "debug defncopy on windows later" if host_windows? quietly { db_tasks.structure_dump configuration, filename } _(filedata).must_match %r{CREATE TABLE dbo\.users} db_tasks.purge(configuration) - _(connection.tables).wont_include 'users' + _(connection.tables).wont_include "users" db_tasks.load_schema configuration, :sql, filename - _(connection.tables).must_include 'users' + _(connection.tables).must_include "users" end end diff --git a/test/cases/schema_dumper_test_sqlserver.rb b/test/cases/schema_dumper_test_sqlserver.rb index a5a5b6677..44cb73e02 100644 --- a/test/cases/schema_dumper_test_sqlserver.rb +++ b/test/cases/schema_dumper_test_sqlserver.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class SchemaDumperTestSQLServer < ActiveRecord::TestCase @@ -9,138 +9,138 @@ class SchemaDumperTestSQLServer < ActiveRecord::TestCase let(:all_tables) { ActiveRecord::Base.connection.tables } let(:schema) { @generated_schema } - it 'sst_datatypes' do - generate_schema_for_table 'sst_datatypes' - assert_line :bigint, type: 'bigint', limit: nil, precision: nil, scale: nil, default: 42 - assert_line :int, type: 'integer', limit: nil, precision: nil, scale: nil, default: 42 - assert_line :smallint, type: 'integer', limit: 2, precision: nil, scale: nil, default: 42 - assert_line :tinyint, type: 'integer', limit: 1, precision: nil, scale: nil, default: 42 - assert_line :bit, type: 'boolean', limit: nil, precision: nil, scale: nil, default: true - assert_line :decimal_9_2, type: 'decimal', limit: nil, precision: 9, scale: 2, default: 12345.01 - assert_line :numeric_18_0, type: 'decimal', limit: nil, precision: 18, scale: 0, default: 191.0 - assert_line :numeric_36_2, type: 'decimal', limit: nil, precision: 36, scale: 2, default: 12345678901234567890.01 - assert_line :money, type: 'money', limit: nil, precision: 19, scale: 4, default: 4.2 - assert_line :smallmoney, type: 'smallmoney', limit: nil, precision: 10, scale: 4, default: 4.2 + it "sst_datatypes" do + generate_schema_for_table "sst_datatypes" + assert_line :bigint, type: "bigint", limit: nil, precision: nil, scale: nil, default: 42 + assert_line :int, type: "integer", limit: nil, precision: nil, scale: nil, default: 42 + assert_line :smallint, type: "integer", limit: 2, precision: nil, scale: nil, default: 42 + assert_line :tinyint, type: "integer", limit: 1, precision: nil, scale: nil, default: 42 + assert_line :bit, type: "boolean", limit: nil, precision: nil, scale: nil, default: true + assert_line :decimal_9_2, type: "decimal", limit: nil, precision: 9, scale: 2, default: 12345.01 + assert_line :numeric_18_0, type: "decimal", limit: nil, precision: 18, scale: 0, default: 191.0 + assert_line :numeric_36_2, type: "decimal", limit: nil, precision: 36, scale: 2, default: 12345678901234567890.01 + assert_line :money, type: "money", limit: nil, precision: 19, scale: 4, default: 4.2 + assert_line :smallmoney, type: "smallmoney", limit: nil, precision: 10, scale: 4, default: 4.2 # Approximate Numerics - assert_line :float, type: 'float', limit: nil, precision: nil, scale: nil, default: 123.00000001 - assert_line :real, type: 'real', limit: nil, precision: nil, scale: nil, default: 123.45 + assert_line :float, type: "float", limit: nil, precision: nil, scale: nil, default: 123.00000001 + assert_line :real, type: "real", limit: nil, precision: nil, scale: nil, default: 123.45 # Date and Time - assert_line :date, type: 'date', limit: nil, precision: nil, scale: nil, default: "01-01-0001" - assert_line :datetime, type: 'datetime', limit: nil, precision: nil, scale: nil, default: "01-01-1753 00:00:00.123" + assert_line :date, type: "date", limit: nil, precision: nil, scale: nil, default: "01-01-0001" + assert_line :datetime, type: "datetime", limit: nil, precision: nil, scale: nil, default: "01-01-1753 00:00:00.123" if connection_dblib_73? - assert_line :datetime2_7, type: 'datetime', limit: nil, precision: 7, scale: nil, default: "12-31-9999 23:59:59.9999999" - assert_line :datetime2_3, type: 'datetime', limit: nil, precision: 3, scale: nil, default: nil - assert_line :datetime2_1, type: 'datetime', limit: nil, precision: 1, scale: nil, default: nil + assert_line :datetime2_7, type: "datetime", limit: nil, precision: 7, scale: nil, default: "12-31-9999 23:59:59.9999999" + assert_line :datetime2_3, type: "datetime", limit: nil, precision: 3, scale: nil, default: nil + assert_line :datetime2_1, type: "datetime", limit: nil, precision: 1, scale: nil, default: nil end - assert_line :smalldatetime, type: 'smalldatetime',limit: nil, precision: nil, scale: nil, default: "01-01-1901 15:45:00.0" + assert_line :smalldatetime, type: "smalldatetime",limit: nil, precision: nil, scale: nil, default: "01-01-1901 15:45:00.0" if connection_dblib_73? - assert_line :time_7, type: 'time', limit: nil, precision: 7, scale: nil, default: "04:20:00.2883215" - assert_line :time_2, type: 'time', limit: nil, precision: 2, scale: nil, default: nil - assert_line :time_default, type: 'time', limit: nil, precision: 7, scale: nil, default: "15:03:42.0621978" + assert_line :time_7, type: "time", limit: nil, precision: 7, scale: nil, default: "04:20:00.2883215" + assert_line :time_2, type: "time", limit: nil, precision: 2, scale: nil, default: nil + assert_line :time_default, type: "time", limit: nil, precision: 7, scale: nil, default: "15:03:42.0621978" end # Character Strings - assert_line :char_10, type: 'char', limit: 10, precision: nil, scale: nil, default: "1234567890", collation: nil - assert_line :varchar_50, type: 'varchar', limit: 50, precision: nil, scale: nil, default: "test varchar_50", collation: nil - assert_line :varchar_max, type: 'varchar_max', limit: nil, precision: nil, scale: nil, default: "test varchar_max", collation: nil - assert_line :text, type: 'text_basic', limit: nil, precision: nil, scale: nil, default: "test text", collation: nil + assert_line :char_10, type: "char", limit: 10, precision: nil, scale: nil, default: "1234567890", collation: nil + assert_line :varchar_50, type: "varchar", limit: 50, precision: nil, scale: nil, default: "test varchar_50", collation: nil + assert_line :varchar_max, type: "varchar_max", limit: nil, precision: nil, scale: nil, default: "test varchar_max", collation: nil + assert_line :text, type: "text_basic", limit: nil, precision: nil, scale: nil, default: "test text", collation: nil # Unicode Character Strings - assert_line :nchar_10, type: 'nchar', limit: 10, precision: nil, scale: nil, default: "12345678åå", collation: nil - assert_line :nvarchar_50, type: 'string', limit: 50, precision: nil, scale: nil, default: "test nvarchar_50 åå", collation: nil - assert_line :nvarchar_max, type: 'text', limit: nil, precision: nil, scale: nil, default: "test nvarchar_max åå", collation: nil - assert_line :ntext, type: 'ntext', limit: nil, precision: nil, scale: nil, default: "test ntext åå", collation: nil + assert_line :nchar_10, type: "nchar", limit: 10, precision: nil, scale: nil, default: "12345678åå", collation: nil + assert_line :nvarchar_50, type: "string", limit: 50, precision: nil, scale: nil, default: "test nvarchar_50 åå", collation: nil + assert_line :nvarchar_max, type: "text", limit: nil, precision: nil, scale: nil, default: "test nvarchar_max åå", collation: nil + assert_line :ntext, type: "ntext", limit: nil, precision: nil, scale: nil, default: "test ntext åå", collation: nil # Binary Strings - assert_line :binary_49, type: 'binary_basic', limit: 49, precision: nil, scale: nil, default: nil - assert_line :varbinary_49, type: 'varbinary', limit: 49, precision: nil, scale: nil, default: nil - assert_line :varbinary_max, type: 'binary', limit: nil, precision: nil, scale: nil, default: nil + assert_line :binary_49, type: "binary_basic", limit: 49, precision: nil, scale: nil, default: nil + assert_line :varbinary_49, type: "varbinary", limit: 49, precision: nil, scale: nil, default: nil + assert_line :varbinary_max, type: "binary", limit: nil, precision: nil, scale: nil, default: nil # Other Data Types - assert_line :uniqueidentifier, type: 'uuid', limit: nil, precision: nil, scale: nil, default: -> { "newid()" } - assert_line :timestamp, type: 'ss_timestamp', limit: nil, precision: nil, scale: nil, default: nil + assert_line :uniqueidentifier, type: "uuid", limit: nil, precision: nil, scale: nil, default: -> { "newid()" } + assert_line :timestamp, type: "ss_timestamp", limit: nil, precision: nil, scale: nil, default: nil end - it 'sst_datatypes_migration' do + it "sst_datatypes_migration" do columns = SSTestDatatypeMigration.columns_hash - generate_schema_for_table 'sst_datatypes_migration' + generate_schema_for_table "sst_datatypes_migration" # Simple Rails conventions - _(columns['integer_col'].sql_type).must_equal 'int(4)' - _(columns['bigint_col'].sql_type).must_equal 'bigint(8)' - _(columns['boolean_col'].sql_type).must_equal 'bit' - _(columns['decimal_col'].sql_type).must_equal 'decimal(18,0)' - _(columns['float_col'].sql_type).must_equal 'float' - _(columns['string_col'].sql_type).must_equal 'nvarchar(4000)' - _(columns['text_col'].sql_type).must_equal 'nvarchar(max)' - _(columns['datetime_col'].sql_type).must_equal 'datetime' - _(columns['timestamp_col'].sql_type).must_equal 'datetime' - _(columns['time_col'].sql_type).must_equal 'time(7)' - _(columns['date_col'].sql_type).must_equal 'date' - _(columns['binary_col'].sql_type).must_equal 'varbinary(max)' - assert_line :integer_col, type: 'integer', limit: nil, precision: nil, scale: nil, default: nil - assert_line :bigint_col, type: 'bigint', limit: nil, precision: nil, scale: nil, default: nil - assert_line :boolean_col, type: 'boolean', limit: nil, precision: nil, scale: nil, default: nil - assert_line :decimal_col, type: 'decimal', limit: nil, precision: 18, scale: 0, default: nil - assert_line :float_col, type: 'float', limit: nil, precision: nil, scale: nil, default: nil - assert_line :string_col, type: 'string', limit: nil, precision: nil, scale: nil, default: nil - assert_line :text_col, type: 'text', limit: nil, precision: nil, scale: nil, default: nil - assert_line :datetime_col, type: 'datetime', limit: nil, precision: nil, scale: nil, default: nil - assert_line :timestamp_col, type: 'datetime', limit: nil, precision: nil, scale: nil, default: nil - assert_line :time_col, type: 'time', limit: nil, precision: 7, scale: nil, default: nil - assert_line :date_col, type: 'date', limit: nil, precision: nil, scale: nil, default: nil - assert_line :binary_col, type: 'binary', limit: nil, precision: nil, scale: nil, default: nil + _(columns["integer_col"].sql_type).must_equal "int(4)" + _(columns["bigint_col"].sql_type).must_equal "bigint(8)" + _(columns["boolean_col"].sql_type).must_equal "bit" + _(columns["decimal_col"].sql_type).must_equal "decimal(18,0)" + _(columns["float_col"].sql_type).must_equal "float" + _(columns["string_col"].sql_type).must_equal "nvarchar(4000)" + _(columns["text_col"].sql_type).must_equal "nvarchar(max)" + _(columns["datetime_col"].sql_type).must_equal "datetime" + _(columns["timestamp_col"].sql_type).must_equal "datetime" + _(columns["time_col"].sql_type).must_equal "time(7)" + _(columns["date_col"].sql_type).must_equal "date" + _(columns["binary_col"].sql_type).must_equal "varbinary(max)" + assert_line :integer_col, type: "integer", limit: nil, precision: nil, scale: nil, default: nil + assert_line :bigint_col, type: "bigint", limit: nil, precision: nil, scale: nil, default: nil + assert_line :boolean_col, type: "boolean", limit: nil, precision: nil, scale: nil, default: nil + assert_line :decimal_col, type: "decimal", limit: nil, precision: 18, scale: 0, default: nil + assert_line :float_col, type: "float", limit: nil, precision: nil, scale: nil, default: nil + assert_line :string_col, type: "string", limit: nil, precision: nil, scale: nil, default: nil + assert_line :text_col, type: "text", limit: nil, precision: nil, scale: nil, default: nil + assert_line :datetime_col, type: "datetime", limit: nil, precision: nil, scale: nil, default: nil + assert_line :timestamp_col, type: "datetime", limit: nil, precision: nil, scale: nil, default: nil + assert_line :time_col, type: "time", limit: nil, precision: 7, scale: nil, default: nil + assert_line :date_col, type: "date", limit: nil, precision: nil, scale: nil, default: nil + assert_line :binary_col, type: "binary", limit: nil, precision: nil, scale: nil, default: nil # Our type methods. - _(columns['real_col'].sql_type).must_equal 'real' - _(columns['money_col'].sql_type).must_equal 'money' - _(columns['smalldatetime_col'].sql_type).must_equal 'smalldatetime' - _(columns['datetime2_col'].sql_type).must_equal 'datetime2(7)' - _(columns['datetimeoffset'].sql_type).must_equal 'datetimeoffset(7)' - _(columns['smallmoney_col'].sql_type).must_equal 'smallmoney' - _(columns['char_col'].sql_type).must_equal 'char(1)' - _(columns['varchar_col'].sql_type).must_equal 'varchar(8000)' - _(columns['text_basic_col'].sql_type).must_equal 'text' - _(columns['nchar_col'].sql_type).must_equal 'nchar(1)' - _(columns['ntext_col'].sql_type).must_equal 'ntext' - _(columns['binary_basic_col'].sql_type).must_equal 'binary(1)' - _(columns['varbinary_col'].sql_type).must_equal 'varbinary(8000)' - _(columns['uuid_col'].sql_type).must_equal 'uniqueidentifier' - _(columns['sstimestamp_col'].sql_type).must_equal 'timestamp' - _(columns['json_col'].sql_type).must_equal 'nvarchar(max)' - assert_line :real_col, type: 'real', limit: nil, precision: nil, scale: nil, default: nil - assert_line :money_col, type: 'money', limit: nil, precision: 19, scale: 4, default: nil - assert_line :smalldatetime_col, type: 'smalldatetime', limit: nil, precision: nil, scale: nil, default: nil - assert_line :datetime2_col, type: 'datetime', limit: nil, precision: 7, scale: nil, default: nil - assert_line :datetimeoffset, type: 'datetimeoffset', limit: nil, precision: 7, scale: nil, default: nil - assert_line :smallmoney_col, type: 'smallmoney', limit: nil, precision: 10, scale: 4, default: nil - assert_line :char_col, type: 'char', limit: 1, precision: nil, scale: nil, default: nil - assert_line :varchar_col, type: 'varchar', limit: nil, precision: nil, scale: nil, default: nil - assert_line :text_basic_col, type: 'text_basic', limit: nil, precision: nil, scale: nil, default: nil - assert_line :nchar_col, type: 'nchar', limit: 1, precision: nil, scale: nil, default: nil - assert_line :ntext_col, type: 'ntext', limit: nil, precision: nil, scale: nil, default: nil - assert_line :binary_basic_col, type: 'binary_basic', limit: 1, precision: nil, scale: nil, default: nil - assert_line :varbinary_col, type: 'varbinary', limit: nil, precision: nil, scale: nil, default: nil - assert_line :uuid_col, type: 'uuid', limit: nil, precision: nil, scale: nil, default: nil - assert_line :sstimestamp_col, type: 'ss_timestamp', limit: nil, precision: nil, scale: nil, default: nil - assert_line :json_col, type: 'text', limit: nil, precision: nil, scale: nil, default: nil + _(columns["real_col"].sql_type).must_equal "real" + _(columns["money_col"].sql_type).must_equal "money" + _(columns["smalldatetime_col"].sql_type).must_equal "smalldatetime" + _(columns["datetime2_col"].sql_type).must_equal "datetime2(7)" + _(columns["datetimeoffset"].sql_type).must_equal "datetimeoffset(7)" + _(columns["smallmoney_col"].sql_type).must_equal "smallmoney" + _(columns["char_col"].sql_type).must_equal "char(1)" + _(columns["varchar_col"].sql_type).must_equal "varchar(8000)" + _(columns["text_basic_col"].sql_type).must_equal "text" + _(columns["nchar_col"].sql_type).must_equal "nchar(1)" + _(columns["ntext_col"].sql_type).must_equal "ntext" + _(columns["binary_basic_col"].sql_type).must_equal "binary(1)" + _(columns["varbinary_col"].sql_type).must_equal "varbinary(8000)" + _(columns["uuid_col"].sql_type).must_equal "uniqueidentifier" + _(columns["sstimestamp_col"].sql_type).must_equal "timestamp" + _(columns["json_col"].sql_type).must_equal "nvarchar(max)" + assert_line :real_col, type: "real", limit: nil, precision: nil, scale: nil, default: nil + assert_line :money_col, type: "money", limit: nil, precision: 19, scale: 4, default: nil + assert_line :smalldatetime_col, type: "smalldatetime", limit: nil, precision: nil, scale: nil, default: nil + assert_line :datetime2_col, type: "datetime", limit: nil, precision: 7, scale: nil, default: nil + assert_line :datetimeoffset, type: "datetimeoffset", limit: nil, precision: 7, scale: nil, default: nil + assert_line :smallmoney_col, type: "smallmoney", limit: nil, precision: 10, scale: 4, default: nil + assert_line :char_col, type: "char", limit: 1, precision: nil, scale: nil, default: nil + assert_line :varchar_col, type: "varchar", limit: nil, precision: nil, scale: nil, default: nil + assert_line :text_basic_col, type: "text_basic", limit: nil, precision: nil, scale: nil, default: nil + assert_line :nchar_col, type: "nchar", limit: 1, precision: nil, scale: nil, default: nil + assert_line :ntext_col, type: "ntext", limit: nil, precision: nil, scale: nil, default: nil + assert_line :binary_basic_col, type: "binary_basic", limit: 1, precision: nil, scale: nil, default: nil + assert_line :varbinary_col, type: "varbinary", limit: nil, precision: nil, scale: nil, default: nil + assert_line :uuid_col, type: "uuid", limit: nil, precision: nil, scale: nil, default: nil + assert_line :sstimestamp_col, type: "ss_timestamp", limit: nil, precision: nil, scale: nil, default: nil + assert_line :json_col, type: "text", limit: nil, precision: nil, scale: nil, default: nil end # Special Cases - it 'honor nonstandard primary keys' do - generate_schema_for_table('movies') do |output| + it "honor nonstandard primary keys" do + generate_schema_for_table("movies") do |output| match = output.match(%r{create_table "movies"(.*)do}) assert_not_nil(match, "nonstandardpk table not found") assert_match %r(primary_key: "movieid"), match[1], "non-standard primary key not preserved" end end - it 'no id with model driven primary key' do - output = generate_schema_for_table 'sst_no_pk_data' + it "no id with model driven primary key" do + output = generate_schema_for_table "sst_no_pk_data" _(output).must_match %r{create_table "sst_no_pk_data".*id:\sfalse.*do} - assert_line :name, type: 'string', limit: nil, default: nil, collation: nil + assert_line :name, type: "string", limit: nil, default: nil, collation: nil end private def generate_schema_for_table(*table_names) - require 'stringio' + require "stringio" stream = StringIO.new ActiveRecord::SchemaDumper.ignore_tables = all_tables - table_names ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream) diff --git a/test/cases/schema_test_sqlserver.rb b/test/cases/schema_test_sqlserver.rb index a913923bc..02244d358 100644 --- a/test/cases/schema_test_sqlserver.rb +++ b/test/cases/schema_test_sqlserver.rb @@ -1,26 +1,26 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class SchemaTestSQLServer < ActiveRecord::TestCase - describe 'When table is dbo schema' do + describe "When table is dbo schema" do - it 'find primary key for tables with odd schema' do - _(connection.primary_key('sst_natural_pk_data')).must_equal 'legacy_id' + it "find primary key for tables with odd schema" do + _(connection.primary_key("sst_natural_pk_data")).must_equal "legacy_id" end end - describe 'When table is in non-dbo schema' do + describe "When table is in non-dbo schema" do - it 'work with table exists' do - assert connection.data_source_exists?('test.sst_schema_natural_id') - assert connection.data_source_exists?('[test].[sst_schema_natural_id]') + it "work with table exists" do + assert connection.data_source_exists?("test.sst_schema_natural_id") + assert connection.data_source_exists?("[test].[sst_schema_natural_id]") end - it 'find primary key for tables with odd schema' do - _(connection.primary_key('test.sst_schema_natural_id')).must_equal 'legacy_id' + it "find primary key for tables with odd schema" do + _(connection.primary_key("test.sst_schema_natural_id")).must_equal "legacy_id" end it "have only one identity column" do @@ -43,10 +43,10 @@ class SchemaTestSQLServer < ActiveRecord::TestCase it "return correct varchar and nvarchar column limit length when table is in non dbo schema" do columns = connection.columns("test.sst_schema_columns") - assert_equal 255, columns.find {|c| c.name == 'name'}.limit - assert_equal 1000, columns.find {|c| c.name == 'description'}.limit - assert_equal 255, columns.find {|c| c.name == 'n_name'}.limit - assert_equal 1000, columns.find {|c| c.name == 'n_description'}.limit + assert_equal 255, columns.find {|c| c.name == "name"}.limit + assert_equal 1000, columns.find {|c| c.name == "description"}.limit + assert_equal 255, columns.find {|c| c.name == "n_name"}.limit + assert_equal 1000, columns.find {|c| c.name == "n_description"}.limit end end diff --git a/test/cases/scratchpad_test_sqlserver.rb b/test/cases/scratchpad_test_sqlserver.rb index f553170ca..a88cdb56d 100644 --- a/test/cases/scratchpad_test_sqlserver.rb +++ b/test/cases/scratchpad_test_sqlserver.rb @@ -1,10 +1,10 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class ScratchpadTestSQLServer < ActiveRecord::TestCase - it 'helps debug things' do + it "helps debug things" do end end diff --git a/test/cases/showplan_test_sqlserver.rb b/test/cases/showplan_test_sqlserver.rb index c43122610..b59e79ff9 100644 --- a/test/cases/showplan_test_sqlserver.rb +++ b/test/cases/showplan_test_sqlserver.rb @@ -1,65 +1,65 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/car' +require "cases/helper_sqlserver" +require "models/car" class ShowplanTestSQLServer < ActiveRecord::TestCase fixtures :cars - describe 'Unprepare previously prepared SQL' do + describe "Unprepare previously prepared SQL" do - it 'from simple statement' do + it "from simple statement" do plan = Car.where(id: 1).explain _(plan).must_include "SELECT [cars].* FROM [cars] WHERE [cars].[id] = 1" - _(plan).must_include "Clustered Index Seek", 'make sure we do not showplan the sp_executesql' + _(plan).must_include "Clustered Index Seek", "make sure we do not showplan the sp_executesql" end - it 'from multiline statement' do + it "from multiline statement" do plan = Car.where("\n id = 1 \n").explain _(plan).must_include "SELECT [cars].* FROM [cars] WHERE (\n id = 1 \n)" - _(plan).must_include "Clustered Index Seek", 'make sure we do not showplan the sp_executesql' + _(plan).must_include "Clustered Index Seek", "make sure we do not showplan the sp_executesql" end - it 'from prepared statement' do - plan = Car.where(name: ',').limit(1).explain + it "from prepared statement" do + plan = Car.where(name: ",").limit(1).explain _(plan).must_include "SELECT [cars].* FROM [cars] WHERE [cars].[name]" - _(plan).must_include "TOP EXPRESSION", 'make sure we do not showplan the sp_executesql' - _(plan).must_include "Clustered Index Scan", 'make sure we do not showplan the sp_executesql' + _(plan).must_include "TOP EXPRESSION", "make sure we do not showplan the sp_executesql" + _(plan).must_include "Clustered Index Scan", "make sure we do not showplan the sp_executesql" end - it 'from array condition using index' do + it "from array condition using index" do plan = Car.where(id: [1, 2]).explain _(plan).must_include "SELECT [cars].* FROM [cars] WHERE [cars].[id] IN (1, 2)" - _(plan).must_include "Clustered Index Seek", 'make sure we do not showplan the sp_executesql' + _(plan).must_include "Clustered Index Seek", "make sure we do not showplan the sp_executesql" end - it 'from array condition' do - plan = Car.where(name: ['honda', 'zyke']).explain + it "from array condition" do + plan = Car.where(name: ["honda", "zyke"]).explain _(plan).must_include " SELECT [cars].* FROM [cars] WHERE [cars].[name] IN (N'honda', N'zyke')" - _(plan).must_include "Clustered Index Scan", 'make sure we do not showplan the sp_executesql' + _(plan).must_include "Clustered Index Scan", "make sure we do not showplan the sp_executesql" end end - describe 'With SHOWPLAN_TEXT option' do + describe "With SHOWPLAN_TEXT option" do - it 'use simple table printer' do - with_showplan_option('SHOWPLAN_TEXT') do + it "use simple table printer" do + with_showplan_option("SHOWPLAN_TEXT") do plan = Car.where(id: 1).explain _(plan).must_include "SELECT [cars].* FROM [cars] WHERE [cars].[id]" - _(plan).must_include "Clustered Index Seek", 'make sure we do not showplan the sp_executesql' + _(plan).must_include "Clustered Index Seek", "make sure we do not showplan the sp_executesql" end end end - describe 'With SHOWPLAN_XML option' do + describe "With SHOWPLAN_XML option" do - it 'show formatted xml' do - with_showplan_option('SHOWPLAN_XML') do + it "show formatted xml" do + with_showplan_option("SHOWPLAN_XML") do plan = Car.where(id: 1).explain - _(plan).must_include 'ShowPlanXML' + _(plan).must_include "ShowPlanXML" end end diff --git a/test/cases/specific_schema_test_sqlserver.rb b/test/cases/specific_schema_test_sqlserver.rb index 21c75a1be..a11cf52e9 100644 --- a/test/cases/specific_schema_test_sqlserver.rb +++ b/test/cases/specific_schema_test_sqlserver.rb @@ -1,29 +1,29 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class SpecificSchemaTestSQLServer < ActiveRecord::TestCase after { SSTestEdgeSchema.delete_all } - it 'handle dollar symbols' do + it "handle dollar symbols" do SSTestDollarTableName.create! SSTestDollarTableName.limit(20).offset(1) end - it 'models can use tinyint pk tables' do - obj = SSTestTinyintPk.create! name: '1' - _(['Fixnum', 'Integer']).must_include obj.id.class.name + it "models can use tinyint pk tables" do + obj = SSTestTinyintPk.create! name: "1" + _(["Fixnum", "Integer"]).must_include obj.id.class.name _(SSTestTinyintPk.find(obj.id)).must_equal obj end - it 'be able to complex count tables with no primary key' do + it "be able to complex count tables with no primary key" do SSTestNoPkData.delete_all 10.times { |n| SSTestNoPkData.create! name: "Test#{n}" } - assert_equal 1, SSTestNoPkData.where(name: 'Test5').count + assert_equal 1, SSTestNoPkData.where(name: "Test5").count end - it 'quote table names properly even when they are views' do + it "quote table names properly even when they are views" do obj = SSTestQuotedTable.create! assert_nothing_raised { assert SSTestQuotedTable.first } obj = SSTestQuotedTableUser.create! @@ -34,40 +34,40 @@ class SpecificSchemaTestSQLServer < ActiveRecord::TestCase assert_nothing_raised { assert SSTestQuotedView2.first } end - it 'cope with multi line defaults' do + it "cope with multi line defaults" do default = SSTestStringDefault.new assert_equal "Some long default with a\nnew line.", default.string_with_multiline_default end - it 'default strings before save' do + it "default strings before save" do default = SSTestStringDefault.new assert_nil default.string_with_null_default - assert_equal 'null', default.string_with_pretend_null_one - assert_equal '(null)', default.string_with_pretend_null_two - assert_equal 'NULL', default.string_with_pretend_null_three - assert_equal '(NULL)', default.string_with_pretend_null_four - assert_equal '(3)', default.string_with_pretend_paren_three + assert_equal "null", default.string_with_pretend_null_one + assert_equal "(null)", default.string_with_pretend_null_two + assert_equal "NULL", default.string_with_pretend_null_three + assert_equal "(NULL)", default.string_with_pretend_null_four + assert_equal "(3)", default.string_with_pretend_paren_three end - it 'default strings after save' do + it "default strings after save" do default = SSTestStringDefault.create assert_nil default.string_with_null_default - assert_equal 'null', default.string_with_pretend_null_one - assert_equal '(null)', default.string_with_pretend_null_two - assert_equal 'NULL', default.string_with_pretend_null_three - assert_equal '(NULL)', default.string_with_pretend_null_four + assert_equal "null", default.string_with_pretend_null_one + assert_equal "(null)", default.string_with_pretend_null_two + assert_equal "NULL", default.string_with_pretend_null_three + assert_equal "(NULL)", default.string_with_pretend_null_four end - it 'default objects work' do - obj = SSTestObjectDefault.create! name: 'MetaSkills' - _(obj.date).must_be_nil 'since this is set on insert' + it "default objects work" do + obj = SSTestObjectDefault.create! name: "MetaSkills" + _(obj.date).must_be_nil "since this is set on insert" _(obj.reload.date).must_be_instance_of Date end - it 'allows datetime2 as timestamps' do - _(SSTestBooking.columns_hash['created_at'].sql_type).must_equal 'datetime2(7)' - _(SSTestBooking.columns_hash['updated_at'].sql_type).must_equal 'datetime2(7)' - obj1 = SSTestBooking.new name: 'test1' + it "allows datetime2 as timestamps" do + _(SSTestBooking.columns_hash["created_at"].sql_type).must_equal "datetime2(7)" + _(SSTestBooking.columns_hash["updated_at"].sql_type).must_equal "datetime2(7)" + obj1 = SSTestBooking.new name: "test1" obj1.save! _(obj1.created_at).must_be_instance_of Time _(obj1.updated_at).must_be_instance_of Time @@ -75,35 +75,35 @@ class SpecificSchemaTestSQLServer < ActiveRecord::TestCase # Natural primary keys. - it 'work with identity inserts' do - record = SSTestNaturalPkData.new name: 'Test', description: 'Natural identity inserts.' - record.id = '12345ABCDE' + it "work with identity inserts" do + record = SSTestNaturalPkData.new name: "Test", description: "Natural identity inserts." + record.id = "12345ABCDE" assert record.save - assert_equal '12345ABCDE', record.reload.id + assert_equal "12345ABCDE", record.reload.id end - it 'work with identity inserts when the key is an int' do - record = SSTestNaturalPkIntData.new name: 'Test', description: 'Natural identity inserts.' + it "work with identity inserts when the key is an int" do + record = SSTestNaturalPkIntData.new name: "Test", description: "Natural identity inserts." record.id = 12 assert record.save assert_equal 12, record.reload.id end - it 'use primary key for row table order in pagination sql' do + it "use primary key for row table order in pagination sql" do sql = /ORDER BY \[sst_natural_pk_data\]\.\[legacy_id\] ASC OFFSET @0 ROWS FETCH NEXT @1 ROWS ONLY/ assert_sql(sql) { SSTestNaturalPkData.limit(5).offset(5).load } end # Special quoted column - it 'work as normal' do + it "work as normal" do SSTestEdgeSchema.delete_all - r = SSTestEdgeSchema.create! 'crazy]]quote' => 'crazyqoute' - assert SSTestEdgeSchema.columns_hash['crazy]]quote'] - assert_equal r, SSTestEdgeSchema.where('crazy]]quote' => 'crazyqoute').first + r = SSTestEdgeSchema.create! "crazy]]quote" => "crazyqoute" + assert SSTestEdgeSchema.columns_hash["crazy]]quote"] + assert_equal r, SSTestEdgeSchema.where("crazy]]quote" => "crazyqoute").first end - it 'various methods to bypass national quoted columns for any column, but primarily useful for char/varchar' do + it "various methods to bypass national quoted columns for any column, but primarily useful for char/varchar" do value = Class.new do def quoted_id "'T'" @@ -115,14 +115,14 @@ def quoted_id # Using our custom char type data. type = ActiveRecord::Type::SQLServer::Char data = ActiveRecord::Type::SQLServer::Data - assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(char_col: data.new('T', type.new)).first } - assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(varchar_col: data.new('T', type.new)).first } + assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(char_col: data.new("T", type.new)).first } + assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(varchar_col: data.new("T", type.new)).first } # Taking care of everything. - assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(char_col: 'T').first } - assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(varchar_col: 'T').first } + assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(char_col: "T").first } + assert_sql(/@0 = 'T'/) { SSTestDatatypeMigration.where(varchar_col: "T").first } end - it 'can update and hence properly quoted non-national char/varchar columns' do + it "can update and hence properly quoted non-national char/varchar columns" do o = SSTestDatatypeMigration.create! o.varchar_col = "O'Reilly" o.save! @@ -134,28 +134,28 @@ def quoted_id # With column names that have spaces - it 'create record using a custom attribute reader and be able to load it back in' do - value = 'Saved value into a column that has a space in the name.' + it "create record using a custom attribute reader and be able to load it back in" do + value = "Saved value into a column that has a space in the name." record = SSTestEdgeSchema.create! with_spaces: value assert_equal value, SSTestEdgeSchema.find(record.id).with_spaces end # With description column - it 'allow all sorts of ordering without adapter munging it up with special description column' do - SSTestEdgeSchema.create! description: 'A' - SSTestEdgeSchema.create! description: 'B' - SSTestEdgeSchema.create! description: 'C' - assert_equal ['A','B','C'], SSTestEdgeSchema.order('description').map(&:description) - assert_equal ['A','B','C'], SSTestEdgeSchema.order('description asc').map(&:description) - assert_equal ['A','B','C'], SSTestEdgeSchema.order('description ASC').map(&:description) - assert_equal ['C','B','A'], SSTestEdgeSchema.order('description desc').map(&:description) - assert_equal ['C','B','A'], SSTestEdgeSchema.order('description DESC').map(&:description) + it "allow all sorts of ordering without adapter munging it up with special description column" do + SSTestEdgeSchema.create! description: "A" + SSTestEdgeSchema.create! description: "B" + SSTestEdgeSchema.create! description: "C" + assert_equal ["A","B","C"], SSTestEdgeSchema.order("description").map(&:description) + assert_equal ["A","B","C"], SSTestEdgeSchema.order("description asc").map(&:description) + assert_equal ["A","B","C"], SSTestEdgeSchema.order("description ASC").map(&:description) + assert_equal ["C","B","A"], SSTestEdgeSchema.order("description desc").map(&:description) + assert_equal ["C","B","A"], SSTestEdgeSchema.order("description DESC").map(&:description) end # For uniqueidentifier model helpers - it 'returns a new id via connection newid_function' do + it "returns a new id via connection newid_function" do acceptable_uuid = ActiveRecord::ConnectionAdapters::SQLServer::Type::Uuid::ACCEPTABLE_UUID db_uuid = ActiveRecord::Base.connection.newid_function _(db_uuid).must_match(acceptable_uuid) @@ -163,10 +163,10 @@ def quoted_id # with similar table definition in two schemas - it 'returns the correct primary columns' do + it "returns the correct primary columns" do connection = ActiveRecord::Base.connection - assert_equal 'field_1', connection.columns('test.sst_schema_test_mulitple_schema').detect(&:is_primary?).name - assert_equal 'field_2', connection.columns('test2.sst_schema_test_mulitple_schema').detect(&:is_primary?).name + assert_equal "field_1", connection.columns("test.sst_schema_test_mulitple_schema").detect(&:is_primary?).name + assert_equal "field_2", connection.columns("test2.sst_schema_test_mulitple_schema").detect(&:is_primary?).name end end diff --git a/test/cases/transaction_test_sqlserver.rb b/test/cases/transaction_test_sqlserver.rb index f94694e36..aa9f99532 100644 --- a/test/cases/transaction_test_sqlserver.rb +++ b/test/cases/transaction_test_sqlserver.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' -require 'models/ship' -require 'models/developer' +require "cases/helper_sqlserver" +require "models/ship" +require "models/developer" class TransactionTestSQLServer < ActiveRecord::TestCase @@ -10,21 +10,21 @@ class TransactionTestSQLServer < ActiveRecord::TestCase before { delete_ships } - it 'allow ActiveRecord::Rollback to work in 1 transaction block' do + it "allow ActiveRecord::Rollback to work in 1 transaction block" do Ship.transaction do - Ship.create! name: 'Black Pearl' + Ship.create! name: "Black Pearl" raise ActiveRecord::Rollback end assert_no_ships end - it 'allow nested transactions to totally rollback' do + it "allow nested transactions to totally rollback" do begin Ship.transaction do - Ship.create! name: 'Black Pearl' + Ship.create! name: "Black Pearl" Ship.transaction do - Ship.create! name: 'Flying Dutchman' - raise 'HELL' + Ship.create! name: "Flying Dutchman" + raise "HELL" end end rescue Exception => e @@ -32,12 +32,12 @@ class TransactionTestSQLServer < ActiveRecord::TestCase end end - it 'can use an isolation level and reverts back to starting isolation level' do + it "can use an isolation level and reverts back to starting isolation level" do in_level = nil begin_level = connection.user_options_isolation_level _(begin_level).must_match %r{read committed}i Ship.transaction(isolation: :serializable) do - Ship.create! name: 'Black Pearl' + Ship.create! name: "Black Pearl" in_level = connection.user_options_isolation_level end after_level = connection.user_options_isolation_level @@ -45,7 +45,7 @@ class TransactionTestSQLServer < ActiveRecord::TestCase _(after_level).must_match %r{read committed}i end - it 'can use an isolation level and reverts back to starting isolation level under exceptions' do + it "can use an isolation level and reverts back to starting isolation level under exceptions" do _(connection.user_options_isolation_level).must_match %r{read committed}i _(lambda { Ship.transaction(isolation: :serializable) { Ship.create! } @@ -53,7 +53,7 @@ class TransactionTestSQLServer < ActiveRecord::TestCase _(connection.user_options_isolation_level).must_match %r{read committed}i end - describe 'when READ_COMMITTED_SNAPSHOT is set' do + describe "when READ_COMMITTED_SNAPSHOT is set" do before do connection.execute "ALTER DATABASE [#{connection.current_database}] SET ALLOW_SNAPSHOT_ISOLATION ON" connection.execute "ALTER DATABASE [#{connection.current_database}] SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE" @@ -64,11 +64,11 @@ class TransactionTestSQLServer < ActiveRecord::TestCase connection.execute "ALTER DATABASE [#{connection.current_database}] SET READ_COMMITTED_SNAPSHOT OFF WITH ROLLBACK IMMEDIATE" end - it 'should use READ COMMITTED as an isolation level' do + it "should use READ COMMITTED as an isolation level" do _(connection.user_options_isolation_level).must_match "read committed snapshot" Ship.transaction(isolation: :serializable) do - Ship.create! name: 'Black Pearl' + Ship.create! name: "Black Pearl" end # We're actually testing that the isolation level was correctly reset to diff --git a/test/cases/trigger_test_sqlserver.rb b/test/cases/trigger_test_sqlserver.rb index 88ccf157e..fc0a6598a 100644 --- a/test/cases/trigger_test_sqlserver.rb +++ b/test/cases/trigger_test_sqlserver.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class SQLServerTriggerTest < ActiveRecord::TestCase after { exclude_output_inserted_table_names.clear } @@ -9,22 +9,22 @@ class SQLServerTriggerTest < ActiveRecord::TestCase ActiveRecord::ConnectionAdapters::SQLServerAdapter.exclude_output_inserted_table_names end - it 'can insert into a table with output inserted - with a true setting for table name' do - exclude_output_inserted_table_names['sst_table_with_trigger'] = true + it "can insert into a table with output inserted - with a true setting for table name" do + exclude_output_inserted_table_names["sst_table_with_trigger"] = true assert SSTestTriggerHistory.all.empty? - obj = SSTestTrigger.create! event_name: 'test trigger' - _(['Fixnum', 'Integer']).must_include obj.id.class.name - _(obj.event_name).must_equal 'test trigger' + obj = SSTestTrigger.create! event_name: "test trigger" + _(["Fixnum", "Integer"]).must_include obj.id.class.name + _(obj.event_name).must_equal "test trigger" _(obj.id).must_be :present? _(obj.id.to_s).must_equal SSTestTriggerHistory.first.id_source end - it 'can insert into a table with output inserted - with a uniqueidentifier value' do - exclude_output_inserted_table_names['sst_table_with_uuid_trigger'] = 'uniqueidentifier' + it "can insert into a table with output inserted - with a uniqueidentifier value" do + exclude_output_inserted_table_names["sst_table_with_uuid_trigger"] = "uniqueidentifier" assert SSTestTriggerHistory.all.empty? - obj = SSTestTriggerUuid.create! event_name: 'test uuid trigger' - _(obj.id.class.name).must_equal 'String' - _(obj.event_name).must_equal 'test uuid trigger' + obj = SSTestTriggerUuid.create! event_name: "test uuid trigger" + _(obj.id.class.name).must_equal "String" + _(obj.event_name).must_equal "test uuid trigger" _(obj.id).must_be :present? _(obj.id.to_s).must_equal SSTestTriggerHistory.first.id_source end diff --git a/test/cases/utils_test_sqlserver.rb b/test/cases/utils_test_sqlserver.rb index 8274a93af..c89074a21 100644 --- a/test/cases/utils_test_sqlserver.rb +++ b/test/cases/utils_test_sqlserver.rb @@ -1,56 +1,56 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class UtilsTestSQLServer < ActiveRecord::TestCase - it '.quote_string' do + it ".quote_string" do _(SQLServer::Utils.quote_string("I'll store this in C:\\Users")).must_equal "I''ll store this in C:\\Users" end - it '.unquote_string' do + it ".unquote_string" do _(SQLServer::Utils.unquote_string("I''ll store this in C:\\Users")).must_equal "I'll store this in C:\\Users" end - it '.quoted_raw' do + it ".quoted_raw" do _(SQLServer::Utils.quoted_raw("some.Name")).must_equal "[some.Name]" end - describe '.extract_identifiers constructor and thus SQLServer::Utils::Name value object' do + describe ".extract_identifiers constructor and thus SQLServer::Utils::Name value object" do let(:valid_names) { valid_names_unquoted + valid_names_quoted } let(:valid_names_unquoted) {[ - 'server.database.schema.object', - 'server.database..object', - 'server..schema.object', - 'server...object', - 'database.schema.object', - 'database..object', - 'schema.object', - 'object' + "server.database.schema.object", + "server.database..object", + "server..schema.object", + "server...object", + "database.schema.object", + "database..object", + "schema.object", + "object" ]} let(:valid_names_quoted) {[ - '[server].[database].[schema].[object]', - '[server].[database]..[object]', - '[server]..[schema].[object]', - '[server]...[object]', - '[database].[schema].[object]', - '[database]..[object]', - '[schema].[object]', - '[object]' + "[server].[database].[schema].[object]", + "[server].[database]..[object]", + "[server]..[schema].[object]", + "[server]...[object]", + "[database].[schema].[object]", + "[database]..[object]", + "[schema].[object]", + "[object]" ]} let(:server_names) { valid_names.partition { |name| name =~ /server/ } } let(:database_names) { valid_names.partition { |name| name =~ /database/ } } let(:schema_names) { valid_names.partition { |name| name =~ /schema/ } } - it 'extracts and returns #object identifier unquoted by default or quoted as needed' do + it "extracts and returns #object identifier unquoted by default or quoted as needed" do valid_names.each do |n| name = extract_identifiers(n) - _(name.object).must_equal 'object', "With #{n.inspect} for #object" - _(name.object_quoted).must_equal '[object]', "With #{n.inspect} for #object_quoted" + _(name.object).must_equal "object", "With #{n.inspect} for #object" + _(name.object_quoted).must_equal "[object]", "With #{n.inspect} for #object_quoted" end end @@ -72,52 +72,52 @@ class UtilsTestSQLServer < ActiveRecord::TestCase end - it 'does not blow up on nil or blank string name' do + it "does not blow up on nil or blank string name" do _(extract_identifiers(nil).object).must_be_nil - _(extract_identifiers(' ').object).must_be_nil + _(extract_identifiers(" ").object).must_be_nil end - it 'has a #quoted that returns a fully quoted name with all identifiers as orginially passed in' do - _(extract_identifiers('object').quoted).must_equal '[object]' - _(extract_identifiers('server.database..object').quoted).must_equal '[server].[database]..[object]' - _(extract_identifiers('[server]...[object]').quoted).must_equal '[server]...[object]' + it "has a #quoted that returns a fully quoted name with all identifiers as orginially passed in" do + _(extract_identifiers("object").quoted).must_equal "[object]" + _(extract_identifiers("server.database..object").quoted).must_equal "[server].[database]..[object]" + _(extract_identifiers("[server]...[object]").quoted).must_equal "[server]...[object]" end - it 'can take a symbol argument' do - _(extract_identifiers(:object).object).must_equal 'object' + it "can take a symbol argument" do + _(extract_identifiers(:object).object).must_equal "object" end - it 'allows identifiers with periods to work' do - _(extract_identifiers('[obj.name]').quoted).must_equal '[obj.name]' - _(extract_identifiers('[obj.name].[foo]').quoted).must_equal '[obj.name].[foo]' + it "allows identifiers with periods to work" do + _(extract_identifiers("[obj.name]").quoted).must_equal "[obj.name]" + _(extract_identifiers("[obj.name].[foo]").quoted).must_equal "[obj.name].[foo]" end - it 'should indicate if a name is fully qualitified' do - _(extract_identifiers('object').fully_qualified?).must_equal false - _(extract_identifiers('schema.object').fully_qualified?).must_equal false - _(extract_identifiers('database.schema.object').fully_qualified?).must_equal false - _(extract_identifiers('database.object').fully_qualified?).must_equal false - _(extract_identifiers('server...object').fully_qualified?).must_equal false - _(extract_identifiers('server.database..object').fully_qualified?).must_equal false - _(extract_identifiers('server.database.schema.object').fully_qualified?).must_equal true - _(extract_identifiers('server.database.schema.').fully_qualified?).must_equal true - _(extract_identifiers('[obj.name]').fully_qualified?).must_equal false - _(extract_identifiers('[schema].[obj.name]').fully_qualified?).must_equal false - _(extract_identifiers('[database].[schema].[obj.name]').fully_qualified?).must_equal false - _(extract_identifiers('[database].[obj.name]').fully_qualified?).must_equal false - _(extract_identifiers('[server.name]...[obj.name]').fully_qualified?).must_equal false - _(extract_identifiers('[server.name].[database]..[obj.name]').fully_qualified?).must_equal false - _(extract_identifiers('[server.name].[database].[schema].[obj.name]').fully_qualified?).must_equal true - _(extract_identifiers('[server.name].[database].[schema].').fully_qualified?).must_equal true + it "should indicate if a name is fully qualitified" do + _(extract_identifiers("object").fully_qualified?).must_equal false + _(extract_identifiers("schema.object").fully_qualified?).must_equal false + _(extract_identifiers("database.schema.object").fully_qualified?).must_equal false + _(extract_identifiers("database.object").fully_qualified?).must_equal false + _(extract_identifiers("server...object").fully_qualified?).must_equal false + _(extract_identifiers("server.database..object").fully_qualified?).must_equal false + _(extract_identifiers("server.database.schema.object").fully_qualified?).must_equal true + _(extract_identifiers("server.database.schema.").fully_qualified?).must_equal true + _(extract_identifiers("[obj.name]").fully_qualified?).must_equal false + _(extract_identifiers("[schema].[obj.name]").fully_qualified?).must_equal false + _(extract_identifiers("[database].[schema].[obj.name]").fully_qualified?).must_equal false + _(extract_identifiers("[database].[obj.name]").fully_qualified?).must_equal false + _(extract_identifiers("[server.name]...[obj.name]").fully_qualified?).must_equal false + _(extract_identifiers("[server.name].[database]..[obj.name]").fully_qualified?).must_equal false + _(extract_identifiers("[server.name].[database].[schema].[obj.name]").fully_qualified?).must_equal true + _(extract_identifiers("[server.name].[database].[schema].").fully_qualified?).must_equal true end - it 'can return fully qualified quoted table name' do - name = extract_identifiers('[my.server].db.schema.') - _(name.fully_qualified_database_quoted).must_equal '[my.server].[db]' - name = extract_identifiers('[server.name].[database].[schema].[object]') - _(name.fully_qualified_database_quoted).must_equal '[server.name].[database]' - name = extract_identifiers('server.database.schema.object') - _(name.fully_qualified_database_quoted).must_equal '[server].[database]' + it "can return fully qualified quoted table name" do + name = extract_identifiers("[my.server].db.schema.") + _(name.fully_qualified_database_quoted).must_equal "[my.server].[db]" + name = extract_identifiers("[server.name].[database].[schema].[object]") + _(name.fully_qualified_database_quoted).must_equal "[server.name].[database]" + name = extract_identifiers("server.database.schema.object") + _(name.fully_qualified_database_quoted).must_equal "[server].[database]" end end diff --git a/test/cases/uuid_test_sqlserver.rb b/test/cases/uuid_test_sqlserver.rb index 4a96c29ce..a79a51e04 100644 --- a/test/cases/uuid_test_sqlserver.rb +++ b/test/cases/uuid_test_sqlserver.rb @@ -1,46 +1,46 @@ # frozen_string_literal: true -require 'cases/helper_sqlserver' +require "cases/helper_sqlserver" class SQLServerUuidTest < ActiveRecord::TestCase let(:acceptable_uuid) { ActiveRecord::ConnectionAdapters::SQLServer::Type::Uuid::ACCEPTABLE_UUID } - it 'has a uuid primary key' do - _(SSTestUuid.columns_hash['id'].type).must_equal :uuid + it "has a uuid primary key" do + _(SSTestUuid.columns_hash["id"].type).must_equal :uuid assert SSTestUuid.primary_key end - it 'can create with a new pk' do + it "can create with a new pk" do obj = SSTestUuid.create! _(obj.id).must_be :present? _(obj.id).must_match acceptable_uuid end - it 'can create other uuid column on reload' do + it "can create other uuid column on reload" do obj = SSTestUuid.create! obj.reload _(obj.other_uuid).must_match acceptable_uuid end - it 'can find uuid pk via connection' do - _(connection.primary_key(SSTestUuid.table_name)).must_equal 'id' + it "can find uuid pk via connection" do + _(connection.primary_key(SSTestUuid.table_name)).must_equal "id" end - it 'changing column default' do + it "changing column default" do table_name = SSTestUuid.table_name connection.add_column table_name, :thingy, :uuid, null: false, default: "NEWSEQUENTIALID()" SSTestUuid.reset_column_information - column = SSTestUuid.columns_hash['thingy'] + column = SSTestUuid.columns_hash["thingy"] _(column.default_function).must_equal "newsequentialid()" # Now to a different function. connection.change_column table_name, :thingy, :uuid, null: false, default: "NEWID()" SSTestUuid.reset_column_information - column = SSTestUuid.columns_hash['thingy'] + column = SSTestUuid.columns_hash["thingy"] _(column.default_function).must_equal "newid()" end - it 'can insert even when use_output_inserted to false ' do + it "can insert even when use_output_inserted to false " do obj = with_use_output_inserted_disabled { SSTestUuid.create!(name: "😢") } _(obj.id).must_be :nil? end diff --git a/test/debug.rb b/test/debug.rb index 1b1f8faad..dc918ddb0 100644 --- a/test/debug.rb +++ b/test/debug.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true # require 'rails/all' -require 'tiny_tds' +require "tiny_tds" c = TinyTds::Client.new( - host: ENV['CI_AZURE_HOST'], - username: 'rails', - password: ENV['CI_AZURE_PASS'], - database: 'activerecord_unittest', + host: ENV["CI_AZURE_HOST"], + username: "rails", + password: ENV["CI_AZURE_PASS"], + database: "activerecord_unittest", azure: true, - tds_version: '7.3' + tds_version: "7.3" ) puts c.execute("SELECT 1 AS [one]").each diff --git a/test/migrations/create_clients_and_change_column_null.rb b/test/migrations/create_clients_and_change_column_null.rb index 18f74cdcf..7f527806c 100644 --- a/test/migrations/create_clients_and_change_column_null.rb +++ b/test/migrations/create_clients_and_change_column_null.rb @@ -11,7 +11,7 @@ def up end change_column :clients, :name, :string, limit: 15 - change_column :clients, :code, :string, default: 'n/a' + change_column :clients, :code, :string, default: "n/a" change_column :clients, :value, :decimal, precision: 32, scale: 8 change_column_null :clients, :name, false diff --git a/test/migrations/transaction_table/1_table_will_never_be_created.rb b/test/migrations/transaction_table/1_table_will_never_be_created.rb index dfcec8368..769ce7967 100644 --- a/test/migrations/transaction_table/1_table_will_never_be_created.rb +++ b/test/migrations/transaction_table/1_table_will_never_be_created.rb @@ -4,7 +4,7 @@ class TableWillNeverBeCreated < ActiveRecord::Migration def self.up create_table(:sqlserver_trans_table1) { } - create_table(:sqlserver_trans_table2) { raise('HELL') } + create_table(:sqlserver_trans_table2) { raise("HELL") } end def self.down diff --git a/test/models/sqlserver/booking.rb b/test/models/sqlserver/booking.rb index 4b70013d1..e3f70a5c5 100644 --- a/test/models/sqlserver/booking.rb +++ b/test/models/sqlserver/booking.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestBooking < ActiveRecord::Base - self.table_name = 'sst_bookings' + self.table_name = "sst_bookings" end diff --git a/test/models/sqlserver/customers_view.rb b/test/models/sqlserver/customers_view.rb index ef3ad2160..f362216cb 100644 --- a/test/models/sqlserver/customers_view.rb +++ b/test/models/sqlserver/customers_view.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestCustomersView < ActiveRecord::Base - self.table_name = 'sst_customers_view' + self.table_name = "sst_customers_view" end diff --git a/test/models/sqlserver/dollar_table_name.rb b/test/models/sqlserver/dollar_table_name.rb index 8b20e5275..ba0fc1596 100644 --- a/test/models/sqlserver/dollar_table_name.rb +++ b/test/models/sqlserver/dollar_table_name.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestDollarTableName < ActiveRecord::Base - self.table_name = 'sst_my$strange_table' + self.table_name = "sst_my$strange_table" end diff --git a/test/models/sqlserver/edge_schema.rb b/test/models/sqlserver/edge_schema.rb index 30c79ad54..40d03c3ab 100644 --- a/test/models/sqlserver/edge_schema.rb +++ b/test/models/sqlserver/edge_schema.rb @@ -2,7 +2,7 @@ class SSTestEdgeSchema < ActiveRecord::Base - self.table_name = 'sst_edge_schemas' + self.table_name = "sst_edge_schemas" def with_spaces read_attribute :'with spaces' diff --git a/test/models/sqlserver/fk_has_fk.rb b/test/models/sqlserver/fk_has_fk.rb index 95486c232..6214b5055 100644 --- a/test/models/sqlserver/fk_has_fk.rb +++ b/test/models/sqlserver/fk_has_fk.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestHasFk < ActiveRecord::Base - self.table_name = 'sst_has_fks' + self.table_name = "sst_has_fks" end diff --git a/test/models/sqlserver/fk_has_pk.rb b/test/models/sqlserver/fk_has_pk.rb index 1bd2506e8..814e22480 100644 --- a/test/models/sqlserver/fk_has_pk.rb +++ b/test/models/sqlserver/fk_has_pk.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestHasPk < ActiveRecord::Base - self.table_name = 'sst_has_pks' + self.table_name = "sst_has_pks" end diff --git a/test/models/sqlserver/natural_pk_data.rb b/test/models/sqlserver/natural_pk_data.rb index 01cfdca06..9da2a6c11 100644 --- a/test/models/sqlserver/natural_pk_data.rb +++ b/test/models/sqlserver/natural_pk_data.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true class SSTestNaturalPkData < ActiveRecord::Base - self.table_name = 'sst_natural_pk_data' - self.primary_key = 'legacy_id' + self.table_name = "sst_natural_pk_data" + self.primary_key = "legacy_id" end diff --git a/test/models/sqlserver/natural_pk_int_data.rb b/test/models/sqlserver/natural_pk_int_data.rb index 4eb770809..294922e0f 100644 --- a/test/models/sqlserver/natural_pk_int_data.rb +++ b/test/models/sqlserver/natural_pk_int_data.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestNaturalPkIntData < ActiveRecord::Base - self.table_name = 'sst_natural_pk_int_data' + self.table_name = "sst_natural_pk_int_data" end diff --git a/test/models/sqlserver/no_pk_data.rb b/test/models/sqlserver/no_pk_data.rb index b9ef19ba3..1a5d15d36 100644 --- a/test/models/sqlserver/no_pk_data.rb +++ b/test/models/sqlserver/no_pk_data.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestNoPkData < ActiveRecord::Base - self.table_name = 'sst_no_pk_data' + self.table_name = "sst_no_pk_data" end diff --git a/test/models/sqlserver/object_default.rb b/test/models/sqlserver/object_default.rb index 5ba7d4912..728c4a802 100644 --- a/test/models/sqlserver/object_default.rb +++ b/test/models/sqlserver/object_default.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestObjectDefault < ActiveRecord::Base - self.table_name = 'sst_defaultobjects' + self.table_name = "sst_defaultobjects" end diff --git a/test/models/sqlserver/quoted_table.rb b/test/models/sqlserver/quoted_table.rb index bee44dd9a..e387bb3df 100644 --- a/test/models/sqlserver/quoted_table.rb +++ b/test/models/sqlserver/quoted_table.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true class SSTestQuotedTable < ActiveRecord::Base - self.table_name = '[sst_quoted-table]' + self.table_name = "[sst_quoted-table]" end class SSTestQuotedTableUser < ActiveRecord::Base - self.table_name = '[dbo].[sst_quoted-table]' + self.table_name = "[dbo].[sst_quoted-table]" end diff --git a/test/models/sqlserver/quoted_view_1.rb b/test/models/sqlserver/quoted_view_1.rb index 587f28691..5e816ae8c 100644 --- a/test/models/sqlserver/quoted_view_1.rb +++ b/test/models/sqlserver/quoted_view_1.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestQuotedView1 < ActiveRecord::Base - self.table_name = 'sst_quoted-view1' + self.table_name = "sst_quoted-view1" end diff --git a/test/models/sqlserver/quoted_view_2.rb b/test/models/sqlserver/quoted_view_2.rb index d993c274c..be9d62f46 100644 --- a/test/models/sqlserver/quoted_view_2.rb +++ b/test/models/sqlserver/quoted_view_2.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestQuotedView2 < ActiveRecord::Base - self.table_name = 'sst_quoted-view2' + self.table_name = "sst_quoted-view2" end diff --git a/test/models/sqlserver/sst_memory.rb b/test/models/sqlserver/sst_memory.rb index 5abbfd2e6..b4d26e602 100644 --- a/test/models/sqlserver/sst_memory.rb +++ b/test/models/sqlserver/sst_memory.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTMemory < ActiveRecord::Base - self.table_name = 'sst_memory' + self.table_name = "sst_memory" end diff --git a/test/models/sqlserver/string_default.rb b/test/models/sqlserver/string_default.rb index d797a401e..f4c2db47c 100644 --- a/test/models/sqlserver/string_default.rb +++ b/test/models/sqlserver/string_default.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestStringDefault < ActiveRecord::Base - self.table_name = 'sst_string_defaults' + self.table_name = "sst_string_defaults" end diff --git a/test/models/sqlserver/string_defaults_big_view.rb b/test/models/sqlserver/string_defaults_big_view.rb index 50bfcbb43..af8e6da6d 100644 --- a/test/models/sqlserver/string_defaults_big_view.rb +++ b/test/models/sqlserver/string_defaults_big_view.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestStringDefaultsBigView < ActiveRecord::Base - self.table_name = 'sst_string_defaults_big_view' + self.table_name = "sst_string_defaults_big_view" end diff --git a/test/models/sqlserver/string_defaults_view.rb b/test/models/sqlserver/string_defaults_view.rb index 6bf3c8b6b..4bcb4fe60 100644 --- a/test/models/sqlserver/string_defaults_view.rb +++ b/test/models/sqlserver/string_defaults_view.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestStringDefaultsView < ActiveRecord::Base - self.table_name = 'sst_string_defaults_view' + self.table_name = "sst_string_defaults_view" end diff --git a/test/models/sqlserver/tinyint_pk.rb b/test/models/sqlserver/tinyint_pk.rb index ca52f8de5..55c05c1a4 100644 --- a/test/models/sqlserver/tinyint_pk.rb +++ b/test/models/sqlserver/tinyint_pk.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestTinyintPk < ActiveRecord::Base - self.table_name = 'sst_tinyint_pk' + self.table_name = "sst_tinyint_pk" end diff --git a/test/models/sqlserver/trigger.rb b/test/models/sqlserver/trigger.rb index 50e4942be..3293cb6eb 100644 --- a/test/models/sqlserver/trigger.rb +++ b/test/models/sqlserver/trigger.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true class SSTestTrigger < ActiveRecord::Base - self.table_name = 'sst_table_with_trigger' + self.table_name = "sst_table_with_trigger" end class SSTestTriggerUuid < ActiveRecord::Base - self.table_name = 'sst_table_with_uuid_trigger' + self.table_name = "sst_table_with_uuid_trigger" end diff --git a/test/models/sqlserver/trigger_history.rb b/test/models/sqlserver/trigger_history.rb index c358d935d..d93bc4384 100644 --- a/test/models/sqlserver/trigger_history.rb +++ b/test/models/sqlserver/trigger_history.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestTriggerHistory < ActiveRecord::Base - self.table_name = 'sst_table_with_trigger_history' + self.table_name = "sst_table_with_trigger_history" end diff --git a/test/models/sqlserver/upper.rb b/test/models/sqlserver/upper.rb index 05432b476..0fa400977 100644 --- a/test/models/sqlserver/upper.rb +++ b/test/models/sqlserver/upper.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestUpper < ActiveRecord::Base - self.table_name = 'sst_upper_tests' + self.table_name = "sst_upper_tests" end diff --git a/test/models/sqlserver/uppered.rb b/test/models/sqlserver/uppered.rb index bb9dce777..9d025b0ab 100644 --- a/test/models/sqlserver/uppered.rb +++ b/test/models/sqlserver/uppered.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestUppered < ActiveRecord::Base - self.table_name = 'SST_UPPER_TESTS' + self.table_name = "SST_UPPER_TESTS" end diff --git a/test/models/sqlserver/uuid.rb b/test/models/sqlserver/uuid.rb index e6eea62e3..91da8fd9a 100644 --- a/test/models/sqlserver/uuid.rb +++ b/test/models/sqlserver/uuid.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class SSTestUuid < ActiveRecord::Base - self.table_name = 'sst_uuids' + self.table_name = "sst_uuids" end diff --git a/test/schema/sqlserver_specific_schema.rb b/test/schema/sqlserver_specific_schema.rb index eefcb363d..35b018b51 100644 --- a/test/schema/sqlserver_specific_schema.rb +++ b/test/schema/sqlserver_specific_schema.rb @@ -45,28 +45,28 @@ # Edge Cases - if ENV['IN_MEMORY_OLTP'] && supports_in_memory_oltp? - create_table 'sst_memory', force: true, id: false, - options: 'WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA)' do |t| + if ENV["IN_MEMORY_OLTP"] && supports_in_memory_oltp? + create_table "sst_memory", force: true, id: false, + options: "WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA)" do |t| t.primary_key_nonclustered :id t.string :name t.timestamps end end - create_table 'sst_bookings', force: true do |t| + create_table "sst_bookings", force: true do |t| t.string :name t.datetime2 :created_at, null: false t.datetime2 :updated_at, null: false end - create_table 'sst_uuids', force: true, id: :uuid do |t| + create_table "sst_uuids", force: true, id: :uuid do |t| t.string :name - t.uuid :other_uuid, default: 'NEWID()' + t.uuid :other_uuid, default: "NEWID()" t.uuid :uuid_nil_default, default: nil end - create_table 'sst_my$strange_table', force: true do |t| + create_table "sst_my$strange_table", force: true do |t| t.string :name end @@ -79,7 +79,7 @@ t.string :name end - create_table 'sst_quoted-table', force: true do |t| + create_table "sst_quoted-table", force: true do |t| end execute "IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'sst_quoted-view1') DROP VIEW [sst_quoted-view1]" execute "CREATE VIEW [sst_quoted-view1] AS SELECT * FROM [sst_quoted-table]" @@ -88,18 +88,18 @@ create_table :sst_string_defaults, force: true do |t| t.column :string_with_null_default, :string, default: nil - t.column :string_with_pretend_null_one, :string, default: 'null' - t.column :string_with_pretend_null_two, :string, default: '(null)' - t.column :string_with_pretend_null_three, :string, default: 'NULL' - t.column :string_with_pretend_null_four, :string, default: '(NULL)' - t.column :string_with_pretend_paren_three, :string, default: '(3)' + t.column :string_with_pretend_null_one, :string, default: "null" + t.column :string_with_pretend_null_two, :string, default: "(null)" + t.column :string_with_pretend_null_three, :string, default: "NULL" + t.column :string_with_pretend_null_four, :string, default: "(NULL)" + t.column :string_with_pretend_paren_three, :string, default: "(3)" t.column :string_with_multiline_default, :string, default: "Some long default with a\nnew line." end create_table :sst_edge_schemas, force: true do |t| t.string :description - t.column 'crazy]]quote', :string - t.column 'with spaces', :string + t.column "crazy]]quote", :string + t.column "with spaces", :string end execute "IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'sst_natural_pk_data') DROP TABLE sst_natural_pk_data" @@ -132,7 +132,7 @@ execute "DROP DEFAULT [sst_getdateobject];" rescue nil execute "CREATE DEFAULT [sst_getdateobject] AS getdate();" rescue nil - create_table 'sst_defaultobjects', force: true do |t| + create_table "sst_defaultobjects", force: true do |t| t.string :name t.date :date end diff --git a/test/support/core_ext/query_cache.rb b/test/support/core_ext/query_cache.rb index 1debd57db..c695b2147 100644 --- a/test/support/core_ext/query_cache.rb +++ b/test/support/core_ext/query_cache.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'active_record/connection_adapters/sqlserver_adapter' +require "active_record/connection_adapters/sqlserver_adapter" module SqlIgnoredCache extend ActiveSupport::Concern diff --git a/test/support/load_schema_sqlserver.rb b/test/support/load_schema_sqlserver.rb index 4b8a3c08b..a1641383f 100644 --- a/test/support/load_schema_sqlserver.rb +++ b/test/support/load_schema_sqlserver.rb @@ -6,15 +6,15 @@ module SQLServer extend self def schema_root - File.join ARTest::SQLServer.test_root_sqlserver, 'schema' + File.join ARTest::SQLServer.test_root_sqlserver, "schema" end def schema_file - File.join schema_root, 'sqlserver_specific_schema.rb' + File.join schema_root, "sqlserver_specific_schema.rb" end def schema_datatypes_2012_file - File.join schema_root, 'datatypes', '2012.sql' + File.join schema_root, "datatypes", "2012.sql" end def load_schema diff --git a/test/support/minitest_sqlserver.rb b/test/support/minitest_sqlserver.rb index 4e5574ef0..3fb0c9ed0 100644 --- a/test/support/minitest_sqlserver.rb +++ b/test/support/minitest_sqlserver.rb @@ -1,3 +1,3 @@ # frozen_string_literal: true -require 'minitest-spec-rails/init/active_support' +require "minitest-spec-rails/init/active_support" diff --git a/test/support/paths_sqlserver.rb b/test/support/paths_sqlserver.rb index a495474f2..fe4421131 100644 --- a/test/support/paths_sqlserver.rb +++ b/test/support/paths_sqlserver.rb @@ -6,27 +6,27 @@ module SQLServer extend self def root_sqlserver - File.expand_path File.join(File.dirname(__FILE__), '..', '..') + File.expand_path File.join(File.dirname(__FILE__), "..", "..") end def test_root_sqlserver - File.join root_sqlserver, 'test' + File.join root_sqlserver, "test" end def root_activerecord - File.join Gem.loaded_specs['rails'].full_gem_path, 'activerecord' + File.join Gem.loaded_specs["rails"].full_gem_path, "activerecord" end def root_activerecord_lib - File.join root_activerecord, 'lib' + File.join root_activerecord, "lib" end def root_activerecord_test - File.join root_activerecord, 'test' + File.join root_activerecord, "test" end def test_load_paths - ['lib', 'test', root_activerecord_lib, root_activerecord_test] + ["lib", "test", root_activerecord_lib, root_activerecord_test] end def add_to_load_paths! @@ -34,15 +34,15 @@ def add_to_load_paths! end def migrations_root - File.join test_root_sqlserver, 'migrations' + File.join test_root_sqlserver, "migrations" end def arconfig_file - File.join test_root_sqlserver, 'config.yml' + File.join test_root_sqlserver, "config.yml" end def arconfig_file_env! - ENV['ARCONFIG'] = arconfig_file + ENV["ARCONFIG"] = arconfig_file end end diff --git a/test/support/rake_helpers.rb b/test/support/rake_helpers.rb index db04b5bba..413faa576 100644 --- a/test/support/rake_helpers.rb +++ b/test/support/rake_helpers.rb @@ -1,24 +1,24 @@ # frozen_string_literal: true -SQLSERVER_HELPER = 'test/cases/helper_sqlserver.rb' -SQLSERVER_COERCED = 'test/cases/coerced_tests.rb' +SQLSERVER_HELPER = "test/cases/helper_sqlserver.rb" +SQLSERVER_COERCED = "test/cases/coerced_tests.rb" def env_ar_test_files - return unless ENV['TEST_FILES_AR'] && !ENV['TEST_FILES_AR'].empty? + return unless ENV["TEST_FILES_AR"] && !ENV["TEST_FILES_AR"].empty? @env_ar_test_files ||= begin - ENV['TEST_FILES_AR'].split(',').map { |file| + ENV["TEST_FILES_AR"].split(",").map { |file| File.join ARTest::SQLServer.root_activerecord, file.strip }.sort end end def env_test_files - return unless ENV['TEST_FILES'] && !ENV['TEST_FILES'].empty? - @env_test_files ||= ENV['TEST_FILES'].split(',').map(&:strip) + return unless ENV["TEST_FILES"] && !ENV["TEST_FILES"].empty? + @env_test_files ||= ENV["TEST_FILES"].split(",").map(&:strip) end def sqlserver_cases - @sqlserver_cases ||= Dir.glob('test/cases/*_test_sqlserver.rb') + @sqlserver_cases ||= Dir.glob("test/cases/*_test_sqlserver.rb") end def ar_cases @@ -32,9 +32,9 @@ def test_files [SQLSERVER_HELPER] + env_ar_test_files elsif env_test_files env_test_files - elsif ENV['ONLY_SQLSERVER'] + elsif ENV["ONLY_SQLSERVER"] sqlserver_cases - elsif ENV['ONLY_ACTIVERECORD'] + elsif ENV["ONLY_ACTIVERECORD"] [SQLSERVER_HELPER] + (ar_cases + [SQLSERVER_COERCED]) else [SQLSERVER_HELPER] + (ar_cases + [SQLSERVER_COERCED] + sqlserver_cases) diff --git a/test/support/test_in_memory_oltp.rb b/test/support/test_in_memory_oltp.rb index ba169951c..88c918c92 100644 --- a/test/support/test_in_memory_oltp.rb +++ b/test/support/test_in_memory_oltp.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -if ENV['IN_MEMORY_OLTP'] - require 'config' - require 'active_record' - require 'support/config' - require 'support/connection' +if ENV["IN_MEMORY_OLTP"] + require "config" + require "active_record" + require "support/config" + require "support/connection" ARTest.connect if ActiveRecord::Base.connection.supports_in_memory_oltp? - puts 'Configuring In-Memory OLTP...' - inmem_file = ARTest::SQLServer.test_root_sqlserver, 'schema', 'enable-in-memory-oltp.sql' + puts "Configuring In-Memory OLTP..." + inmem_file = ARTest::SQLServer.test_root_sqlserver, "schema", "enable-in-memory-oltp.sql" inmem_sql = File.read File.join(inmem_file) ActiveRecord::Base.connection.execute(inmem_sql) end