diff options
Diffstat (limited to 'activerecord/test/cases/adapters')
69 files changed, 1716 insertions, 1300 deletions
diff --git a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb index 95d1f6b8a3..2a528b2cb1 100644 --- a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase include ConnectionHelper @@ -21,42 +21,45 @@ class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase def (ActiveRecord::Base.connection).index_name_exists?(*); false; end expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`) " - assert_equal expected, add_index(:people, :last_name, :length => nil) + assert_equal expected, add_index(:people, :last_name, length: nil) expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`(10)) " - assert_equal expected, add_index(:people, :last_name, :length => 10) + assert_equal expected, add_index(:people, :last_name, length: 10) expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(15)) " - assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15) + assert_equal expected, add_index(:people, [:last_name, :first_name], length: 15) + assert_equal expected, add_index(:people, ["last_name", "first_name"], length: 15) expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`) " - assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15}) + assert_equal expected, add_index(:people, [:last_name, :first_name], length: { last_name: 15 }) + assert_equal expected, add_index(:people, ["last_name", "first_name"], length: { last_name: 15 }) expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(10)) " - assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15, :first_name => 10}) + assert_equal expected, add_index(:people, [:last_name, :first_name], length: { last_name: 15, first_name: 10 }) + assert_equal expected, add_index(:people, ["last_name", :first_name], length: { last_name: 15, "first_name" => 10 }) %w(SPATIAL FULLTEXT UNIQUE).each do |type| expected = "CREATE #{type} INDEX `index_people_on_last_name` ON `people` (`last_name`) " - assert_equal expected, add_index(:people, :last_name, :type => type) + assert_equal expected, add_index(:people, :last_name, type: type) end %w(btree hash).each do |using| expected = "CREATE INDEX `index_people_on_last_name` USING #{using} ON `people` (`last_name`) " - assert_equal expected, add_index(:people, :last_name, :using => using) + assert_equal expected, add_index(:people, :last_name, using: using) end expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) " - assert_equal expected, add_index(:people, :last_name, :length => 10, :using => :btree) + assert_equal expected, add_index(:people, :last_name, length: 10, using: :btree) expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) ALGORITHM = COPY" - assert_equal expected, add_index(:people, :last_name, :length => 10, using: :btree, algorithm: :copy) + assert_equal expected, add_index(:people, :last_name, length: 10, using: :btree, algorithm: :copy) assert_raise ArgumentError do add_index(:people, :last_name, algorithm: :coyp) end expected = "CREATE INDEX `index_people_on_last_name_and_first_name` USING btree ON `people` (`last_name`(15), `first_name`(15)) " - assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15, :using => :btree) + assert_equal expected, add_index(:people, [:last_name, :first_name], length: 15, using: :btree) end def test_index_in_create @@ -102,13 +105,13 @@ class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase def test_create_mysql_database_with_encoding assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt) - assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => 'latin1'}) - assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {:charset => :big5, :collation => :big5_chinese_ci}) + assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, charset: "latin1") + assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, charset: :big5, collation: :big5_chinese_ci) end def test_recreate_mysql_database_with_encoding - create_database(:luca, {:charset => 'latin1'}) - assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {:charset => 'latin1'}) + create_database(:luca, charset: "latin1") + assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, charset: "latin1") end def test_add_column @@ -116,11 +119,11 @@ class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase end def test_add_column_with_limit - assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, :limit => 32) + assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, limit: 32) end def test_drop_table_with_specific_database - assert_equal "DROP TABLE `otherdb`.`people`", drop_table('otherdb.people') + assert_equal "DROP TABLE `otherdb`.`people`", drop_table("otherdb.people") end def test_add_timestamps @@ -128,8 +131,8 @@ class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase begin ActiveRecord::Base.connection.create_table :delete_me ActiveRecord::Base.connection.add_timestamps :delete_me, null: true - assert column_present?('delete_me', 'updated_at', 'datetime') - assert column_present?('delete_me', 'created_at', 'datetime') + assert column_present?("delete_me", "updated_at", "datetime") + assert column_present?("delete_me", "created_at", "datetime") ensure ActiveRecord::Base.connection.drop_table :delete_me rescue nil end @@ -142,9 +145,9 @@ class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase ActiveRecord::Base.connection.create_table :delete_me do |t| t.timestamps null: true end - ActiveRecord::Base.connection.remove_timestamps :delete_me, { null: true } - assert !column_present?('delete_me', 'updated_at', 'datetime') - assert !column_present?('delete_me', 'created_at', 'datetime') + ActiveRecord::Base.connection.remove_timestamps :delete_me, null: true + assert !column_present?("delete_me", "updated_at", "datetime") + assert !column_present?("delete_me", "created_at", "datetime") ensure ActiveRecord::Base.connection.drop_table :delete_me rescue nil end @@ -185,6 +188,6 @@ class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase def column_present?(table_name, column_name, type) results = ActiveRecord::Base.connection.select_all("SHOW FIELDS FROM #{table_name} LIKE '#{column_name}'") - results.first && results.first['Type'] == type + results.first && results.first["Type"] == type end end diff --git a/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb b/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb index abdf3dbf5b..8f7c803a21 100644 --- a/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb +++ b/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'models/topic' +require "models/topic" module ActiveRecord module ConnectionAdapters @@ -20,7 +20,7 @@ module ActiveRecord def test_create_question_marks str = "foo?bar" - x = Topic.create!(:title => str, :content => str) + x = Topic.create!(title: str, content: str) x.reload assert_equal str, x.title assert_equal str, x.content @@ -39,7 +39,7 @@ module ActiveRecord def test_create_null_bytes str = "foo\0bar" - x = Topic.create!(:title => str, :content => str) + x = Topic.create!(title: str, content: str) x.reload assert_equal str, x.title assert_equal str, x.content diff --git a/activerecord/test/cases/adapters/mysql2/boolean_test.rb b/activerecord/test/cases/adapters/mysql2/boolean_test.rb index 739bb275ce..2fa39282fb 100644 --- a/activerecord/test/cases/adapters/mysql2/boolean_test.rb +++ b/activerecord/test/cases/adapters/mysql2/boolean_test.rb @@ -86,11 +86,11 @@ class Mysql2BooleanTest < ActiveRecord::Mysql2TestCase end def boolean_column - BooleanType.columns.find { |c| c.name == 'archived' } + BooleanType.columns.find { |c| c.name == "archived" } end def string_column - BooleanType.columns.find { |c| c.name == 'published' } + BooleanType.columns.find { |c| c.name == "published" } end def emulate_booleans(value) diff --git a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb index 9cb05119a2..50ba9ab831 100644 --- a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb +++ b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb @@ -7,46 +7,46 @@ class Mysql2CaseSensitivityTest < ActiveRecord::Mysql2TestCase repair_validations(CollationTest) def test_columns_include_collation_different_from_table - assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation - assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation + assert_equal "utf8_bin", CollationTest.columns_hash["string_cs_column"].collation + assert_equal "utf8_general_ci", CollationTest.columns_hash["string_ci_column"].collation end def test_case_sensitive - assert !CollationTest.columns_hash['string_ci_column'].case_sensitive? - assert CollationTest.columns_hash['string_cs_column'].case_sensitive? + assert !CollationTest.columns_hash["string_ci_column"].case_sensitive? + assert CollationTest.columns_hash["string_cs_column"].case_sensitive? end def test_case_insensitive_comparison_for_ci_column - CollationTest.validates_uniqueness_of(:string_ci_column, :case_sensitive => false) - CollationTest.create!(:string_ci_column => 'A') - invalid = CollationTest.new(:string_ci_column => 'a') + CollationTest.validates_uniqueness_of(:string_ci_column, case_sensitive: false) + CollationTest.create!(string_ci_column: "A") + invalid = CollationTest.new(string_ci_column: "a") queries = assert_sql { invalid.save } ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) } assert_no_match(/lower/i, ci_uniqueness_query) end def test_case_insensitive_comparison_for_cs_column - CollationTest.validates_uniqueness_of(:string_cs_column, :case_sensitive => false) - CollationTest.create!(:string_cs_column => 'A') - invalid = CollationTest.new(:string_cs_column => 'a') + CollationTest.validates_uniqueness_of(:string_cs_column, case_sensitive: false) + CollationTest.create!(string_cs_column: "A") + invalid = CollationTest.new(string_cs_column: "a") queries = assert_sql { invalid.save } - cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/)} + cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) } assert_match(/lower/i, cs_uniqueness_query) end def test_case_sensitive_comparison_for_ci_column - CollationTest.validates_uniqueness_of(:string_ci_column, :case_sensitive => true) - CollationTest.create!(:string_ci_column => 'A') - invalid = CollationTest.new(:string_ci_column => 'A') + CollationTest.validates_uniqueness_of(:string_ci_column, case_sensitive: true) + CollationTest.create!(string_ci_column: "A") + invalid = CollationTest.new(string_ci_column: "A") queries = assert_sql { invalid.save } ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) } assert_match(/binary/i, ci_uniqueness_query) end def test_case_sensitive_comparison_for_cs_column - CollationTest.validates_uniqueness_of(:string_cs_column, :case_sensitive => true) - CollationTest.create!(:string_cs_column => 'A') - invalid = CollationTest.new(:string_cs_column => 'A') + CollationTest.validates_uniqueness_of(:string_cs_column, case_sensitive: true) + CollationTest.create!(string_cs_column: "A") + invalid = CollationTest.new(string_cs_column: "A") queries = assert_sql { invalid.save } cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) } assert_no_match(/binary/i, cs_uniqueness_query) @@ -54,8 +54,8 @@ class Mysql2CaseSensitivityTest < ActiveRecord::Mysql2TestCase def test_case_sensitive_comparison_for_binary_column CollationTest.validates_uniqueness_of(:binary_column, case_sensitive: true) - CollationTest.create!(binary_column: 'A') - invalid = CollationTest.new(binary_column: 'A') + CollationTest.create!(binary_column: "A") + invalid = CollationTest.new(binary_column: "A") queries = assert_sql { invalid.save } bin_uniqueness_query = queries.detect { |q| q.match(/binary_column/) } assert_no_match(/\bBINARY\b/, bin_uniqueness_query) diff --git a/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb b/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb index c8028b6b36..8826ad7fd1 100644 --- a/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb +++ b/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase include SchemaDumpingHelper @@ -8,8 +8,8 @@ class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase setup do @connection = ActiveRecord::Base.connection @connection.create_table :charset_collations, force: true do |t| - t.string :string_ascii_bin, charset: 'ascii', collation: 'ascii_bin' - t.text :text_ucs2_unicode_ci, charset: 'ucs2', collation: 'ucs2_unicode_ci' + t.string :string_ascii_bin, charset: "ascii", collation: "ascii_bin" + t.text :text_ucs2_unicode_ci, charset: "ucs2", collation: "ucs2_unicode_ci" end end @@ -18,32 +18,32 @@ class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase end test "string column with charset and collation" do - column = @connection.columns(:charset_collations).find { |c| c.name == 'string_ascii_bin' } + column = @connection.columns(:charset_collations).find { |c| c.name == "string_ascii_bin" } assert_equal :string, column.type - assert_equal 'ascii_bin', column.collation + assert_equal "ascii_bin", column.collation end test "text column with charset and collation" do - column = @connection.columns(:charset_collations).find { |c| c.name == 'text_ucs2_unicode_ci' } + column = @connection.columns(:charset_collations).find { |c| c.name == "text_ucs2_unicode_ci" } assert_equal :text, column.type - assert_equal 'ucs2_unicode_ci', column.collation + assert_equal "ucs2_unicode_ci", column.collation end test "add column with charset and collation" do - @connection.add_column :charset_collations, :title, :string, charset: 'utf8', collation: 'utf8_bin' + @connection.add_column :charset_collations, :title, :string, charset: "utf8", collation: "utf8_bin" - column = @connection.columns(:charset_collations).find { |c| c.name == 'title' } + column = @connection.columns(:charset_collations).find { |c| c.name == "title" } assert_equal :string, column.type - assert_equal 'utf8_bin', column.collation + assert_equal "utf8_bin", column.collation end test "change column with charset and collation" do - @connection.add_column :charset_collations, :description, :string, charset: 'utf8', collation: 'utf8_unicode_ci' - @connection.change_column :charset_collations, :description, :text, charset: 'utf8', collation: 'utf8_general_ci' + @connection.add_column :charset_collations, :description, :string, charset: "utf8", collation: "utf8_unicode_ci" + @connection.change_column :charset_collations, :description, :text, charset: "utf8", collation: "utf8_general_ci" - column = @connection.columns(:charset_collations).find { |c| c.name == 'description' } + column = @connection.columns(:charset_collations).find { |c| c.name == "description" } assert_equal :text, column.type - assert_equal 'utf8_general_ci', column.collation + assert_equal "utf8_general_ci", column.collation end test "schema dump includes collation" do diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index fe610ae951..c1de2218e2 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase include ConnectionHelper @@ -9,7 +9,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase def setup super @subscriber = SQLSubscriber.new - @subscription = ActiveSupport::Notifications.subscribe('sql.active_record', @subscriber) + @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber) @connection = ActiveRecord::Base.connection end @@ -20,9 +20,9 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase def test_bad_connection assert_raise ActiveRecord::NoDatabaseError do - configuration = ActiveRecord::Base.configurations['arunit'].merge(database: 'inexistent_activerecord_unittest') + configuration = ActiveRecord::Base.configurations["arunit"].merge(database: "inexistent_activerecord_unittest") connection = ActiveRecord::Base.mysql2_connection(configuration) - connection.drop_table 'ex', if_exists: true + connection.drop_table "ex", if_exists: true end end @@ -39,7 +39,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase def test_no_automatic_reconnection_after_timeout assert @connection.active? - @connection.update('set @@wait_timeout=1') + @connection.update("set @@wait_timeout=1") sleep 2 assert !@connection.active? @@ -49,7 +49,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase def test_successful_reconnection_after_timeout_with_manual_reconnect assert @connection.active? - @connection.update('set @@wait_timeout=1') + @connection.update("set @@wait_timeout=1") sleep 2 @connection.reconnect! assert @connection.active? @@ -57,15 +57,36 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase def test_successful_reconnection_after_timeout_with_verify assert @connection.active? - @connection.update('set @@wait_timeout=1') + @connection.update("set @@wait_timeout=1") sleep 2 @connection.verify! assert @connection.active? end + def test_execute_after_disconnect + @connection.disconnect! + + assert_raise(ActiveRecord::StatementInvalid) do + @connection.execute("SELECT 1") + end + end + + def test_quote_after_disconnect + @connection.disconnect! + + assert_raise(Mysql2::Error) do + @connection.quote("string") + end + end + + def test_active_after_disconnect + @connection.disconnect! + assert_equal false, @connection.active? + end + def test_mysql_connection_collation_is_configured - assert_equal 'utf8_unicode_ci', @connection.show_variable('collation_connection') - assert_equal 'utf8_general_ci', ARUnit2Model.connection.show_variable('collation_connection') + assert_equal "utf8_unicode_ci", @connection.show_variable("collation_connection") + assert_equal "utf8_general_ci", ARUnit2Model.connection.show_variable("collation_connection") end def test_mysql_default_in_strict_mode @@ -92,29 +113,29 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase def test_mysql_sql_mode_variable_overrides_strict_mode run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { 'sql_mode' => 'ansi' })) - result = ActiveRecord::Base.connection.select_value('SELECT @@SESSION.sql_mode') + ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { "sql_mode" => "ansi" })) + result = ActiveRecord::Base.connection.select_value("SELECT @@SESSION.sql_mode") assert_no_match %r(STRICT_ALL_TABLES), result end end def test_passing_arbitary_flags_to_adapter run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.merge({flags: Mysql2::Client::COMPRESS})) - assert_equal (Mysql2::Client::COMPRESS | Mysql2::Client::FOUND_ROWS), ActiveRecord::Base.connection.raw_connection.query_options[:flags] + ActiveRecord::Base.establish_connection(orig_connection.merge(flags: Mysql2::Client::COMPRESS)) + assert_equal (Mysql2::Client::COMPRESS | Mysql2::Client::FOUND_ROWS), ActiveRecord::Base.connection.raw_connection.query_options[:flags] end end def test_passing_flags_by_array_to_adapter run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.merge({flags: ['COMPRESS'] })) + ActiveRecord::Base.establish_connection(orig_connection.merge(flags: ["COMPRESS"])) assert_equal ["COMPRESS", "FOUND_ROWS"], ActiveRecord::Base.connection.raw_connection.query_options[:flags] end end def test_mysql_set_session_variable run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => 3}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { default_week_format: 3 })) session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" assert_equal 3, session_mode.rows.first.first.to_i end @@ -122,7 +143,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase def test_mysql_set_session_variable_to_default run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => :default}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { default_week_format: :default })) global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT" session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT" assert_equal global_mode.rows, session_mode.rows @@ -130,14 +151,14 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase end def test_logs_name_show_variable - @connection.show_variable 'foo' + @connection.show_variable "foo" assert_equal "SCHEMA", @subscriber.logged[0][1] end def test_logs_name_rename_column_sql @connection.execute "CREATE TABLE `bar_baz` (`foo` varchar(255))" @subscriber.logged.clear - @connection.send(:rename_column_sql, 'bar_baz', 'foo', 'foo2') + @connection.send(:rename_column_sql, "bar_baz", "foo", "foo2") assert_equal "SCHEMA", @subscriber.logged[0][1] ensure @connection.execute "DROP TABLE `bar_baz`" @@ -155,19 +176,19 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase released_lock = @connection.release_advisory_lock(lock_name) assert released_lock, "expected release_advisory_lock to return true but it didn't" - assert test_lock_free(lock_name), 'expected the test lock to be available after releasing' + assert test_lock_free(lock_name), "expected the test lock to be available after releasing" end def test_release_non_existent_advisory_lock lock_name = "fake lock'n'name" released_non_existent_lock = @connection.release_advisory_lock(lock_name) assert_equal released_non_existent_lock, false, - 'expected release_advisory_lock to return false when there was no lock to release' + "expected release_advisory_lock to return false when there was no lock to release" end - protected + private - def test_lock_free(lock_name) - @connection.select_value("SELECT IS_FREE_LOCK(#{@connection.quote(lock_name)})") == 1 - end + def test_lock_free(lock_name) + @connection.select_value("SELECT IS_FREE_LOCK(#{@connection.quote(lock_name)})") == 1 + end end diff --git a/activerecord/test/cases/adapters/mysql2/datetime_precision_quoting_test.rb b/activerecord/test/cases/adapters/mysql2/datetime_precision_quoting_test.rb index e349c67c93..135789a57d 100644 --- a/activerecord/test/cases/adapters/mysql2/datetime_precision_quoting_test.rb +++ b/activerecord/test/cases/adapters/mysql2/datetime_precision_quoting_test.rb @@ -5,23 +5,23 @@ class Mysql2DatetimePrecisionQuotingTest < ActiveRecord::Mysql2TestCase @connection = ActiveRecord::Base.connection end - test 'microsecond precision for MySQL gte 5.6.4' do - stub_version '5.6.4' + test "microsecond precision for MySQL gte 5.6.4" do + stub_version "5.6.4" assert_microsecond_precision end - test 'no microsecond precision for MySQL lt 5.6.4' do - stub_version '5.6.3' + test "no microsecond precision for MySQL lt 5.6.4" do + stub_version "5.6.3" assert_no_microsecond_precision end - test 'microsecond precision for MariaDB gte 5.3.0' do - stub_version '5.5.5-10.1.8-MariaDB-log' + test "microsecond precision for MariaDB gte 5.3.0" do + stub_version "5.5.5-10.1.8-MariaDB-log" assert_microsecond_precision end - test 'no microsecond precision for MariaDB lt 5.3.0' do - stub_version '5.2.9-MariaDB' + test "no microsecond precision for MariaDB lt 5.3.0" do + stub_version "5.2.9-MariaDB" assert_no_microsecond_precision end diff --git a/activerecord/test/cases/adapters/mysql2/enum_test.rb b/activerecord/test/cases/adapters/mysql2/enum_test.rb index 35dbc76d1b..7ad3e3ca2d 100644 --- a/activerecord/test/cases/adapters/mysql2/enum_test.rb +++ b/activerecord/test/cases/adapters/mysql2/enum_test.rb @@ -5,22 +5,17 @@ class Mysql2EnumTest < ActiveRecord::Mysql2TestCase end def test_enum_limit - column = EnumTest.columns_hash['enum_column'] + column = EnumTest.columns_hash["enum_column"] assert_equal 8, column.limit end - def test_should_not_be_blob_or_text_column - column = EnumTest.columns_hash['enum_column'] - assert_not column.blob_or_text_column? - end - def test_should_not_be_unsigned - column = EnumTest.columns_hash['enum_column'] + column = EnumTest.columns_hash["enum_column"] assert_not column.unsigned? end def test_should_not_be_bigint - column = EnumTest.columns_hash['enum_column'] + column = EnumTest.columns_hash["enum_column"] assert_not column.bigint? end end diff --git a/activerecord/test/cases/adapters/mysql2/explain_test.rb b/activerecord/test/cases/adapters/mysql2/explain_test.rb index b783b5fcd9..7916921e5a 100644 --- a/activerecord/test/cases/adapters/mysql2/explain_test.rb +++ b/activerecord/test/cases/adapters/mysql2/explain_test.rb @@ -1,6 +1,6 @@ require "cases/helper" -require 'models/developer' -require 'models/computer' +require "models/developer" +require "models/computer" class Mysql2ExplainTest < ActiveRecord::Mysql2TestCase fixtures :developers diff --git a/activerecord/test/cases/adapters/mysql2/json_test.rb b/activerecord/test/cases/adapters/mysql2/json_test.rb index 9c3fef1b59..6954006003 100644 --- a/activerecord/test/cases/adapters/mysql2/json_test.rb +++ b/activerecord/test/cases/adapters/mysql2/json_test.rb @@ -1,179 +1,195 @@ -require 'cases/helper' -require 'support/schema_dumping_helper' +require "cases/helper" +require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_json? -class Mysql2JSONTest < ActiveRecord::Mysql2TestCase - include SchemaDumpingHelper - self.use_transactional_tests = false + class Mysql2JSONTest < ActiveRecord::Mysql2TestCase + include SchemaDumpingHelper + self.use_transactional_tests = false - class JsonDataType < ActiveRecord::Base - self.table_name = 'json_data_type' + class JsonDataType < ActiveRecord::Base + self.table_name = "json_data_type" - store_accessor :settings, :resolution - end + store_accessor :settings, :resolution + end - def setup - @connection = ActiveRecord::Base.connection - begin - @connection.create_table('json_data_type') do |t| - t.json 'payload' - t.json 'settings' + def setup + @connection = ActiveRecord::Base.connection + begin + @connection.create_table("json_data_type") do |t| + t.json "payload" + t.json "settings" + end end end - end - def teardown - @connection.drop_table :json_data_type, if_exists: true - JsonDataType.reset_column_information - end + def teardown + @connection.drop_table :json_data_type, if_exists: true + JsonDataType.reset_column_information + end - def test_column - column = JsonDataType.columns_hash["payload"] - assert_equal :json, column.type - assert_equal 'json', column.sql_type + def test_column + column = JsonDataType.columns_hash["payload"] + assert_equal :json, column.type + assert_equal "json", column.sql_type - type = JsonDataType.type_for_attribute("payload") - assert_not type.binary? - end + type = JsonDataType.type_for_attribute("payload") + assert_not type.binary? + end - def test_change_table_supports_json - @connection.change_table('json_data_type') do |t| - t.json 'users' + def test_change_table_supports_json + @connection.change_table("json_data_type") do |t| + t.json "users" + end + JsonDataType.reset_column_information + column = JsonDataType.columns_hash["users"] + assert_equal :json, column.type end - JsonDataType.reset_column_information - column = JsonDataType.columns_hash['users'] - assert_equal :json, column.type - end - def test_schema_dumping - output = dump_table_schema("json_data_type") - assert_match(/t\.json\s+"settings"/, output) - end + def test_schema_dumping + output = dump_table_schema("json_data_type") + assert_match(/t\.json\s+"settings"/, output) + end - def test_cast_value_on_write - x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar} - assert_equal({"string" => "foo", :symbol => :bar}, x.payload_before_type_cast) - assert_equal({"string" => "foo", "symbol" => "bar"}, x.payload) - x.save - assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload) - end + def test_cast_value_on_write + x = JsonDataType.new payload: { "string" => "foo", :symbol => :bar } + assert_equal({ "string" => "foo", :symbol => :bar }, x.payload_before_type_cast) + assert_equal({ "string" => "foo", "symbol" => "bar" }, x.payload) + x.save + assert_equal({ "string" => "foo", "symbol" => "bar" }, x.reload.payload) + end - def test_type_cast_json - type = JsonDataType.type_for_attribute("payload") + def test_type_cast_json + type = JsonDataType.type_for_attribute("payload") - data = "{\"a_key\":\"a_value\"}" - hash = type.deserialize(data) - assert_equal({'a_key' => 'a_value'}, hash) - assert_equal({'a_key' => 'a_value'}, type.deserialize(data)) + data = "{\"a_key\":\"a_value\"}" + hash = type.deserialize(data) + assert_equal({ "a_key" => "a_value" }, hash) + assert_equal({ "a_key" => "a_value" }, type.deserialize(data)) - assert_equal({}, type.deserialize("{}")) - assert_equal({'key'=>nil}, type.deserialize('{"key": null}')) - assert_equal({'c'=>'}','"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"}))) - end + assert_equal({}, type.deserialize("{}")) + assert_equal({ "key" => nil }, type.deserialize('{"key": null}')) + assert_equal({ "c" => "}", '"a"' => 'b "a b' }, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"}))) + end - def test_rewrite - @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" - x = JsonDataType.first - x.payload = { '"a\'' => 'b' } - assert x.save! - end + def test_rewrite + @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" + x = JsonDataType.first + x.payload = { '"a\'' => "b" } + assert x.save! + end - def test_select - @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" - x = JsonDataType.first - assert_equal({'k' => 'v'}, x.payload) - end + def test_select + @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" + x = JsonDataType.first + assert_equal({ "k" => "v" }, x.payload) + end - def test_select_multikey - @connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')| - x = JsonDataType.first - assert_equal({'k1' => 'v1', 'k2' => 'v2', 'k3' => [1,2,3]}, x.payload) - end + def test_select_multikey + @connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')| + x = JsonDataType.first + assert_equal({ "k1" => "v1", "k2" => "v2", "k3" => [1, 2, 3] }, x.payload) + end - def test_null_json - @connection.execute %q|insert into json_data_type (payload) VALUES(null)| - x = JsonDataType.first - assert_equal(nil, x.payload) - end + def test_null_json + @connection.execute "insert into json_data_type (payload) VALUES(null)" + x = JsonDataType.first + assert_nil(x.payload) + end - def test_select_array_json_value - @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| - x = JsonDataType.first - assert_equal(['v0', {'k1' => 'v1'}], x.payload) - end + def test_select_array_json_value + @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| + x = JsonDataType.first + assert_equal(["v0", { "k1" => "v1" }], x.payload) + end - def test_rewrite_array_json_value - @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| - x = JsonDataType.first - x.payload = ['v1', {'k2' => 'v2'}, 'v3'] - assert x.save! - end + def test_select_nil_json_after_create + json = JsonDataType.create(payload: nil) + x = JsonDataType.where(payload: nil).first + assert_equal(json, x) + end - def test_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + def test_select_nil_json_after_update + json = JsonDataType.create(payload: "foo") + x = JsonDataType.where(payload: nil).first + assert_nil(x) - x.save! - x = JsonDataType.first - assert_equal "320×480", x.resolution + json.update_attributes payload: nil + x = JsonDataType.where(payload: nil).first + assert_equal(json.reload, x) + end - x.resolution = "640×1136" - x.save! + def test_rewrite_array_json_value + @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| + x = JsonDataType.first + x.payload = ["v1", { "k2" => "v2" }, "v3"] + assert x.save! + end - x = JsonDataType.first - assert_equal "640×1136", x.resolution - end + def test_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - def test_duplication_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + x.save! + x = JsonDataType.first + assert_equal "320×480", x.resolution - y = x.dup - assert_equal "320×480", y.resolution - end + x.resolution = "640×1136" + x.save! - def test_yaml_round_trip_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + x = JsonDataType.first + assert_equal "640×1136", x.resolution + end - y = YAML.load(YAML.dump(x)) - assert_equal "320×480", y.resolution - end + def test_duplication_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - def test_changes_in_place - json = JsonDataType.new - assert_not json.changed? + y = x.dup + assert_equal "320×480", y.resolution + end - json.payload = { 'one' => 'two' } - assert json.changed? - assert json.payload_changed? + def test_yaml_round_trip_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - json.save! - assert_not json.changed? + y = YAML.load(YAML.dump(x)) + assert_equal "320×480", y.resolution + end - json.payload['three'] = 'four' - assert json.payload_changed? + def test_changes_in_place + json = JsonDataType.new + assert_not json.changed? - json.save! - json.reload + json.payload = { "one" => "two" } + assert json.changed? + assert json.payload_changed? - assert_equal({ 'one' => 'two', 'three' => 'four' }, json.payload) - assert_not json.changed? - end + json.save! + assert_not json.changed? - def test_assigning_string_literal - json = JsonDataType.create(payload: "foo") - assert_equal "foo", json.payload - end + json.payload["three"] = "four" + assert json.payload_changed? - def test_assigning_number - json = JsonDataType.create(payload: 1.234) - assert_equal 1.234, json.payload - end + json.save! + json.reload - def test_assigning_boolean - json = JsonDataType.create(payload: true) - assert_equal true, json.payload + assert_equal({ "one" => "two", "three" => "four" }, json.payload) + assert_not json.changed? + end + + def test_assigning_string_literal + json = JsonDataType.create(payload: "foo") + assert_equal "foo", json.payload + end + + def test_assigning_number + json = JsonDataType.create(payload: 1.234) + assert_equal 1.234, json.payload + end + + def test_assigning_boolean + json = JsonDataType.create(payload: true) + assert_equal true, json.payload + end end end -end diff --git a/activerecord/test/cases/adapters/mysql2/legacy_migration_test.rb b/activerecord/test/cases/adapters/mysql2/legacy_migration_test.rb new file mode 100644 index 0000000000..5d3125c2be --- /dev/null +++ b/activerecord/test/cases/adapters/mysql2/legacy_migration_test.rb @@ -0,0 +1,60 @@ +require "cases/helper" + +class MysqlLegacyMigrationTest < ActiveRecord::Mysql2TestCase + self.use_transactional_tests = false + + class GenerateTableWithoutBigint < ActiveRecord::Migration[5.0] + def change + create_table :legacy_integer_pk do |table| + table.string :foo + end + + create_table :override_pk, id: :bigint do |table| + table.string :bar + end + end + end + + def setup + super + @connection = ActiveRecord::Base.connection + + @migration_verbose_old = ActiveRecord::Migration.verbose + ActiveRecord::Migration.verbose = false + + migrations = [GenerateTableWithoutBigint.new(nil, 1)] + + ActiveRecord::Migrator.new(:up, migrations).migrate + end + + def teardown + ActiveRecord::Migration.verbose = @migration_verbose_old + @connection.drop_table("legacy_integer_pk") + @connection.drop_table("override_pk") + ActiveRecord::SchemaMigration.delete_all rescue nil + super + end + + def test_create_table_uses_integer_as_pkey_by_default + col = column(:legacy_integer_pk, :id) + assert_equal "int(11)", sql_type_for(col) + assert col.auto_increment? + end + + def test_create_tables_respects_pk_column_type_override + col = column(:override_pk, :id) + assert_equal "bigint(20)", sql_type_for(col) + end + + private + + def column(table_name, column_name) + ActiveRecord::Base.connection + .columns(table_name.to_s) + .detect { |c| c.name == column_name.to_s } + end + + def sql_type_for(col) + col && col.sql_type + end +end diff --git a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb index 61dd0828d0..aab3dcb724 100644 --- a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb +++ b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb @@ -11,15 +11,15 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase def test_exec_query_nothing_raises_with_no_result_queries assert_nothing_raised do with_example_table do - @conn.exec_query('INSERT INTO ex (number) VALUES (1)') - @conn.exec_query('DELETE FROM ex WHERE number = 1') + @conn.exec_query("INSERT INTO ex (number) VALUES (1)") + @conn.exec_query("DELETE FROM ex WHERE number = 1") end end end def test_valid_column with_example_table do - column = @conn.columns('ex').find { |col| col.name == 'id' } + column = @conn.columns("ex").find { |col| col.name == "id" } assert @conn.valid_type?(column.type) end end @@ -45,8 +45,8 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase def test_columns_for_distinct_with_case assert_equal( - 'posts.id, CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END AS alias_0', - @conn.columns_for_distinct('posts.id', + "posts.id, CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END AS alias_0", + @conn.columns_for_distinct("posts.id", ["CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END"]) ) end @@ -65,9 +65,22 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase @conn.columns_for_distinct("posts.id", [order]) end - private + def test_errors_for_bigint_fks_on_integer_pk_table + # table old_cars has primary key of integer + + error = assert_raises(ActiveRecord::MismatchedForeignKey) do + @conn.add_reference :engines, :old_car + @conn.add_foreign_key :engines, :old_cars + end - def with_example_table(definition = 'id int auto_increment primary key, number int, data varchar(255)', &block) - super(@conn, 'ex', definition, &block) + assert_match "Column `old_car_id` on table `engines` has a type of `bigint(20)`", error.message + assert_not_nil error.cause + @conn.exec_query("ALTER TABLE engines DROP COLUMN old_car_id") end + + private + + def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block) + super(@conn, "ex", definition, &block) + end end diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb index ffb4e2c5cf..2c778b1150 100644 --- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb @@ -4,24 +4,24 @@ require "cases/helper" # reserved word names (ie: group, order, values, etc...) class Mysql2ReservedWordTest < ActiveRecord::Mysql2TestCase class Group < ActiveRecord::Base - Group.table_name = 'group' + Group.table_name = "group" belongs_to :select has_one :values end class Select < ActiveRecord::Base - Select.table_name = 'select' + Select.table_name = "select" has_many :groups end class Values < ActiveRecord::Base - Values.table_name = 'values' + Values.table_name = "values" end class Distinct < ActiveRecord::Base - Distinct.table_name = 'distinct' + Distinct.table_name = "distinct" has_and_belongs_to_many :selects - has_many :values, :through => :groups + has_many :values, through: :groups end def setup @@ -30,15 +30,15 @@ class Mysql2ReservedWordTest < ActiveRecord::Mysql2TestCase # we call execute directly here (and do similar below) because ActiveRecord::Base#create_table() # will fail with these table names if these test cases fail - create_tables_directly 'group'=>'id int auto_increment primary key, `order` varchar(255), select_id int', - 'select'=>'id int auto_increment primary key', - 'values'=>'id int auto_increment primary key, group_id int', - 'distinct'=>'id int auto_increment primary key', - 'distinct_select'=>'distinct_id int, select_id int' + create_tables_directly "group" => "id int auto_increment primary key, `order` varchar(255), select_id int", + "select" => "id int auto_increment primary key", + "values" => "id int auto_increment primary key, group_id int", + "distinct" => "id int auto_increment primary key", + "distinct_select" => "distinct_id int, select_id int" end teardown do - drop_tables_directly ['group', 'select', 'values', 'distinct', 'distinct_select', 'order'] + drop_tables_directly ["group", "select", "values", "distinct", "distinct_select", "order"] end # create tables with reserved-word names and columns @@ -57,9 +57,9 @@ class Mysql2ReservedWordTest < ActiveRecord::Mysql2TestCase # alter column with a reserved-word name in a table with a reserved-word name def test_change_columns - assert_nothing_raised { @connection.change_column_default(:group, :order, 'whatever') } + assert_nothing_raised { @connection.change_column_default(:group, :order, "whatever") } #the quoting here will reveal any double quoting issues in change_column's interaction with the column method in the adapter - assert_nothing_raised { @connection.change_column('group', 'order', :Int, :default => 0) } + assert_nothing_raised { @connection.change_column("group", "order", :Int, default: 0) } assert_nothing_raised { @connection.rename_column(:group, :order, :values) } end @@ -78,11 +78,11 @@ class Mysql2ReservedWordTest < ActiveRecord::Mysql2TestCase create_test_fixtures :select, :distinct, :group, :values, :distinct_select x = nil assert_nothing_raised { x = Group.new } - x.order = 'x' + x.order = "x" assert_nothing_raised { x.save } - x.order = 'y' + x.order = "y" assert_nothing_raised { x.save } - assert_nothing_raised { Group.find_by_order('y') } + assert_nothing_raised { Group.find_by_order("y") } assert_nothing_raised { Group.find(1) } end @@ -124,29 +124,28 @@ class Mysql2ReservedWordTest < ActiveRecord::Mysql2TestCase end def test_associations_work_with_reserved_words - assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a } + assert_nothing_raised { Select.all.merge!(includes: [:groups]).to_a } end #the following functions were added to DRY test cases private - # custom fixture loader, uses FixtureSet#create_fixtures and appends base_path to the current file's path - def create_test_fixtures(*fixture_names) - ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names) - end - - # custom drop table, uses execute on connection to drop a table if it exists. note: escapes table_name - def drop_tables_directly(table_names, connection = @connection) - table_names.each do |name| - connection.drop_table name, if_exists: true + # custom fixture loader, uses FixtureSet#create_fixtures and appends base_path to the current file's path + def create_test_fixtures(*fixture_names) + ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names) end - end - # custom create table, uses execute on connection to create a table, note: escapes table_name, does NOT escape columns - def create_tables_directly (tables, connection = @connection) - tables.each do |table_name, column_properties| - connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )") + # custom drop table, uses execute on connection to drop a table if it exists. note: escapes table_name + def drop_tables_directly(table_names, connection = @connection) + table_names.each do |name| + connection.drop_table name, if_exists: true + end end - end + # custom create table, uses execute on connection to create a table, note: escapes table_name, does NOT escape columns + def create_tables_directly(tables, connection = @connection) + tables.each do |table_name, column_properties| + connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )") + end + end end diff --git a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb index 7c89fda582..fa54aac6b3 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb @@ -18,7 +18,7 @@ class SchemaMigrationsTest < ActiveRecord::Mysql2TestCase connection.initialize_schema_migrations_table - assert connection.column_exists?(table_name, :version, :string, collation: 'utf8_general_ci') + assert connection.column_exists?(table_name, :version, :string, collation: "utf8_general_ci") end end @@ -29,31 +29,31 @@ class SchemaMigrationsTest < ActiveRecord::Mysql2TestCase connection.initialize_internal_metadata_table - assert connection.column_exists?(table_name, :key, :string, collation: 'utf8_general_ci') + assert connection.column_exists?(table_name, :key, :string, collation: "utf8_general_ci") end end private - def with_encoding_utf8mb4 - database_name = connection.current_database - database_info = connection.select_one("SELECT * FROM information_schema.schemata WHERE schema_name = '#{database_name}'") + def with_encoding_utf8mb4 + database_name = connection.current_database + database_info = connection.select_one("SELECT * FROM information_schema.schemata WHERE schema_name = '#{database_name}'") - original_charset = database_info["DEFAULT_CHARACTER_SET_NAME"] - original_collation = database_info["DEFAULT_COLLATION_NAME"] + original_charset = database_info["DEFAULT_CHARACTER_SET_NAME"] + original_collation = database_info["DEFAULT_COLLATION_NAME"] - execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET utf8mb4") + execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET utf8mb4") - yield - ensure - execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET #{original_charset} COLLATE #{original_collation}") - end + yield + ensure + execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET #{original_charset} COLLATE #{original_collation}") + end - def connection - @connection ||= ActiveRecord::Base.connection - end + def connection + @connection ||= ActiveRecord::Base.connection + end - def execute(sql) - connection.execute(sql) - end + def execute(sql) + connection.execute(sql) + end end diff --git a/activerecord/test/cases/adapters/mysql2/schema_test.rb b/activerecord/test/cases/adapters/mysql2/schema_test.rb index 43957791b1..1fad5585de 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb @@ -1,6 +1,6 @@ require "cases/helper" -require 'models/post' -require 'models/comment' +require "models/post" +require "models/comment" module ActiveRecord module ConnectionAdapters @@ -16,7 +16,7 @@ module ActiveRecord @omgpost = Class.new(ActiveRecord::Base) do self.inheritance_column = :disabled self.table_name = "#{db}.#{table}" - def self.name; 'Post'; end + def self.name; "Post"; end end end @@ -31,13 +31,13 @@ module ActiveRecord t.float :float_25, limit: 25 end - column_no_limit = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_no_limit' } - column_short = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_short' } - column_long = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_long' } + column_no_limit = @connection.columns(:mysql_doubles).find { |c| c.name == "float_no_limit" } + column_short = @connection.columns(:mysql_doubles).find { |c| c.name == "float_short" } + column_long = @connection.columns(:mysql_doubles).find { |c| c.name == "float_long" } - column_23 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_23' } - column_24 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_24' } - column_25 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_25' } + column_23 = @connection.columns(:mysql_doubles).find { |c| c.name == "float_23" } + column_24 = @connection.columns(:mysql_doubles).find { |c| c.name == "float_24" } + column_25 = @connection.columns(:mysql_doubles).find { |c| c.name == "float_25" } # Mysql floats are precision 0..24, Mysql doubles are precision 25..53 assert_equal 24, column_no_limit.limit @@ -56,7 +56,7 @@ module ActiveRecord end def test_primary_key - assert_equal 'id', @omgpost.primary_key + assert_equal "id", @omgpost.primary_key end def test_data_source_exists? @@ -69,18 +69,18 @@ module ActiveRecord end def test_dump_indexes - index_a_name = 'index_key_tests_on_snack' - index_b_name = 'index_key_tests_on_pizza' - index_c_name = 'index_key_tests_on_awesome' + index_a_name = "index_key_tests_on_snack" + index_b_name = "index_key_tests_on_pizza" + index_c_name = "index_key_tests_on_awesome" - table = 'key_tests' + table = "key_tests" indexes = @connection.indexes(table).sort_by(&:name) - assert_equal 3,indexes.size + assert_equal 3, indexes.size - index_a = indexes.select{|i| i.name == index_a_name}[0] - index_b = indexes.select{|i| i.name == index_b_name}[0] - index_c = indexes.select{|i| i.name == index_c_name}[0] + index_a = indexes.select { |i| i.name == index_a_name }[0] + index_b = indexes.select { |i| i.name == index_b_name }[0] + index_c = indexes.select { |i| i.name == index_c_name }[0] assert_equal :btree, index_a.using assert_nil index_a.type assert_equal :btree, index_b.using @@ -103,3 +103,24 @@ module ActiveRecord end end end + +class Mysql2AnsiQuotesTest < ActiveRecord::Mysql2TestCase + def setup + @connection = ActiveRecord::Base.connection + @connection.execute("SET SESSION sql_mode='ANSI_QUOTES'") + end + + def teardown + @connection.reconnect! + end + + def test_primary_key_method_with_ansi_quotes + assert_equal "id", @connection.primary_key("topics") + end + + def test_foreign_keys_method_with_ansi_quotes + fks = @connection.foreign_keys("lessons_students") + assert_equal([["lessons_students", "students", :cascade]], + fks.map { |fk| [fk.from_table, fk.to_table, fk.on_delete] }) + end +end diff --git a/activerecord/test/cases/adapters/mysql2/sp_test.rb b/activerecord/test/cases/adapters/mysql2/sp_test.rb index 4197ba45f1..4182532535 100644 --- a/activerecord/test/cases/adapters/mysql2/sp_test.rb +++ b/activerecord/test/cases/adapters/mysql2/sp_test.rb @@ -1,13 +1,13 @@ require "cases/helper" -require 'models/topic' -require 'models/reply' +require "models/topic" +require "models/reply" class Mysql2StoredProcedureTest < ActiveRecord::Mysql2TestCase fixtures :topics def setup @connection = ActiveRecord::Base.connection - unless ActiveRecord::Base.connection.version >= '5.6.0' + unless ActiveRecord::Base.connection.version >= "5.6.0" skip("no stored procedure support") end end @@ -17,19 +17,19 @@ class Mysql2StoredProcedureTest < ActiveRecord::Mysql2TestCase # In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default. # http://dev.mysql.com/doc/refman/5.6/en/call.html def test_multi_results - rows = @connection.select_rows('CALL ten();') + rows = @connection.select_rows("CALL ten();") assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_rows'" end def test_multi_results_from_select_one - row = @connection.select_one('CALL topics(1);') - assert_equal 'David', row['author_name'] + row = @connection.select_one("CALL topics(1);") + assert_equal "David", row["author_name"] assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_one'" end def test_multi_results_from_find_by_sql - topics = Topic.find_by_sql 'CALL topics(3);' + topics = Topic.find_by_sql "CALL topics(3);" assert_equal 3, topics.size assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select'" end diff --git a/activerecord/test/cases/adapters/mysql2/sql_types_test.rb b/activerecord/test/cases/adapters/mysql2/sql_types_test.rb index 4926bc2267..bee42d48f1 100644 --- a/activerecord/test/cases/adapters/mysql2/sql_types_test.rb +++ b/activerecord/test/cases/adapters/mysql2/sql_types_test.rb @@ -2,10 +2,10 @@ require "cases/helper" class Mysql2SqlTypesTest < ActiveRecord::Mysql2TestCase def test_binary_types - assert_equal 'varbinary(64)', type_to_sql(:binary, 64) - assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095) - assert_equal 'blob', type_to_sql(:binary, 4096) - assert_equal 'blob', type_to_sql(:binary) + assert_equal "varbinary(64)", type_to_sql(:binary, 64) + assert_equal "varbinary(4095)", type_to_sql(:binary, 4095) + assert_equal "blob", type_to_sql(:binary, 4096) + assert_equal "blob", type_to_sql(:binary) end def type_to_sql(*args) diff --git a/activerecord/test/cases/adapters/mysql2/table_options_test.rb b/activerecord/test/cases/adapters/mysql2/table_options_test.rb index af121ee7d9..61a8ce9bc0 100644 --- a/activerecord/test/cases/adapters/mysql2/table_options_test.rb +++ b/activerecord/test/cases/adapters/mysql2/table_options_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class Mysql2TableOptionsTest < ActiveRecord::Mysql2TestCase include SchemaDumpingHelper diff --git a/activerecord/test/cases/adapters/mysql2/transaction_test.rb b/activerecord/test/cases/adapters/mysql2/transaction_test.rb index 0e37c70e5c..16101e38cb 100644 --- a/activerecord/test/cases/adapters/mysql2/transaction_test.rb +++ b/activerecord/test/cases/adapters/mysql2/transaction_test.rb @@ -1,22 +1,24 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" module ActiveRecord class Mysql2TransactionTest < ActiveRecord::Mysql2TestCase self.use_transactional_tests = false class Sample < ActiveRecord::Base - self.table_name = 'samples' + self.table_name = "samples" end setup do + @abort, Thread.abort_on_exception = Thread.abort_on_exception, false + @connection = ActiveRecord::Base.connection @connection.clear_cache! @connection.transaction do - @connection.drop_table 'samples', if_exists: true - @connection.create_table('samples') do |t| - t.integer 'value' + @connection.drop_table "samples", if_exists: true + @connection.create_table("samples") do |t| + t.integer "value" end end @@ -24,38 +26,35 @@ module ActiveRecord end teardown do - @connection.drop_table 'samples', if_exists: true + @connection.drop_table "samples", if_exists: true + + Thread.abort_on_exception = @abort end - test "raises error when a serialization failure occurs" do - assert_raises(ActiveRecord::TransactionSerializationError) do - thread = Thread.new do - Sample.transaction isolation: :serializable do - Sample.delete_all + test "raises Deadlocked when a deadlock is encountered" do + assert_raises(ActiveRecord::Deadlocked) do + barrier = Concurrent::CyclicBarrier.new(2) - 10.times do |i| - sleep 0.1 + s1 = Sample.create value: 1 + s2 = Sample.create value: 2 - Sample.create value: i - end + thread = Thread.new do + Sample.transaction do + s1.lock! + barrier.wait + s2.update_attributes value: 1 end end - sleep 0.1 - - Sample.transaction isolation: :serializable do - Sample.delete_all - - 10.times do |i| - sleep 0.1 - - Sample.create value: i + begin + Sample.transaction do + s2.lock! + barrier.wait + s1.update_attributes value: 2 end - - sleep 1 + ensure + thread.join end - - thread.join end end end diff --git a/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb b/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb index 3df11ce11b..a0823be143 100644 --- a/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb +++ b/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb @@ -15,6 +15,7 @@ class Mysql2UnsignedTypeTest < ActiveRecord::Mysql2TestCase t.bigint :unsigned_bigint, unsigned: true t.float :unsigned_float, unsigned: true t.decimal :unsigned_decimal, unsigned: true, precision: 10, scale: 2 + t.column :unsigned_zerofill, "int unsigned zerofill" end end @@ -34,10 +35,10 @@ class Mysql2UnsignedTypeTest < ActiveRecord::Mysql2TestCase assert_raise(ActiveModel::RangeError) do UnsignedType.create(unsigned_bigint: -10) end - assert_raise(ActiveRecord::StatementInvalid) do + assert_raise(ActiveRecord::RangeError) do UnsignedType.create(unsigned_float: -10.0) end - assert_raise(ActiveRecord::StatementInvalid) do + assert_raise(ActiveRecord::RangeError) do UnsignedType.create(unsigned_decimal: -10.0) end end @@ -50,7 +51,7 @@ class Mysql2UnsignedTypeTest < ActiveRecord::Mysql2TestCase t.unsigned_decimal :unsigned_decimal_t, precision: 10, scale: 2 end - @connection.columns("unsigned_types").select { |c| /^unsigned_/ === c.name }.each do |column| + @connection.columns("unsigned_types").select { |c| /^unsigned_/.match?(c.name) }.each do |column| assert column.unsigned? end end diff --git a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb index 439e2ce6f7..b787de8453 100644 --- a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require "cases/helper" class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase def setup @@ -15,12 +15,12 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase def test_create_database_with_encoding assert_equal %(CREATE DATABASE "matt" ENCODING = 'utf8'), create_database(:matt) - assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1) - assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, 'encoding' => :latin1) + assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, encoding: :latin1) + assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, "encoding" => :latin1) end def test_create_database_with_collation_and_ctype - assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF8' LC_CTYPE = 'ja_JP.UTF8'), create_database(:aimonetti, :encoding => :"UTF8", :collation => :"ja_JP.UTF8", :ctype => :"ja_JP.UTF8") + assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF8' LC_CTYPE = 'ja_JP.UTF8'), create_database(:aimonetti, encoding: :"UTF8", collation: :"ja_JP.UTF8", ctype: :"ja_JP.UTF8") end def test_add_index @@ -31,14 +31,18 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase assert_equal expected, add_index(:people, :last_name, unique: true, where: "state = 'active'") expected = %(CREATE UNIQUE INDEX "index_people_on_lower_last_name" ON "people" (lower(last_name))) - assert_equal expected, add_index(:people, 'lower(last_name)', unique: true) + assert_equal expected, add_index(:people, "lower(last_name)", unique: true) expected = %(CREATE UNIQUE INDEX "index_people_on_last_name_varchar_pattern_ops" ON "people" (last_name varchar_pattern_ops)) - assert_equal expected, add_index(:people, 'last_name varchar_pattern_ops', unique: true) + assert_equal expected, add_index(:people, "last_name varchar_pattern_ops", unique: true) expected = %(CREATE INDEX CONCURRENTLY "index_people_on_last_name" ON "people" ("last_name")) assert_equal expected, add_index(:people, :last_name, algorithm: :concurrently) + expected = %(CREATE INDEX "index_people_on_last_name_and_first_name" ON "people" ("last_name" DESC, "first_name" ASC)) + assert_equal expected, add_index(:people, [:last_name, :first_name], order: { last_name: :desc, first_name: :asc }) + assert_equal expected, add_index(:people, ["last_name", :first_name], order: { last_name: :desc, "first_name" => :asc }) + %w(gin gist hash btree).each do |type| expected = %(CREATE INDEX "index_people_on_last_name" ON "people" USING #{type} ("last_name")) assert_equal expected, add_index(:people, :last_name, using: type) @@ -50,7 +54,7 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase assert_equal expected, add_index(:people, :last_name, using: type, unique: true, where: "state = 'active'") expected = %(CREATE UNIQUE INDEX "index_people_on_lower_last_name" ON "people" USING #{type} (lower(last_name))) - assert_equal expected, add_index(:people, 'lower(last_name)', using: type, unique: true) + assert_equal expected, add_index(:people, "lower(last_name)", using: type, unique: true) end assert_raise ArgumentError do @@ -63,7 +67,7 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase def test_remove_index # remove_index calls index_name_for_remove which can't work since execute is stubbed ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:define_method, :index_name_for_remove) do |*| - 'index_people_on_last_name' + "index_people_on_last_name" end expected = %(DROP INDEX CONCURRENTLY "index_people_on_last_name") @@ -81,6 +85,12 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase assert_equal expected, remove_index(:people, name: "index_people_on_last_name", algorithm: :concurrently) end + def test_remove_index_with_wrong_option + assert_raises ArgumentError do + remove_index(:people, coulmn: :last_name) + end + end + private def method_missing(method_symbol, *arguments) ActiveRecord::Base.connection.send(method_symbol, *arguments) diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index 380a90d765..c78c6178ff 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -1,63 +1,65 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper include InTimeZone class PgArray < ActiveRecord::Base - self.table_name = 'pg_arrays' + self.table_name = "pg_arrays" end def setup @connection = ActiveRecord::Base.connection - enable_extension!('hstore', @connection) + enable_extension!("hstore", @connection) @connection.transaction do - @connection.create_table('pg_arrays') do |t| - t.string 'tags', array: true - t.integer 'ratings', array: true + @connection.create_table("pg_arrays") do |t| + t.string "tags", array: true, limit: 255 + t.integer "ratings", array: true t.datetime :datetimes, array: true t.hstore :hstores, array: true + t.decimal :decimals, array: true, default: [], precision: 10, scale: 2 + t.timestamp :timestamps, array: true, default: [], precision: 6 end end PgArray.reset_column_information - @column = PgArray.columns_hash['tags'] + @column = PgArray.columns_hash["tags"] @type = PgArray.type_for_attribute("tags") end teardown do - @connection.drop_table 'pg_arrays', if_exists: true - disable_extension!('hstore', @connection) + @connection.drop_table "pg_arrays", if_exists: true + disable_extension!("hstore", @connection) end def test_column assert_equal :string, @column.type - assert_equal "character varying", @column.sql_type + assert_equal "character varying(255)", @column.sql_type assert @column.array? assert_not @type.binary? - ratings_column = PgArray.columns_hash['ratings'] + ratings_column = PgArray.columns_hash["ratings"] assert_equal :integer, ratings_column.type assert ratings_column.array? end def test_default - @connection.add_column 'pg_arrays', 'score', :integer, array: true, default: [4, 4, 2] + @connection.add_column "pg_arrays", "score", :integer, array: true, default: [4, 4, 2] PgArray.reset_column_information - assert_equal([4, 4, 2], PgArray.column_defaults['score']) + assert_equal([4, 4, 2], PgArray.column_defaults["score"]) assert_equal([4, 4, 2], PgArray.new.score) ensure PgArray.reset_column_information end def test_default_strings - @connection.add_column 'pg_arrays', 'names', :string, array: true, default: ["foo", "bar"] + @connection.add_column "pg_arrays", "names", :string, array: true, default: ["foo", "bar"] PgArray.reset_column_information - assert_equal(["foo", "bar"], PgArray.column_defaults['names']) + assert_equal(["foo", "bar"], PgArray.column_defaults["names"]) assert_equal(["foo", "bar"], PgArray.new.names) ensure PgArray.reset_column_information @@ -68,10 +70,10 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase @connection.change_column :pg_arrays, :snippets, :text, array: true, default: [] PgArray.reset_column_information - column = PgArray.columns_hash['snippets'] + column = PgArray.columns_hash["snippets"] assert_equal :text, column.type - assert_equal [], PgArray.column_defaults['snippets'] + assert_equal [], PgArray.column_defaults["snippets"] assert column.array? end @@ -88,17 +90,17 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase @connection.change_column_default :pg_arrays, :tags, [] PgArray.reset_column_information - assert_equal [], PgArray.column_defaults['tags'] + assert_equal [], PgArray.column_defaults["tags"] end def test_type_cast_array - assert_equal(['1', '2', '3'], @type.deserialize('{1,2,3}')) - assert_equal([], @type.deserialize('{}')) - assert_equal([nil], @type.deserialize('{NULL}')) + assert_equal(["1", "2", "3"], @type.deserialize("{1,2,3}")) + assert_equal([], @type.deserialize("{}")) + assert_equal([nil], @type.deserialize("{NULL}")) end def test_type_cast_integers - x = PgArray.new(ratings: ['1', '2']) + x = PgArray.new(ratings: ["1", "2"]) assert_equal([1, 2], x.ratings) @@ -110,22 +112,23 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase def test_schema_dump_with_shorthand output = dump_table_schema "pg_arrays" - assert_match %r[t\.string\s+"tags",\s+array: true], output + assert_match %r[t\.string\s+"tags",\s+limit: 255,\s+array: true], output assert_match %r[t\.integer\s+"ratings",\s+array: true], output + assert_match %r[t\.decimal\s+"decimals",\s+precision: 10,\s+scale: 2,\s+default: \[\],\s+array: true], output end def test_select_with_strings @connection.execute "insert into pg_arrays (tags) VALUES ('{1,2,3}')" x = PgArray.first - assert_equal(['1','2','3'], x.tags) + assert_equal(["1", "2", "3"], x.tags) end def test_rewrite_with_strings @connection.execute "insert into pg_arrays (tags) VALUES ('{1,2,3}')" x = PgArray.first - x.tags = ['1','2','3','4'] + x.tags = ["1", "2", "3", "4"] x.save! - assert_equal ['1','2','3','4'], x.reload.tags + assert_equal ["1", "2", "3", "4"], x.reload.tags end def test_select_with_integers @@ -137,25 +140,25 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase def test_rewrite_with_integers @connection.execute "insert into pg_arrays (ratings) VALUES ('{1,2,3}')" x = PgArray.first - x.ratings = [2, '3', 4] + x.ratings = [2, "3", 4] x.save! assert_equal [2, 3, 4], x.reload.ratings end def test_multi_dimensional_with_strings - assert_cycle(:tags, [[['1'], ['2']], [['2'], ['3']]]) + assert_cycle(:tags, [[["1"], ["2"]], [["2"], ["3"]]]) end def test_with_empty_strings - assert_cycle(:tags, [ '1', '2', '', '4', '', '5' ]) + assert_cycle(:tags, [ "1", "2", "", "4", "", "5" ]) end def test_with_multi_dimensional_empty_strings - assert_cycle(:tags, [[['1', '2'], ['', '4'], ['', '5']]]) + assert_cycle(:tags, [[["1", "2"], ["", "4"], ["", "5"]]]) end def test_with_arbitrary_whitespace - assert_cycle(:tags, [[['1', '2'], [' ', '4'], [' ', '5']]]) + assert_cycle(:tags, [[["1", "2"], [" ", "4"], [" ", "5"]]]) end def test_multi_dimensional_with_integers @@ -163,34 +166,39 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase end def test_strings_with_quotes - assert_cycle(:tags, ['this has','some "s that need to be escaped"']) + assert_cycle(:tags, ["this has", 'some "s that need to be escaped"']) end def test_strings_with_commas - assert_cycle(:tags, ['this,has','many,values']) + assert_cycle(:tags, ["this,has", "many,values"]) end def test_strings_with_array_delimiters - assert_cycle(:tags, ['{','}']) + assert_cycle(:tags, ["{", "}"]) end def test_strings_with_null_strings - assert_cycle(:tags, ['NULL','NULL']) + assert_cycle(:tags, ["NULL", "NULL"]) end def test_contains_nils - assert_cycle(:tags, ['1',nil,nil]) + assert_cycle(:tags, ["1", nil, nil]) end def test_insert_fixture tag_values = ["val1", "val2", "val3_with_'_multiple_quote_'_chars"] - @connection.insert_fixture({"tags" => tag_values}, "pg_arrays" ) + @connection.insert_fixture({ "tags" => tag_values }, "pg_arrays") assert_equal(PgArray.last.tags, tag_values) end def test_attribute_for_inspect_for_array_field + record = PgArray.new { |a| a.ratings = (1..10).to_a } + assert_equal("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", record.attribute_for_inspect(:ratings)) + end + + def test_attribute_for_inspect_for_array_field_for_large_array record = PgArray.new { |a| a.ratings = (1..11).to_a } - assert_equal("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]", record.attribute_for_inspect(:ratings)) + assert_equal("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]", record.attribute_for_inspect(:ratings)) end def test_escaping @@ -206,17 +214,18 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase x = PgArray.create!(tags: tags) x.reload - assert_equal x.tags_before_type_cast, PgArray.type_for_attribute('tags').serialize(tags) + refute x.changed? end def test_quoting_non_standard_delimiters strings = ["hello,", "world;"] oid = ActiveRecord::ConnectionAdapters::PostgreSQL::OID - comma_delim = oid::Array.new(ActiveRecord::Type::String.new, ',') - semicolon_delim = oid::Array.new(ActiveRecord::Type::String.new, ';') + comma_delim = oid::Array.new(ActiveRecord::Type::String.new, ",") + semicolon_delim = oid::Array.new(ActiveRecord::Type::String.new, ";") + conn = PgArray.connection - assert_equal %({"hello,",world;}), comma_delim.serialize(strings) - assert_equal %({hello,;"world;"}), semicolon_delim.serialize(strings) + assert_equal %({"hello,",world;}), conn.type_cast(comma_delim.serialize(strings)) + assert_equal %({hello,;"world;"}), conn.type_cast(semicolon_delim.serialize(strings)) end def test_mutate_array @@ -231,13 +240,13 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase end def test_mutate_value_in_array - x = PgArray.create!(hstores: [{ a: 'a' }, { b: 'b' }]) + x = PgArray.create!(hstores: [{ a: "a" }, { b: "b" }]) - x.hstores.first['a'] = 'c' + x.hstores.first["a"] = "c" x.save! x.reload - assert_equal [{ 'a' => 'c' }, { 'b' => 'b' }], x.hstores + assert_equal [{ "a" => "c" }, { "b" => "b" }], x.hstores assert_not x.changed? end @@ -285,6 +294,12 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase assert_equal record.tags, record.reload.tags end + def test_where_by_attribute_with_array + tags = ["black", "blue"] + record = PgArray.create!(tags: tags) + assert_equal record, PgArray.where(tags: tags).take + end + def test_uniqueness_validation klass = Class.new(PgArray) do validates_uniqueness_of :tags @@ -300,18 +315,33 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase assert_equal ["has already been taken"], e2.errors[:tags], "Should have uniqueness message for tags" end - private - def assert_cycle field, array - # test creation - x = PgArray.create!(field => array) - x.reload - assert_equal(array, x.public_send(field)) + def test_encoding_arrays_of_utf8_strings + arrays_of_utf8_strings = %w(nový ファイル) + assert_equal arrays_of_utf8_strings, @type.deserialize(@type.serialize(arrays_of_utf8_strings)) + assert_equal [arrays_of_utf8_strings], @type.deserialize(@type.serialize([arrays_of_utf8_strings])) + end - # test updating - x = PgArray.create!(field => []) - x.public_send("#{field}=", array) - x.save! - x.reload - assert_equal(array, x.public_send(field)) + def test_precision_is_respected_on_timestamp_columns + time = Time.now.change(usec: 123) + record = PgArray.create!(timestamps: [time]) + + assert_equal 123, record.timestamps.first.usec + record.reload + assert_equal 123, record.timestamps.first.usec end + + private + def assert_cycle(field, array) + # test creation + x = PgArray.create!(field => array) + x.reload + assert_equal(array, x.public_send(field)) + + # test updating + x = PgArray.create!(field => []) + x.public_send("#{field}=", array) + x.save! + x.reload + assert_equal(array, x.public_send(field)) + end end diff --git a/activerecord/test/cases/adapters/postgresql/bit_string_test.rb b/activerecord/test/cases/adapters/postgresql/bit_string_test.rb index cec6081aec..7712e809a2 100644 --- a/activerecord/test/cases/adapters/postgresql/bit_string_test.rb +++ b/activerecord/test/cases/adapters/postgresql/bit_string_test.rb @@ -1,6 +1,6 @@ require "cases/helper" -require 'support/connection_helper' -require 'support/schema_dumping_helper' +require "support/connection_helper" +require "support/schema_dumping_helper" class PostgresqlBitStringTest < ActiveRecord::PostgreSQLTestCase include ConnectionHelper @@ -10,7 +10,7 @@ class PostgresqlBitStringTest < ActiveRecord::PostgreSQLTestCase def setup @connection = ActiveRecord::Base.connection - @connection.create_table('postgresql_bit_strings', :force => true) do |t| + @connection.create_table("postgresql_bit_strings", force: true) do |t| t.bit :a_bit, default: "00000011", limit: 8 t.bit_varying :a_bit_varying, default: "0011", limit: 4 t.bit :another_bit @@ -20,7 +20,7 @@ class PostgresqlBitStringTest < ActiveRecord::PostgreSQLTestCase def teardown return unless @connection - @connection.drop_table 'postgresql_bit_strings', if_exists: true + @connection.drop_table "postgresql_bit_strings", if_exists: true end def test_bit_string_column @@ -44,10 +44,10 @@ class PostgresqlBitStringTest < ActiveRecord::PostgreSQLTestCase end def test_default - assert_equal "00000011", PostgresqlBitString.column_defaults['a_bit'] + assert_equal "00000011", PostgresqlBitString.column_defaults["a_bit"] assert_equal "00000011", PostgresqlBitString.new.a_bit - assert_equal "0011", PostgresqlBitString.column_defaults['a_bit_varying'] + assert_equal "0011", PostgresqlBitString.column_defaults["a_bit_varying"] assert_equal "0011", PostgresqlBitString.new.a_bit_varying end @@ -65,10 +65,11 @@ class PostgresqlBitStringTest < ActiveRecord::PostgreSQLTestCase end def test_roundtrip - PostgresqlBitString.create! a_bit: "00001010", a_bit_varying: "0101" - record = PostgresqlBitString.first + record = PostgresqlBitString.create!(a_bit: "00001010", a_bit_varying: "0101") assert_equal "00001010", record.a_bit assert_equal "0101", record.a_bit_varying + assert_nil record.another_bit + assert_nil record.another_bit_varying record.a_bit = "11111111" record.a_bit_varying = "0xF" diff --git a/activerecord/test/cases/adapters/postgresql/bytea_test.rb b/activerecord/test/cases/adapters/postgresql/bytea_test.rb index 7adc070430..5c207116c4 100644 --- a/activerecord/test/cases/adapters/postgresql/bytea_test.rb +++ b/activerecord/test/cases/adapters/postgresql/bytea_test.rb @@ -1,29 +1,29 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper class ByteaDataType < ActiveRecord::Base - self.table_name = 'bytea_data_type' + self.table_name = "bytea_data_type" end def setup @connection = ActiveRecord::Base.connection begin @connection.transaction do - @connection.create_table('bytea_data_type') do |t| - t.binary 'payload' - t.binary 'serialized' + @connection.create_table("bytea_data_type") do |t| + t.binary "payload" + t.binary "serialized" end end end - @column = ByteaDataType.columns_hash['payload'] + @column = ByteaDataType.columns_hash["payload"] @type = ByteaDataType.type_for_attribute("payload") end teardown do - @connection.drop_table 'bytea_data_type', if_exists: true + @connection.drop_table "bytea_data_type", if_exists: true end def test_column @@ -32,7 +32,7 @@ class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase end def test_binary_columns_are_limitless_the_upper_limit_is_one_GB - assert_equal 'bytea', @connection.type_to_sql(:binary, 100_000) + assert_equal "bytea", @connection.type_to_sql(:binary, 100_000) assert_raise ActiveRecord::ActiveRecordError do @connection.type_to_sql :binary, 4294967295 end @@ -42,8 +42,8 @@ class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase assert @column data = "\u001F\x8B" - assert_equal('UTF-8', data.encoding.name) - assert_equal('ASCII-8BIT', @type.deserialize(data).encoding.name) + assert_equal("UTF-8", data.encoding.name) + assert_equal("ASCII-8BIT", @type.deserialize(data).encoding.name) end def test_type_cast_binary_value @@ -52,7 +52,7 @@ class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase end def test_type_case_nil - assert_equal(nil, @type.deserialize(nil)) + assert_nil(@type.deserialize(nil)) end def test_read_value @@ -66,7 +66,7 @@ class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase def test_read_nil_value @connection.execute "insert into bytea_data_type (payload) VALUES (null)" record = ByteaDataType.first - assert_equal(nil, record.payload) + assert_nil(record.payload) record.delete end @@ -88,14 +88,14 @@ class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase def test_via_to_sql_with_complicating_connection Thread.new do other_conn = ActiveRecord::Base.connection - other_conn.execute('SET standard_conforming_strings = off') + other_conn.execute("SET standard_conforming_strings = off") end.join test_via_to_sql end def test_write_binary - data = File.read(File.join(File.dirname(__FILE__), '..', '..', '..', 'assets', 'example.log')) + data = File.read(File.join(File.dirname(__FILE__), "..", "..", "..", "assets", "example.log")) assert(data.size > 1) record = ByteaDataType.create(payload: data) assert_not record.new_record? @@ -106,8 +106,8 @@ class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase def test_write_nil record = ByteaDataType.create(payload: nil) assert_not record.new_record? - assert_equal(nil, record.payload) - assert_equal(nil, ByteaDataType.where(id: record.id).first.payload) + assert_nil(record.payload) + assert_nil(ByteaDataType.where(id: record.id).first.payload) end class Serializer diff --git a/activerecord/test/cases/adapters/postgresql/case_insensitive_test.rb b/activerecord/test/cases/adapters/postgresql/case_insensitive_test.rb new file mode 100644 index 0000000000..03b44feab6 --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/case_insensitive_test.rb @@ -0,0 +1,26 @@ +require "cases/helper" + +class PostgresqlCaseInsensitiveTest < ActiveRecord::PostgreSQLTestCase + class Default < ActiveRecord::Base; end + + def test_case_insensitiveness + connection = ActiveRecord::Base.connection + table = Default.arel_table + + column = Default.columns_hash["char1"] + comparison = connection.case_insensitive_comparison table, :char1, column, nil + assert_match(/lower/i, comparison.to_sql) + + column = Default.columns_hash["char2"] + comparison = connection.case_insensitive_comparison table, :char2, column, nil + assert_match(/lower/i, comparison.to_sql) + + column = Default.columns_hash["char3"] + comparison = connection.case_insensitive_comparison table, :char3, column, nil + assert_match(/lower/i, comparison.to_sql) + + column = Default.columns_hash["multiline_default"] + comparison = connection.case_insensitive_comparison table, :multiline_default, column, nil + assert_match(/lower/i, comparison.to_sql) + end +end diff --git a/activerecord/test/cases/adapters/postgresql/change_schema_test.rb b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb index bc12df668d..ea642069d2 100644 --- a/activerecord/test/cases/adapters/postgresql/change_schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require "cases/helper" module ActiveRecord class Migration @@ -19,17 +19,17 @@ module ActiveRecord def test_change_string_to_date connection.change_column :strings, :somedate, :timestamp, using: 'CAST("somedate" AS timestamp)' - assert_equal :datetime, connection.columns(:strings).find { |c| c.name == 'somedate' }.type + assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type end def test_change_type_with_symbol connection.change_column :strings, :somedate, :timestamp, cast_as: :timestamp - assert_equal :datetime, connection.columns(:strings).find { |c| c.name == 'somedate' }.type + assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type end def test_change_type_with_array connection.change_column :strings, :somedate, :timestamp, array: true, cast_as: :timestamp - column = connection.columns(:strings).find { |c| c.name == 'somedate' } + column = connection.columns(:strings).find { |c| c.name == "somedate" } assert_equal :datetime, column.type assert column.array? end diff --git a/activerecord/test/cases/adapters/postgresql/citext_test.rb b/activerecord/test/cases/adapters/postgresql/citext_test.rb index bd62041e79..ca95e4b626 100644 --- a/activerecord/test/cases/adapters/postgresql/citext_test.rb +++ b/activerecord/test/cases/adapters/postgresql/citext_test.rb @@ -1,49 +1,49 @@ -require 'cases/helper' -require 'support/schema_dumping_helper' +require "cases/helper" +require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_extensions? class PostgresqlCitextTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper class Citext < ActiveRecord::Base - self.table_name = 'citexts' + self.table_name = "citexts" end def setup @connection = ActiveRecord::Base.connection - enable_extension!('citext', @connection) + enable_extension!("citext", @connection) - @connection.create_table('citexts') do |t| - t.citext 'cival' + @connection.create_table("citexts") do |t| + t.citext "cival" end end teardown do - @connection.drop_table 'citexts', if_exists: true - disable_extension!('citext', @connection) + @connection.drop_table "citexts", if_exists: true + disable_extension!("citext", @connection) end def test_citext_enabled - assert @connection.extension_enabled?('citext') + assert @connection.extension_enabled?("citext") end def test_column - column = Citext.columns_hash['cival'] + column = Citext.columns_hash["cival"] assert_equal :citext, column.type - assert_equal 'citext', column.sql_type + assert_equal "citext", column.sql_type assert_not column.array? - type = Citext.type_for_attribute('cival') + type = Citext.type_for_attribute("cival") assert_not type.binary? end def test_change_table_supports_json @connection.transaction do - @connection.change_table('citexts') do |t| - t.citext 'username' + @connection.change_table("citexts") do |t| + t.citext "username" end Citext.reset_column_information - column = Citext.columns_hash['username'] + column = Citext.columns_hash["username"] assert_equal :citext, column.type raise ActiveRecord::Rollback # reset the schema change @@ -53,7 +53,7 @@ if ActiveRecord::Base.connection.supports_extensions? end def test_write - x = Citext.new(cival: 'Some CI Text') + x = Citext.new(cival: "Some CI Text") x.save! citext = Citext.first assert_equal "Some CI Text", citext.cival @@ -66,8 +66,8 @@ if ActiveRecord::Base.connection.supports_extensions? def test_select_case_insensitive @connection.execute "insert into citexts (cival) values('Cased Text')" - x = Citext.where(cival: 'cased text').first - assert_equal 'Cased Text', x.cival + x = Citext.where(cival: "cased text").first + assert_equal "Cased Text", x.cival end def test_schema_dump_with_shorthand diff --git a/activerecord/test/cases/adapters/postgresql/collation_test.rb b/activerecord/test/cases/adapters/postgresql/collation_test.rb index 8470329c35..b39e298a5d 100644 --- a/activerecord/test/cases/adapters/postgresql/collation_test.rb +++ b/activerecord/test/cases/adapters/postgresql/collation_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class PostgresqlCollationTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper @@ -7,8 +7,8 @@ class PostgresqlCollationTest < ActiveRecord::PostgreSQLTestCase def setup @connection = ActiveRecord::Base.connection @connection.create_table :postgresql_collations, force: true do |t| - t.string :string_c, collation: 'C' - t.text :text_posix, collation: 'POSIX' + t.string :string_c, collation: "C" + t.text :text_posix, collation: "POSIX" end end @@ -17,32 +17,32 @@ class PostgresqlCollationTest < ActiveRecord::PostgreSQLTestCase end test "string column with collation" do - column = @connection.columns(:postgresql_collations).find { |c| c.name == 'string_c' } + column = @connection.columns(:postgresql_collations).find { |c| c.name == "string_c" } assert_equal :string, column.type - assert_equal 'C', column.collation + assert_equal "C", column.collation end test "text column with collation" do - column = @connection.columns(:postgresql_collations).find { |c| c.name == 'text_posix' } + column = @connection.columns(:postgresql_collations).find { |c| c.name == "text_posix" } assert_equal :text, column.type - assert_equal 'POSIX', column.collation + assert_equal "POSIX", column.collation end test "add column with collation" do - @connection.add_column :postgresql_collations, :title, :string, collation: 'C' + @connection.add_column :postgresql_collations, :title, :string, collation: "C" - column = @connection.columns(:postgresql_collations).find { |c| c.name == 'title' } + column = @connection.columns(:postgresql_collations).find { |c| c.name == "title" } assert_equal :string, column.type - assert_equal 'C', column.collation + assert_equal "C", column.collation end test "change column with collation" do @connection.add_column :postgresql_collations, :description, :string - @connection.change_column :postgresql_collations, :description, :text, collation: 'POSIX' + @connection.change_column :postgresql_collations, :description, :text, collation: "POSIX" - column = @connection.columns(:postgresql_collations).find { |c| c.name == 'description' } + column = @connection.columns(:postgresql_collations).find { |c| c.name == "description" } assert_equal :text, column.type - assert_equal 'POSIX', column.collation + assert_equal "POSIX", column.collation end test "schema dump includes collation" do diff --git a/activerecord/test/cases/adapters/postgresql/composite_test.rb b/activerecord/test/cases/adapters/postgresql/composite_test.rb index 1de87e5f01..1da2a9e2ac 100644 --- a/activerecord/test/cases/adapters/postgresql/composite_test.rb +++ b/activerecord/test/cases/adapters/postgresql/composite_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" module PostgresqlCompositeBehavior include ConnectionHelper @@ -20,7 +20,7 @@ module PostgresqlCompositeBehavior street VARCHAR(90) ); SQL - @connection.create_table('postgresql_composites') do |t| + @connection.create_table("postgresql_composites") do |t| t.column :address, :full_address end end @@ -29,8 +29,8 @@ module PostgresqlCompositeBehavior def teardown super - @connection.drop_table 'postgresql_composites', if_exists: true - @connection.execute 'DROP TYPE IF EXISTS full_address' + @connection.drop_table "postgresql_composites", if_exists: true + @connection.execute "DROP TYPE IF EXISTS full_address" reset_connection PostgresqlComposite.reset_column_information end @@ -69,12 +69,12 @@ class PostgresqlCompositeTest < ActiveRecord::PostgreSQLTestCase end private - def ensure_warning_is_issued - warning = capture(:stderr) do - PostgresqlComposite.columns_hash + def ensure_warning_is_issued + warning = capture(:stderr) do + PostgresqlComposite.columns_hash + end + assert_match(/unknown OID \d+: failed to recognize type of 'address'\. It will be treated as String\./, warning) end - assert_match(/unknown OID \d+: failed to recognize type of 'address'\. It will be treated as String\./, warning) - end end class PostgresqlCompositeWithCustomOIDTest < ActiveRecord::PostgreSQLTestCase @@ -126,7 +126,7 @@ class PostgresqlCompositeWithCustomOIDTest < ActiveRecord::PostgreSQLTestCase composite.address = FullAddress.new("Paris", "Rue Basse") composite.save! - assert_equal 'Paris', composite.reload.address.city - assert_equal 'Rue Basse', composite.reload.address.street + assert_equal "Paris", composite.reload.address.city + assert_equal "Rue Basse", composite.reload.address.street end end diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index f8403bfe1a..e916d15f7f 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" module ActiveRecord class PostgresqlConnectionTest < ActiveRecord::PostgreSQLTestCase @@ -13,7 +13,7 @@ module ActiveRecord def setup super @subscriber = SQLSubscriber.new - @subscription = ActiveSupport::Notifications.subscribe('sql.active_record', @subscriber) + @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber) @connection = ActiveRecord::Base.connection end @@ -23,10 +23,10 @@ module ActiveRecord end def test_truncate - count = ActiveRecord::Base.connection.execute("select count(*) from comments").first['count'].to_i + count = ActiveRecord::Base.connection.execute("select count(*) from comments").first["count"].to_i assert_operator count, :>, 0 ActiveRecord::Base.connection.truncate("comments") - count = ActiveRecord::Base.connection.execute("select count(*) from comments").first['count'].to_i + count = ActiveRecord::Base.connection.execute("select count(*) from comments").first["count"].to_i assert_equal 0, count end @@ -54,85 +54,85 @@ module ActiveRecord NonExistentTable.establish_connection(params) # Verify the connection param has been applied. - expect = NonExistentTable.connection.query('show geqo').first.first - assert_equal 'off', expect + expect = NonExistentTable.connection.query("show geqo").first.first + assert_equal "off", expect end def test_reset - @connection.query('ROLLBACK') - @connection.query('SET geqo TO off') + @connection.query("ROLLBACK") + @connection.query("SET geqo TO off") # Verify the setting has been applied. - expect = @connection.query('show geqo').first.first - assert_equal 'off', expect + expect = @connection.query("show geqo").first.first + assert_equal "off", expect @connection.reset! # Verify the setting has been cleared. - expect = @connection.query('show geqo').first.first - assert_equal 'on', expect + expect = @connection.query("show geqo").first.first + assert_equal "on", expect end def test_reset_with_transaction - @connection.query('ROLLBACK') - @connection.query('SET geqo TO off') + @connection.query("ROLLBACK") + @connection.query("SET geqo TO off") # Verify the setting has been applied. - expect = @connection.query('show geqo').first.first - assert_equal 'off', expect + expect = @connection.query("show geqo").first.first + assert_equal "off", expect - @connection.query('BEGIN') + @connection.query("BEGIN") @connection.reset! # Verify the setting has been cleared. - expect = @connection.query('show geqo').first.first - assert_equal 'on', expect + expect = @connection.query("show geqo").first.first + assert_equal "on", expect end def test_tables_logs_name - ActiveSupport::Deprecation.silence { @connection.tables('hello') } - assert_equal 'SCHEMA', @subscriber.logged[0][1] + @connection.tables + assert_equal "SCHEMA", @subscriber.logged[0][1] end def test_indexes_logs_name - @connection.indexes('items', 'hello') - assert_equal 'SCHEMA', @subscriber.logged[0][1] + @connection.indexes("items", "hello") + assert_equal "SCHEMA", @subscriber.logged[0][1] end def test_table_exists_logs_name - ActiveSupport::Deprecation.silence { @connection.table_exists?('items') } - assert_equal 'SCHEMA', @subscriber.logged[0][1] + @connection.table_exists?("items") + assert_equal "SCHEMA", @subscriber.logged[0][1] end def test_table_alias_length_logs_name @connection.instance_variable_set("@table_alias_length", nil) @connection.table_alias_length - assert_equal 'SCHEMA', @subscriber.logged[0][1] + assert_equal "SCHEMA", @subscriber.logged[0][1] end def test_current_database_logs_name @connection.current_database - assert_equal 'SCHEMA', @subscriber.logged[0][1] + assert_equal "SCHEMA", @subscriber.logged[0][1] end def test_encoding_logs_name @connection.encoding - assert_equal 'SCHEMA', @subscriber.logged[0][1] + assert_equal "SCHEMA", @subscriber.logged[0][1] end def test_schema_names_logs_name @connection.schema_names - assert_equal 'SCHEMA', @subscriber.logged[0][1] + assert_equal "SCHEMA", @subscriber.logged[0][1] end if ActiveRecord::Base.connection.prepared_statements def test_statement_key_is_logged bind = Relation::QueryAttribute.new(nil, 1, Type::Value.new) - @connection.exec_query('SELECT $1::integer', 'SQL', [bind], prepare: true) + @connection.exec_query("SELECT $1::integer", "SQL", [bind], prepare: true) name = @subscriber.payloads.last[:statement_name] assert name res = @connection.exec_query("EXPLAIN (FORMAT JSON) EXECUTE #{name}(1)") - plan = res.column_types['QUERY PLAN'].deserialize res.rows.first.first + plan = res.column_types["QUERY PLAN"].deserialize res.rows.first.first assert_operator plan.length, :>, 0 end end @@ -146,7 +146,7 @@ module ActiveRecord # To restart PostgreSQL 9.1 on OS X, installed via MacPorts, ... # sudo su postgres -c "pg_ctl restart -D /opt/local/var/db/postgresql91/defaultdb/ -m fast" def test_reconnection_after_actual_disconnection_with_verify - original_connection_pid = @connection.query('select pg_backend_pid()') + original_connection_pid = @connection.query("select pg_backend_pid()") # Sanity check. assert @connection.active? @@ -155,8 +155,8 @@ module ActiveRecord secondary_connection = ActiveRecord::Base.connection_pool.checkout secondary_connection.query("select pg_terminate_backend(#{original_connection_pid.first.first})") ActiveRecord::Base.connection_pool.checkin(secondary_connection) - elsif ARTest.config['with_manual_interventions'] - puts 'Kill the connection now (e.g. by restarting the PostgreSQL ' + + elsif ARTest.config["with_manual_interventions"] + puts "Kill the connection now (e.g. by restarting the PostgreSQL " + 'server with the "-m fast" option) and then press enter.' $stdin.gets else @@ -172,7 +172,7 @@ module ActiveRecord # If we get no exception here, then either we re-connected successfully, or # we never actually got disconnected. - new_connection_pid = @connection.query('select pg_backend_pid()') + new_connection_pid = @connection.query("select pg_backend_pid()") assert_not_equal original_connection_pid, new_connection_pid, "umm -- looks like you didn't break the connection, because we're still " + @@ -184,7 +184,7 @@ module ActiveRecord def test_set_session_variable_true run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => true}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: true })) set_true = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" assert_equal set_true.rows, [["on"]] end @@ -192,7 +192,7 @@ module ActiveRecord def test_set_session_variable_false run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => false}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: false })) set_false = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN" assert_equal set_false.rows, [["off"]] end @@ -201,14 +201,14 @@ module ActiveRecord def test_set_session_variable_nil run_without_connection do |orig_connection| # This should be a no-op that does not raise an error - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => nil}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: nil })) end end def test_set_session_variable_default run_without_connection do |orig_connection| # This should execute a query that does not raise an error - ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => :default}})) + ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: :default })) end end @@ -224,14 +224,14 @@ module ActiveRecord got_lock = @connection.get_advisory_lock(lock_id) assert got_lock, "get_advisory_lock should have returned true but it didn't" - advisory_lock = @connection.query(list_advisory_locks).find {|l| l[1] == lock_id} + advisory_lock = @connection.query(list_advisory_locks).find { |l| l[1] == lock_id } assert advisory_lock, "expected to find an advisory lock with lock_id #{lock_id} but there wasn't one" released_lock = @connection.release_advisory_lock(lock_id) assert released_lock, "expected release_advisory_lock to return true but it didn't" - advisory_locks = @connection.query(list_advisory_locks).select {|l| l[1] == lock_id} + advisory_locks = @connection.query(list_advisory_locks).select { |l| l[1] == lock_id } assert_empty advisory_locks, "expected to have released advisory lock with lock_id #{lock_id} but it was still held" end @@ -241,17 +241,17 @@ module ActiveRecord with_warning_suppression do released_non_existent_lock = @connection.release_advisory_lock(fake_lock_id) assert_equal released_non_existent_lock, false, - 'expected release_advisory_lock to return false when there was no lock to release' + "expected release_advisory_lock to return false when there was no lock to release" end end - protected + private - def with_warning_suppression - log_level = @connection.client_min_messages - @connection.client_min_messages = 'error' - yield - @connection.client_min_messages = log_level - end + def with_warning_suppression + log_level = @connection.client_min_messages + @connection.client_min_messages = "error" + yield + @connection.client_min_messages = log_level + end end end diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb index 232c25cb3b..0ac8b7339b 100644 --- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb +++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb @@ -1,6 +1,5 @@ require "cases/helper" -require 'support/ddl_helper' - +require "support/ddl_helper" class PostgresqlTime < ActiveRecord::Base end @@ -38,8 +37,8 @@ class PostgresqlDataTypeTest < ActiveRecord::PostgreSQLTestCase end def test_time_values - assert_equal '-1 years -2 days', @first_time.time_interval - assert_equal '-21 days', @first_time.scaled_time_interval + assert_equal "-1 years -2 days", @first_time.time_interval + assert_equal "-21 days", @first_time.scaled_time_interval end def test_oid_values @@ -47,10 +46,10 @@ class PostgresqlDataTypeTest < ActiveRecord::PostgreSQLTestCase end def test_update_time - @first_time.time_interval = '2 years 3 minutes' + @first_time.time_interval = "2 years 3 minutes" assert @first_time.save assert @first_time.reload - assert_equal '2 years 00:03:00', @first_time.time_interval + assert_equal "2 years 00:03:00", @first_time.time_interval end def test_update_oid @@ -62,7 +61,7 @@ class PostgresqlDataTypeTest < ActiveRecord::PostgreSQLTestCase end def test_text_columns_are_limitless_the_upper_limit_is_one_GB - assert_equal 'text', @connection.type_to_sql(:text, 100_000) + assert_equal "text", @connection.type_to_sql(:text, 100_000) assert_raise ActiveRecord::ActiveRecordError do @connection.type_to_sql :text, 4294967295 end @@ -77,15 +76,15 @@ class PostgresqlInternalDataTypeTest < ActiveRecord::PostgreSQLTestCase end def test_name_column_type - with_example_table @connection, 'ex', 'data name' do - column = @connection.columns('ex').find { |col| col.name == 'data' } + with_example_table @connection, "ex", "data name" do + column = @connection.columns("ex").find { |col| col.name == "data" } assert_equal :string, column.type end end def test_char_column_type - with_example_table @connection, 'ex', 'data "char"' do - column = @connection.columns('ex').find { |col| col.name == 'data' } + with_example_table @connection, "ex", 'data "char"' do + column = @connection.columns("ex").find { |col| col.name == "data" } assert_equal :string, column.type end end diff --git a/activerecord/test/cases/adapters/postgresql/domain_test.rb b/activerecord/test/cases/adapters/postgresql/domain_test.rb index 6102ddacd1..f1eb8adb15 100644 --- a/activerecord/test/cases/adapters/postgresql/domain_test.rb +++ b/activerecord/test/cases/adapters/postgresql/domain_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" class PostgresqlDomainTest < ActiveRecord::PostgreSQLTestCase include ConnectionHelper @@ -12,15 +12,15 @@ class PostgresqlDomainTest < ActiveRecord::PostgreSQLTestCase @connection = ActiveRecord::Base.connection @connection.transaction do @connection.execute "CREATE DOMAIN custom_money as numeric(8,2)" - @connection.create_table('postgresql_domains') do |t| + @connection.create_table("postgresql_domains") do |t| t.column :price, :custom_money end end end teardown do - @connection.drop_table 'postgresql_domains', if_exists: true - @connection.execute 'DROP DOMAIN IF EXISTS custom_money' + @connection.drop_table "postgresql_domains", if_exists: true + @connection.execute "DROP DOMAIN IF EXISTS custom_money" reset_connection end diff --git a/activerecord/test/cases/adapters/postgresql/enum_test.rb b/activerecord/test/cases/adapters/postgresql/enum_test.rb index 6816a6514b..5e5a3158ba 100644 --- a/activerecord/test/cases/adapters/postgresql/enum_test.rb +++ b/activerecord/test/cases/adapters/postgresql/enum_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" class PostgresqlEnumTest < ActiveRecord::PostgreSQLTestCase include ConnectionHelper @@ -14,15 +14,15 @@ class PostgresqlEnumTest < ActiveRecord::PostgreSQLTestCase @connection.execute <<-SQL CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); SQL - @connection.create_table('postgresql_enums') do |t| + @connection.create_table("postgresql_enums") do |t| t.column :current_mood, :mood end end end teardown do - @connection.drop_table 'postgresql_enums', if_exists: true - @connection.execute 'DROP TYPE IF EXISTS mood' + @connection.drop_table "postgresql_enums", if_exists: true + @connection.execute "DROP TYPE IF EXISTS mood" reset_connection end @@ -37,10 +37,10 @@ class PostgresqlEnumTest < ActiveRecord::PostgreSQLTestCase end def test_enum_defaults - @connection.add_column 'postgresql_enums', 'good_mood', :mood, default: 'happy' + @connection.add_column "postgresql_enums", "good_mood", :mood, default: "happy" PostgresqlEnum.reset_column_information - assert_equal "happy", PostgresqlEnum.column_defaults['good_mood'] + assert_equal "happy", PostgresqlEnum.column_defaults["good_mood"] assert_equal "happy", PostgresqlEnum.new.good_mood ensure PostgresqlEnum.reset_column_information diff --git a/activerecord/test/cases/adapters/postgresql/explain_test.rb b/activerecord/test/cases/adapters/postgresql/explain_test.rb index 29bf2c15ea..7493bce4fb 100644 --- a/activerecord/test/cases/adapters/postgresql/explain_test.rb +++ b/activerecord/test/cases/adapters/postgresql/explain_test.rb @@ -1,20 +1,20 @@ require "cases/helper" -require 'models/developer' -require 'models/computer' +require "models/developer" +require "models/computer" class PostgreSQLExplainTest < ActiveRecord::PostgreSQLTestCase fixtures :developers def test_explain_for_one_query explain = Developer.where(id: 1).explain - assert_match %r(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = \$?1), explain + assert_match %r(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = (?:\$1 \[\["id", 1\]\]|1)), explain assert_match %(QUERY PLAN), explain end def test_explain_with_eager_loading explain = Developer.where(id: 1).includes(:audit_logs).explain assert_match %(QUERY PLAN), explain - assert_match %r(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = \$?1), explain + assert_match %r(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = (?:\$1 \[\["id", 1\]\]|1)), explain assert_match %(EXPLAIN for: SELECT "audit_logs".* FROM "audit_logs" WHERE "audit_logs"."developer_id" = 1), explain end end diff --git a/activerecord/test/cases/adapters/postgresql/full_text_test.rb b/activerecord/test/cases/adapters/postgresql/full_text_test.rb index bde7513339..5ddfe32007 100644 --- a/activerecord/test/cases/adapters/postgresql/full_text_test.rb +++ b/activerecord/test/cases/adapters/postgresql/full_text_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class PostgresqlFullTextTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper @@ -7,13 +7,13 @@ class PostgresqlFullTextTest < ActiveRecord::PostgreSQLTestCase setup do @connection = ActiveRecord::Base.connection - @connection.create_table('tsvectors') do |t| - t.tsvector 'text_vector' + @connection.create_table("tsvectors") do |t| + t.tsvector "text_vector" end end teardown do - @connection.drop_table 'tsvectors', if_exists: true + @connection.drop_table "tsvectors", if_exists: true end def test_tsvector_column diff --git a/activerecord/test/cases/adapters/postgresql/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb index 66f0a70394..c1f3a4ae2c 100644 --- a/activerecord/test/cases/adapters/postgresql/geometric_test.rb +++ b/activerecord/test/cases/adapters/postgresql/geometric_test.rb @@ -1,6 +1,6 @@ require "cases/helper" -require 'support/connection_helper' -require 'support/schema_dumping_helper' +require "support/connection_helper" +require "support/schema_dumping_helper" class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase include ConnectionHelper @@ -18,7 +18,7 @@ class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase def setup @connection = ActiveRecord::Base.connection - @connection.create_table('postgresql_points') do |t| + @connection.create_table("postgresql_points") do |t| t.point :x t.point :y, default: [12.2, 13.3] t.point :z, default: "(14.4,15.5)" @@ -27,22 +27,10 @@ class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase t.point :legacy_y, default: [12.2, 13.3] t.point :legacy_z, default: "(14.4,15.5)" end - @connection.create_table('deprecated_points') do |t| - t.point :x - end end teardown do - @connection.drop_table 'postgresql_points', if_exists: true - @connection.drop_table 'deprecated_points', if_exists: true - end - - class DeprecatedPoint < ActiveRecord::Base; end - - def test_deprecated_legacy_type - assert_deprecated do - DeprecatedPoint.new - end + @connection.drop_table "postgresql_points", if_exists: true end def test_column @@ -56,10 +44,10 @@ class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase end def test_default - assert_equal ActiveRecord::Point.new(12.2, 13.3), PostgresqlPoint.column_defaults['y'] + assert_equal ActiveRecord::Point.new(12.2, 13.3), PostgresqlPoint.column_defaults["y"] assert_equal ActiveRecord::Point.new(12.2, 13.3), PostgresqlPoint.new.y - assert_equal ActiveRecord::Point.new(14.4, 15.5), PostgresqlPoint.column_defaults['z'] + assert_equal ActiveRecord::Point.new(14.4, 15.5), PostgresqlPoint.column_defaults["z"] assert_equal ActiveRecord::Point.new(14.4, 15.5), PostgresqlPoint.new.z end @@ -108,7 +96,7 @@ class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase assert_nothing_raised { PostgresqlPoint.new(x: "") } p = PostgresqlPoint.new(x: "") - assert_equal nil, p.x + assert_nil p.x end def test_array_of_points_round_trip @@ -136,10 +124,10 @@ class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase end def test_legacy_default - assert_equal [12.2, 13.3], PostgresqlPoint.column_defaults['legacy_y'] + assert_equal [12.2, 13.3], PostgresqlPoint.column_defaults["legacy_y"] assert_equal [12.2, 13.3], PostgresqlPoint.new.legacy_y - assert_equal [14.4, 15.5], PostgresqlPoint.column_defaults['legacy_z'] + assert_equal [14.4, 15.5], PostgresqlPoint.column_defaults["legacy_z"] assert_equal [14.4, 15.5], PostgresqlPoint.new.legacy_z end @@ -190,51 +178,51 @@ class PostgresqlGeometricTest < ActiveRecord::PostgreSQLTestCase end teardown do - @connection.drop_table 'postgresql_geometrics', if_exists: true + @connection.drop_table "postgresql_geometrics", if_exists: true end def test_geometric_types g = PostgresqlGeometric.new( - :a_line_segment => '(2.0, 3), (5.5, 7.0)', - :a_box => '2.0, 3, 5.5, 7.0', - :a_path => '[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]', - :a_polygon => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))', - :a_circle => '<(5.3, 10.4), 2>' + a_line_segment: "(2.0, 3), (5.5, 7.0)", + a_box: "2.0, 3, 5.5, 7.0", + a_path: "[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]", + a_polygon: "((2.0, 3), (5.5, 7.0), (8.5, 11.0))", + a_circle: "<(5.3, 10.4), 2>" ) g.save! h = PostgresqlGeometric.find(g.id) - assert_equal '[(2,3),(5.5,7)]', h.a_line_segment - assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner - assert_equal '[(2,3),(5.5,7),(8.5,11)]', h.a_path - assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon - assert_equal '<(5.3,10.4),2>', h.a_circle + assert_equal "[(2,3),(5.5,7)]", h.a_line_segment + assert_equal "(5.5,7),(2,3)", h.a_box # reordered to store upper right corner then bottom left corner + assert_equal "[(2,3),(5.5,7),(8.5,11)]", h.a_path + assert_equal "((2,3),(5.5,7),(8.5,11))", h.a_polygon + assert_equal "<(5.3,10.4),2>", h.a_circle end def test_alternative_format g = PostgresqlGeometric.new( - :a_line_segment => '((2.0, 3), (5.5, 7.0))', - :a_box => '(2.0, 3), (5.5, 7.0)', - :a_path => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))', - :a_polygon => '2.0, 3, 5.5, 7.0, 8.5, 11.0', - :a_circle => '((5.3, 10.4), 2)' + a_line_segment: "((2.0, 3), (5.5, 7.0))", + a_box: "(2.0, 3), (5.5, 7.0)", + a_path: "((2.0, 3), (5.5, 7.0), (8.5, 11.0))", + a_polygon: "2.0, 3, 5.5, 7.0, 8.5, 11.0", + a_circle: "((5.3, 10.4), 2)" ) g.save! h = PostgresqlGeometric.find(g.id) - assert_equal '[(2,3),(5.5,7)]', h.a_line_segment - assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner - assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_path - assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon - assert_equal '<(5.3,10.4),2>', h.a_circle + assert_equal "[(2,3),(5.5,7)]", h.a_line_segment + assert_equal "(5.5,7),(2,3)", h.a_box # reordered to store upper right corner then bottom left corner + assert_equal "((2,3),(5.5,7),(8.5,11))", h.a_path + assert_equal "((2,3),(5.5,7),(8.5,11))", h.a_polygon + assert_equal "<(5.3,10.4),2>", h.a_circle end def test_geometric_function - PostgresqlGeometric.create! a_path: '[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]' # [ ] is an open path - PostgresqlGeometric.create! a_path: '((2.0, 3), (5.5, 7.0), (8.5, 11.0))' # ( ) is a closed path + PostgresqlGeometric.create! a_path: "[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]" # [ ] is an open path + PostgresqlGeometric.create! a_path: "((2.0, 3), (5.5, 7.0), (8.5, 11.0))" # ( ) is a closed path objs = PostgresqlGeometric.find_by_sql "SELECT isopen(a_path) FROM postgresql_geometrics ORDER BY id ASC" assert_equal [true, false], objs.map(&:isopen) @@ -270,28 +258,28 @@ class PostgreSQLGeometricLineTest < ActiveRecord::PostgreSQLTestCase teardown do if defined?(@connection) - @connection.drop_table 'postgresql_lines', if_exists: true + @connection.drop_table "postgresql_lines", if_exists: true end end def test_geometric_line_type g = PostgresqlLine.new( - a_line: '{2.0, 3, 5.5}' + a_line: "{2.0, 3, 5.5}" ) g.save! h = PostgresqlLine.find(g.id) - assert_equal '{2,3,5.5}', h.a_line + assert_equal "{2,3,5.5}", h.a_line end def test_alternative_format_line_type g = PostgresqlLine.new( - a_line: '(2.0, 3), (4.0, 6.0)' + a_line: "(2.0, 3), (4.0, 6.0)" ) g.save! h = PostgresqlLine.find(g.id) - assert_equal '{1.5,-1,0}', h.a_line + assert_equal "{1.5,-1,0}", h.a_line end def test_schema_dumping_for_line_type @@ -374,12 +362,12 @@ class PostgreSQLGeometricTypesTest < ActiveRecord::PostgreSQLTestCase private - def assert_column_exists(column_name) - assert connection.column_exists?(table_name, column_name) - end + def assert_column_exists(column_name) + assert connection.column_exists?(table_name, column_name) + end - def assert_type_correct(column_name, type) - column = connection.columns(table_name).find { |c| c.name == column_name.to_s } - assert_equal type, column.type - end + def assert_type_correct(column_name, type) + column = connection.columns(table_name).find { |c| c.name == column_name.to_s } + assert_equal type, column.type + end end diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index 27cc65a643..f9cce10fb8 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -1,52 +1,58 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_extensions? class PostgresqlHstoreTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper class Hstore < ActiveRecord::Base - self.table_name = 'hstores' + self.table_name = "hstores" store_accessor :settings, :language, :timezone end + class FakeParameters + def to_unsafe_h + { "hi" => "hi" } + end + end + def setup @connection = ActiveRecord::Base.connection - unless @connection.extension_enabled?('hstore') - @connection.enable_extension 'hstore' + unless @connection.extension_enabled?("hstore") + @connection.enable_extension "hstore" @connection.commit_db_transaction end @connection.reconnect! @connection.transaction do - @connection.create_table('hstores') do |t| - t.hstore 'tags', :default => '' - t.hstore 'payload', array: true - t.hstore 'settings' + @connection.create_table("hstores") do |t| + t.hstore "tags", default: "" + t.hstore "payload", array: true + t.hstore "settings" end end Hstore.reset_column_information - @column = Hstore.columns_hash['tags'] + @column = Hstore.columns_hash["tags"] @type = Hstore.type_for_attribute("tags") end teardown do - @connection.drop_table 'hstores', if_exists: true + @connection.drop_table "hstores", if_exists: true end def test_hstore_included_in_extensions assert @connection.respond_to?(:extensions), "connection should have a list of extensions" - assert @connection.extensions.include?('hstore'), "extension list should include hstore" + assert_includes @connection.extensions, "hstore", "extension list should include hstore" end def test_disable_enable_hstore - assert @connection.extension_enabled?('hstore') - @connection.disable_extension 'hstore' - assert_not @connection.extension_enabled?('hstore') - @connection.enable_extension 'hstore' - assert @connection.extension_enabled?('hstore') + assert @connection.extension_enabled?("hstore") + @connection.disable_extension "hstore" + assert_not @connection.extension_enabled?("hstore") + @connection.enable_extension "hstore" + assert @connection.extension_enabled?("hstore") ensure # Restore column(s) dropped by `drop extension hstore cascade;` load_schema @@ -61,22 +67,22 @@ if ActiveRecord::Base.connection.supports_extensions? end def test_default - @connection.add_column 'hstores', 'permissions', :hstore, default: '"users"=>"read", "articles"=>"write"' + @connection.add_column "hstores", "permissions", :hstore, default: '"users"=>"read", "articles"=>"write"' Hstore.reset_column_information - assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.column_defaults['permissions']) - assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.new.permissions) + assert_equal({ "users" => "read", "articles" => "write" }, Hstore.column_defaults["permissions"]) + assert_equal({ "users" => "read", "articles" => "write" }, Hstore.new.permissions) ensure Hstore.reset_column_information end def test_change_table_supports_hstore @connection.transaction do - @connection.change_table('hstores') do |t| - t.hstore 'users', default: '' + @connection.change_table("hstores") do |t| + t.hstore "users", default: "" end Hstore.reset_column_information - column = Hstore.columns_hash['users'] + column = Hstore.columns_hash["users"] assert_equal :hstore, column.type raise ActiveRecord::Rollback # reset the schema change @@ -103,18 +109,18 @@ if ActiveRecord::Base.connection.supports_extensions? end def test_cast_value_on_write - x = Hstore.new tags: {"bool" => true, "number" => 5} - assert_equal({"bool" => true, "number" => 5}, x.tags_before_type_cast) - assert_equal({"bool" => "true", "number" => "5"}, x.tags) + x = Hstore.new tags: { "bool" => true, "number" => 5 } + assert_equal({ "bool" => true, "number" => 5 }, x.tags_before_type_cast) + assert_equal({ "bool" => "true", "number" => "5" }, x.tags) x.save - assert_equal({"bool" => "true", "number" => "5"}, x.reload.tags) + assert_equal({ "bool" => "true", "number" => "5" }, x.reload.tags) end def test_type_cast_hstore - assert_equal({'1' => '2'}, @type.deserialize("\"1\"=>\"2\"")) + assert_equal({ "1" => "2" }, @type.deserialize("\"1\"=>\"2\"")) assert_equal({}, @type.deserialize("")) - assert_equal({'key'=>nil}, @type.deserialize('key => NULL')) - assert_equal({'c'=>'}','"a"'=>'b "a b'}, @type.deserialize(%q(c=>"}", "\"a\""=>"b \"a b"))) + assert_equal({ "key" => nil }, @type.deserialize("key => NULL")) + assert_equal({ "c" => "}", '"a"' => 'b "a b' }, @type.deserialize(%q(c=>"}", "\"a\""=>"b \"a b"))) end def test_with_store_accessors @@ -156,132 +162,151 @@ if ActiveRecord::Base.connection.supports_extensions? end def test_changes_in_place - hstore = Hstore.create!(settings: { 'one' => 'two' }) - hstore.settings['three'] = 'four' + hstore = Hstore.create!(settings: { "one" => "two" }) + hstore.settings["three"] = "four" hstore.save! hstore.reload - assert_equal 'four', hstore.settings['three'] + assert_equal "four", hstore.settings["three"] assert_not hstore.changed? end + def test_dirty_from_user_equal + settings = { "alongkey" => "anything", "key" => "value" } + hstore = Hstore.create!(settings: settings) + + hstore.settings = { "key" => "value", "alongkey" => "anything" } + assert_equal settings, hstore.settings + refute hstore.changed? + end + + def test_hstore_dirty_from_database_equal + settings = { "alongkey" => "anything", "key" => "value" } + hstore = Hstore.create!(settings: settings) + hstore.reload + + assert_equal settings, hstore.settings + hstore.settings = settings + refute hstore.changed? + end + def test_gen1 - assert_equal(%q(" "=>""), @type.serialize({' '=>''})) + assert_equal('" "=>""', @type.serialize(" " => "")) end def test_gen2 - assert_equal(%q(","=>""), @type.serialize({','=>''})) + assert_equal('","=>""', @type.serialize("," => "")) end def test_gen3 - assert_equal(%q("="=>""), @type.serialize({'='=>''})) + assert_equal('"="=>""', @type.serialize("=" => "")) end def test_gen4 - assert_equal(%q(">"=>""), @type.serialize({'>'=>''})) + assert_equal('">"=>""', @type.serialize(">" => "")) end def test_parse1 - assert_equal({'a'=>nil,'b'=>nil,'c'=>'NuLl','null'=>'c'}, @type.deserialize('a=>null,b=>NuLl,c=>"NuLl",null=>c')) + assert_equal({ "a" => nil, "b" => nil, "c" => "NuLl", "null" => "c" }, @type.deserialize('a=>null,b=>NuLl,c=>"NuLl",null=>c')) end def test_parse2 - assert_equal({" " => " "}, @type.deserialize("\\ =>\\ ")) + assert_equal({ " " => " " }, @type.deserialize("\\ =>\\ ")) end def test_parse3 - assert_equal({"=" => ">"}, @type.deserialize("==>>")) + assert_equal({ "=" => ">" }, @type.deserialize("==>>")) end def test_parse4 - assert_equal({"=a"=>"q=w"}, @type.deserialize('\=a=>q=w')) + assert_equal({ "=a" => "q=w" }, @type.deserialize('\=a=>q=w')) end def test_parse5 - assert_equal({"=a"=>"q=w"}, @type.deserialize('"=a"=>q\=w')) + assert_equal({ "=a" => "q=w" }, @type.deserialize('"=a"=>q\=w')) end def test_parse6 - assert_equal({"\"a"=>"q>w"}, @type.deserialize('"\"a"=>q>w')) + assert_equal({ "\"a" => "q>w" }, @type.deserialize('"\"a"=>q>w')) end def test_parse7 - assert_equal({"\"a"=>"q\"w"}, @type.deserialize('\"a=>q"w')) + assert_equal({ "\"a" => "q\"w" }, @type.deserialize('\"a=>q"w')) end def test_rewrite @connection.execute "insert into hstores (tags) VALUES ('1=>2')" x = Hstore.first - x.tags = { '"a\'' => 'b' } + x.tags = { '"a\'' => "b" } assert x.save! end def test_select @connection.execute "insert into hstores (tags) VALUES ('1=>2')" x = Hstore.first - assert_equal({'1' => '2'}, x.tags) + assert_equal({ "1" => "2" }, x.tags) end def test_array_cycle - assert_array_cycle([{"AA" => "BB", "CC" => "DD"}, {"AA" => nil}]) + assert_array_cycle([{ "AA" => "BB", "CC" => "DD" }, { "AA" => nil }]) end def test_array_strings_with_quotes - assert_array_cycle([{'this has' => 'some "s that need to be escaped"'}]) + assert_array_cycle([{ "this has" => 'some "s that need to be escaped"' }]) end def test_array_strings_with_commas - assert_array_cycle([{'this,has' => 'many,values'}]) + assert_array_cycle([{ "this,has" => "many,values" }]) end def test_array_strings_with_array_delimiters - assert_array_cycle(['{' => '}']) + assert_array_cycle(["{" => "}"]) end def test_array_strings_with_null_strings - assert_array_cycle([{'NULL' => 'NULL'}]) + assert_array_cycle([{ "NULL" => "NULL" }]) end def test_contains_nils - assert_array_cycle([{'NULL' => nil}]) + assert_array_cycle([{ "NULL" => nil }]) end def test_select_multikey @connection.execute "insert into hstores (tags) VALUES ('1=>2,2=>3')" x = Hstore.first - assert_equal({'1' => '2', '2' => '3'}, x.tags) + assert_equal({ "1" => "2", "2" => "3" }, x.tags) end def test_create - assert_cycle('a' => 'b', '1' => '2') + assert_cycle("a" => "b", "1" => "2") end def test_nil - assert_cycle('a' => nil) + assert_cycle("a" => nil) end def test_quotes - assert_cycle('a' => 'b"ar', '1"foo' => '2') + assert_cycle("a" => 'b"ar', '1"foo' => "2") end def test_whitespace - assert_cycle('a b' => 'b ar', '1"foo' => '2') + assert_cycle("a b" => "b ar", '1"foo' => "2") end def test_backslash - assert_cycle('a\\b' => 'b\\ar', '1"foo' => '2') + assert_cycle('a\\b' => 'b\\ar', '1"foo' => "2") end def test_comma - assert_cycle('a, b' => 'bar', '1"foo' => '2') + assert_cycle("a, b" => "bar", '1"foo' => "2") end def test_arrow - assert_cycle('a=>b' => 'bar', '1"foo' => '2') + assert_cycle("a=>b" => "bar", '1"foo' => "2") end def test_quoting_special_characters - assert_cycle('ca' => 'cà', 'ac' => 'àc') + assert_cycle("ca" => "cà", "ac" => "àc") end def test_multiline @@ -300,20 +325,20 @@ if ActiveRecord::Base.connection.supports_extensions? end def test_hstore_with_serialized_attributes - HstoreWithSerialize.create! tags: TagCollection.new({"one" => "two"}) + HstoreWithSerialize.create! tags: TagCollection.new("one" => "two") record = HstoreWithSerialize.first assert_instance_of TagCollection, record.tags - assert_equal({"one" => "two"}, record.tags.to_hash) + assert_equal({ "one" => "two" }, record.tags.to_hash) record.tags = TagCollection.new("three" => "four") record.save! - assert_equal({"three" => "four"}, HstoreWithSerialize.first.tags.to_hash) + assert_equal({ "three" => "four" }, HstoreWithSerialize.first.tags.to_hash) end def test_clone_hstore_with_serialized_attributes - HstoreWithSerialize.create! tags: TagCollection.new({"one" => "two"}) + HstoreWithSerialize.create! tags: TagCollection.new("one" => "two") record = HstoreWithSerialize.first dupe = record.dup - assert_equal({"one" => "two"}, dupe.tags.to_hash) + assert_equal({ "one" => "two" }, dupe.tags.to_hash) end def test_schema_dump_with_shorthand @@ -321,33 +346,37 @@ if ActiveRecord::Base.connection.supports_extensions? assert_match %r[t\.hstore "tags",\s+default: {}], output end - private - def assert_array_cycle(array) - # test creation - x = Hstore.create!(payload: array) - x.reload - assert_equal(array, x.payload) - - # test updating - x = Hstore.create!(payload: []) - x.payload = array - x.save! - x.reload - assert_equal(array, x.payload) + def test_supports_to_unsafe_h_values + assert_equal("\"hi\"=>\"hi\"", @type.serialize(FakeParameters.new)) end - def assert_cycle(hash) - # test creation - x = Hstore.create!(:tags => hash) - x.reload - assert_equal(hash, x.tags) + private + def assert_array_cycle(array) + # test creation + x = Hstore.create!(payload: array) + x.reload + assert_equal(array, x.payload) + + # test updating + x = Hstore.create!(payload: []) + x.payload = array + x.save! + x.reload + assert_equal(array, x.payload) + end - # test updating - x = Hstore.create!(:tags => {}) - x.tags = hash - x.save! - x.reload - assert_equal(hash, x.tags) - end + def assert_cycle(hash) + # test creation + x = Hstore.create!(tags: hash) + x.reload + assert_equal(hash, x.tags) + + # test updating + x = Hstore.create!(tags: {}) + x.tags = hash + x.save! + x.reload + assert_equal(hash, x.tags) + end end end diff --git a/activerecord/test/cases/adapters/postgresql/infinity_test.rb b/activerecord/test/cases/adapters/postgresql/infinity_test.rb index bfda933fa4..19b00258b6 100644 --- a/activerecord/test/cases/adapters/postgresql/infinity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/infinity_test.rb @@ -15,7 +15,7 @@ class PostgresqlInfinityTest < ActiveRecord::PostgreSQLTestCase end teardown do - @connection.drop_table 'postgresql_infinities', if_exists: true + @connection.drop_table "postgresql_infinities", if_exists: true end test "type casting infinity on a float column" do @@ -25,11 +25,11 @@ class PostgresqlInfinityTest < ActiveRecord::PostgreSQLTestCase end test "type casting string on a float column" do - record = PostgresqlInfinity.new(float: 'Infinity') + record = PostgresqlInfinity.new(float: "Infinity") assert_equal Float::INFINITY, record.float - record = PostgresqlInfinity.new(float: '-Infinity') + record = PostgresqlInfinity.new(float: "-Infinity") assert_equal(-Float::INFINITY, record.float) - record = PostgresqlInfinity.new(float: 'NaN') + record = PostgresqlInfinity.new(float: "NaN") assert_send [record.float, :nan?] end diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb index 663de680b5..93558ac4d2 100644 --- a/activerecord/test/cases/adapters/postgresql/json_test.rb +++ b/activerecord/test/cases/adapters/postgresql/json_test.rb @@ -1,11 +1,11 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" module PostgresqlJSONSharedTestCases include SchemaDumpingHelper class JsonDataType < ActiveRecord::Base - self.table_name = 'json_data_type' + self.table_name = "json_data_type" store_accessor :settings, :resolution end @@ -13,9 +13,9 @@ module PostgresqlJSONSharedTestCases def setup @connection = ActiveRecord::Base.connection begin - @connection.create_table('json_data_type') do |t| - t.public_send column_type, 'payload', default: {} # t.json 'payload', default: {} - t.public_send column_type, 'settings' # t.json 'settings' + @connection.create_table("json_data_type") do |t| + t.public_send column_type, "payload", default: {} # t.json 'payload', default: {} + t.public_send column_type, "settings" # t.json 'settings' end rescue ActiveRecord::StatementInvalid skip "do not test on PostgreSQL without #{column_type} type." @@ -38,22 +38,22 @@ module PostgresqlJSONSharedTestCases end def test_default - @connection.add_column 'json_data_type', 'permissions', column_type, default: {"users": "read", "posts": ["read", "write"]} + @connection.add_column "json_data_type", "permissions", column_type, default: { "users": "read", "posts": ["read", "write"] } JsonDataType.reset_column_information - assert_equal({"users"=>"read", "posts"=>["read", "write"]}, JsonDataType.column_defaults['permissions']) - assert_equal({"users"=>"read", "posts"=>["read", "write"]}, JsonDataType.new.permissions) + assert_equal({ "users" => "read", "posts" => ["read", "write"] }, JsonDataType.column_defaults["permissions"]) + assert_equal({ "users" => "read", "posts" => ["read", "write"] }, JsonDataType.new.permissions) ensure JsonDataType.reset_column_information end def test_change_table_supports_json @connection.transaction do - @connection.change_table('json_data_type') do |t| - t.public_send column_type, 'users', default: '{}' # t.json 'users', default: '{}' + @connection.change_table("json_data_type") do |t| + t.public_send column_type, "users", default: "{}" # t.json 'users', default: '{}' end JsonDataType.reset_column_information - column = JsonDataType.columns_hash['users'] + column = JsonDataType.columns_hash["users"] assert_equal column_type, column.type raise ActiveRecord::Rollback # reset the schema change @@ -68,11 +68,11 @@ module PostgresqlJSONSharedTestCases end def test_cast_value_on_write - x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar} - assert_equal({"string" => "foo", :symbol => :bar}, x.payload_before_type_cast) - assert_equal({"string" => "foo", "symbol" => "bar"}, x.payload) + x = JsonDataType.new payload: { "string" => "foo", :symbol => :bar } + assert_equal({ "string" => "foo", :symbol => :bar }, x.payload_before_type_cast) + assert_equal({ "string" => "foo", "symbol" => "bar" }, x.payload) x.save - assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload) + assert_equal({ "string" => "foo", "symbol" => "bar" }, x.reload.payload) end def test_type_cast_json @@ -80,49 +80,65 @@ module PostgresqlJSONSharedTestCases data = "{\"a_key\":\"a_value\"}" hash = type.deserialize(data) - assert_equal({'a_key' => 'a_value'}, hash) - assert_equal({'a_key' => 'a_value'}, type.deserialize(data)) + assert_equal({ "a_key" => "a_value" }, hash) + assert_equal({ "a_key" => "a_value" }, type.deserialize(data)) assert_equal({}, type.deserialize("{}")) - assert_equal({'key'=>nil}, type.deserialize('{"key": null}')) - assert_equal({'c'=>'}','"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"}))) + assert_equal({ "key" => nil }, type.deserialize('{"key": null}')) + assert_equal({ "c" => "}", '"a"' => 'b "a b' }, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"}))) end def test_rewrite @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" x = JsonDataType.first - x.payload = { '"a\'' => 'b' } + x.payload = { '"a\'' => "b" } assert x.save! end def test_select @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" x = JsonDataType.first - assert_equal({'k' => 'v'}, x.payload) + assert_equal({ "k" => "v" }, x.payload) end def test_select_multikey @connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')| x = JsonDataType.first - assert_equal({'k1' => 'v1', 'k2' => 'v2', 'k3' => [1,2,3]}, x.payload) + assert_equal({ "k1" => "v1", "k2" => "v2", "k3" => [1, 2, 3] }, x.payload) end def test_null_json - @connection.execute %q|insert into json_data_type (payload) VALUES(null)| + @connection.execute "insert into json_data_type (payload) VALUES(null)" x = JsonDataType.first - assert_equal(nil, x.payload) + assert_nil(x.payload) + end + + def test_select_nil_json_after_create + json = JsonDataType.create(payload: nil) + x = JsonDataType.where(payload: nil).first + assert_equal(json, x) + end + + def test_select_nil_json_after_update + json = JsonDataType.create(payload: "foo") + x = JsonDataType.where(payload: nil).first + assert_nil(x) + + json.update_attributes payload: nil + x = JsonDataType.where(payload: nil).first + assert_equal(json.reload, x) end def test_select_array_json_value @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| x = JsonDataType.first - assert_equal(['v0', {'k1' => 'v1'}], x.payload) + assert_equal(["v0", { "k1" => "v1" }], x.payload) end def test_rewrite_array_json_value @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')| x = JsonDataType.first - x.payload = ['v1', {'k2' => 'v2'}, 'v3'] + x.payload = ["v1", { "k2" => "v2" }, "v3"] assert x.save! end @@ -161,20 +177,20 @@ module PostgresqlJSONSharedTestCases json = JsonDataType.new assert_not json.changed? - json.payload = { 'one' => 'two' } + json.payload = { "one" => "two" } assert json.changed? assert json.payload_changed? json.save! assert_not json.changed? - json.payload['three'] = 'four' + json.payload["three"] = "four" assert json.payload_changed? json.save! json.reload - assert_equal({ 'one' => 'two', 'three' => 'four' }, json.payload) + assert_equal({ "one" => "two", "three" => "four" }, json.payload) assert_not json.changed? end diff --git a/activerecord/test/cases/adapters/postgresql/legacy_migration_test.rb b/activerecord/test/cases/adapters/postgresql/legacy_migration_test.rb new file mode 100644 index 0000000000..082fe95053 --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/legacy_migration_test.rb @@ -0,0 +1,54 @@ +require "cases/helper" + +class PostgresqlLegacyMigrationTest < ActiveRecord::PostgreSQLTestCase + class GenerateTableWithoutBigserial < ActiveRecord::Migration[5.0] + def change + create_table :legacy_integer_pk do |table| + table.string :foo + end + + create_table :override_pk, id: :bigint do |table| + table.string :bar + end + end + end + + def setup + super + + @migration_verbose_old = ActiveRecord::Migration.verbose + ActiveRecord::Migration.verbose = false + + migrations = [GenerateTableWithoutBigserial.new(nil, 1)] + ActiveRecord::Migrator.new(:up, migrations).migrate + end + + def teardown + ActiveRecord::Migration.verbose = @migration_verbose_old + + super + end + + def test_create_table_uses_serial_as_pkey_by_default + col = column(:legacy_integer_pk, :id) + assert_equal "integer", sql_type_for(col) + assert col.serial? + end + + def test_create_tables_respects_pk_column_type_override + col = column(:override_pk, :id) + assert_equal "bigint", sql_type_for(col) + end + + private + + def column(table_name, column_name) + ActiveRecord::Base.connection. + columns(table_name.to_s). + detect { |c| c.name == column_name.to_s } + end + + def sql_type_for(col) + col && col.sql_type + end +end diff --git a/activerecord/test/cases/adapters/postgresql/ltree_test.rb b/activerecord/test/cases/adapters/postgresql/ltree_test.rb index 56516c82b4..2b5ac1cac6 100644 --- a/activerecord/test/cases/adapters/postgresql/ltree_test.rb +++ b/activerecord/test/cases/adapters/postgresql/ltree_test.rb @@ -1,20 +1,20 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class PostgresqlLtreeTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper class Ltree < ActiveRecord::Base - self.table_name = 'ltrees' + self.table_name = "ltrees" end def setup @connection = ActiveRecord::Base.connection - enable_extension!('ltree', @connection) + enable_extension!("ltree", @connection) @connection.transaction do - @connection.create_table('ltrees') do |t| - t.ltree 'path' + @connection.create_table("ltrees") do |t| + t.ltree "path" end end rescue ActiveRecord::StatementInvalid @@ -22,28 +22,28 @@ class PostgresqlLtreeTest < ActiveRecord::PostgreSQLTestCase end teardown do - @connection.drop_table 'ltrees', if_exists: true + @connection.drop_table "ltrees", if_exists: true end def test_column - column = Ltree.columns_hash['path'] + column = Ltree.columns_hash["path"] assert_equal :ltree, column.type assert_equal "ltree", column.sql_type assert_not column.array? - type = Ltree.type_for_attribute('path') + type = Ltree.type_for_attribute("path") assert_not type.binary? end def test_write - ltree = Ltree.new(path: '1.2.3.4') + ltree = Ltree.new(path: "1.2.3.4") assert ltree.save! end def test_select @connection.execute "insert into ltrees (path) VALUES ('1.2.3')" ltree = Ltree.first - assert_equal '1.2.3', ltree.path + assert_equal "1.2.3", ltree.path end def test_schema_dump_with_shorthand diff --git a/activerecord/test/cases/adapters/postgresql/money_test.rb b/activerecord/test/cases/adapters/postgresql/money_test.rb index c031178479..1b5d8362af 100644 --- a/activerecord/test/cases/adapters/postgresql/money_test.rb +++ b/activerecord/test/cases/adapters/postgresql/money_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper @@ -9,14 +9,14 @@ class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase setup do @connection = ActiveRecord::Base.connection @connection.execute("set lc_monetary = 'C'") - @connection.create_table('postgresql_moneys', force: true) do |t| + @connection.create_table("postgresql_moneys", force: true) do |t| t.money "wealth" t.money "depth", default: "150.55" end end teardown do - @connection.drop_table 'postgresql_moneys', if_exists: true + @connection.drop_table "postgresql_moneys", if_exists: true end def test_column @@ -31,7 +31,7 @@ class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase end def test_default - assert_equal BigDecimal.new("150.55"), PostgresqlMoney.column_defaults['depth'] + assert_equal BigDecimal.new("150.55"), PostgresqlMoney.column_defaults["depth"] assert_equal BigDecimal.new("150.55"), PostgresqlMoney.new.depth end @@ -46,7 +46,7 @@ class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase end def test_money_type_cast - type = PostgresqlMoney.type_for_attribute('wealth') + type = PostgresqlMoney.type_for_attribute("wealth") assert_equal(12345678.12, type.cast("$12,345,678.12")) assert_equal(12345678.12, type.cast("$12.345.678,12")) assert_equal(-1.15, type.cast("-$1.15")) @@ -63,7 +63,7 @@ class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase money = PostgresqlMoney.create(wealth: "987.65") assert_equal 987.65, money.wealth - new_value = BigDecimal.new('123.45') + new_value = BigDecimal.new("123.45") money.wealth = new_value money.save! money.reload @@ -80,7 +80,7 @@ class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase def test_update_all_with_money_big_decimal money = PostgresqlMoney.create! - PostgresqlMoney.update_all(wealth: '123.45'.to_d) + PostgresqlMoney.update_all(wealth: "123.45".to_d) money.reload assert_equal 123.45, money.wealth diff --git a/activerecord/test/cases/adapters/postgresql/network_test.rb b/activerecord/test/cases/adapters/postgresql/network_test.rb index fe6ee4e2d9..a33b0ef8a7 100644 --- a/activerecord/test/cases/adapters/postgresql/network_test.rb +++ b/activerecord/test/cases/adapters/postgresql/network_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class PostgresqlNetworkTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper @@ -7,15 +7,15 @@ class PostgresqlNetworkTest < ActiveRecord::PostgreSQLTestCase setup do @connection = ActiveRecord::Base.connection - @connection.create_table('postgresql_network_addresses', force: true) do |t| - t.inet 'inet_address', default: "192.168.1.1" - t.cidr 'cidr_address', default: "192.168.1.0/24" - t.macaddr 'mac_address', default: "ff:ff:ff:ff:ff:ff" + @connection.create_table("postgresql_network_addresses", force: true) do |t| + t.inet "inet_address", default: "192.168.1.1" + t.cidr "cidr_address", default: "192.168.1.0/24" + t.macaddr "mac_address", default: "ff:ff:ff:ff:ff:ff" end end teardown do - @connection.drop_table 'postgresql_network_addresses', if_exists: true + @connection.drop_table "postgresql_network_addresses", if_exists: true end def test_cidr_column @@ -49,33 +49,33 @@ class PostgresqlNetworkTest < ActiveRecord::PostgreSQLTestCase end def test_network_types - PostgresqlNetworkAddress.create(cidr_address: '192.168.0.0/24', - inet_address: '172.16.1.254/32', - mac_address: '01:23:45:67:89:0a') + PostgresqlNetworkAddress.create(cidr_address: "192.168.0.0/24", + inet_address: "172.16.1.254/32", + mac_address: "01:23:45:67:89:0a") address = PostgresqlNetworkAddress.first - assert_equal IPAddr.new('192.168.0.0/24'), address.cidr_address - assert_equal IPAddr.new('172.16.1.254'), address.inet_address - assert_equal '01:23:45:67:89:0a', address.mac_address + assert_equal IPAddr.new("192.168.0.0/24"), address.cidr_address + assert_equal IPAddr.new("172.16.1.254"), address.inet_address + assert_equal "01:23:45:67:89:0a", address.mac_address - address.cidr_address = '10.1.2.3/32' - address.inet_address = '10.0.0.0/8' - address.mac_address = 'bc:de:f0:12:34:56' + address.cidr_address = "10.1.2.3/32" + address.inet_address = "10.0.0.0/8" + address.mac_address = "bc:de:f0:12:34:56" address.save! assert address.reload - assert_equal IPAddr.new('10.1.2.3/32'), address.cidr_address - assert_equal IPAddr.new('10.0.0.0/8'), address.inet_address - assert_equal 'bc:de:f0:12:34:56', address.mac_address + assert_equal IPAddr.new("10.1.2.3/32"), address.cidr_address + assert_equal IPAddr.new("10.0.0.0/8"), address.inet_address + assert_equal "bc:de:f0:12:34:56", address.mac_address end def test_invalid_network_address - invalid_address = PostgresqlNetworkAddress.new(cidr_address: 'invalid addr', - inet_address: 'invalid addr') + invalid_address = PostgresqlNetworkAddress.new(cidr_address: "invalid addr", + inet_address: "invalid addr") assert_nil invalid_address.cidr_address assert_nil invalid_address.inet_address - assert_equal 'invalid addr', invalid_address.cidr_address_before_type_cast - assert_equal 'invalid addr', invalid_address.inet_address_before_type_cast + assert_equal "invalid addr", invalid_address.cidr_address_before_type_cast + assert_equal "invalid addr", invalid_address.inet_address_before_type_cast assert invalid_address.save invalid_address.reload diff --git a/activerecord/test/cases/adapters/postgresql/numbers_test.rb b/activerecord/test/cases/adapters/postgresql/numbers_test.rb index ba7e7dc9a3..834354dcc9 100644 --- a/activerecord/test/cases/adapters/postgresql/numbers_test.rb +++ b/activerecord/test/cases/adapters/postgresql/numbers_test.rb @@ -5,14 +5,14 @@ class PostgresqlNumberTest < ActiveRecord::PostgreSQLTestCase setup do @connection = ActiveRecord::Base.connection - @connection.create_table('postgresql_numbers', force: true) do |t| - t.column 'single', 'REAL' - t.column 'double', 'DOUBLE PRECISION' + @connection.create_table("postgresql_numbers", force: true) do |t| + t.column "single", "REAL" + t.column "double", "DOUBLE PRECISION" end end teardown do - @connection.drop_table 'postgresql_numbers', if_exists: true + @connection.drop_table "postgresql_numbers", if_exists: true end def test_data_type diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index 9832df7839..e6af93a53e 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -1,6 +1,6 @@ require "cases/helper" -require 'support/ddl_helper' -require 'support/connection_helper' +require "support/ddl_helper" +require "support/connection_helper" module ActiveRecord module ConnectionAdapters @@ -15,15 +15,15 @@ module ActiveRecord def test_bad_connection assert_raise ActiveRecord::NoDatabaseError do - configuration = ActiveRecord::Base.configurations['arunit'].merge(database: 'should_not_exist-cinco-dog-db') + configuration = ActiveRecord::Base.configurations["arunit"].merge(database: "should_not_exist-cinco-dog-db") connection = ActiveRecord::Base.postgresql_connection(configuration) - connection.exec_query('SELECT 1') + connection.exec_query("SELECT 1") end end def test_valid_column with_example_table do - column = @connection.columns('ex').find { |col| col.name == 'id' } + column = @connection.columns("ex").find { |col| col.name == "id" } assert @connection.valid_type?(column.type) end end @@ -34,144 +34,138 @@ module ActiveRecord def test_primary_key with_example_table do - assert_equal 'id', @connection.primary_key('ex') + assert_equal "id", @connection.primary_key("ex") end end def test_primary_key_works_tables_containing_capital_letters - assert_equal 'id', @connection.primary_key('CamelCase') + assert_equal "id", @connection.primary_key("CamelCase") end def test_non_standard_primary_key - with_example_table 'data character varying(255) primary key' do - assert_equal 'data', @connection.primary_key('ex') + with_example_table "data character varying(255) primary key" do + assert_equal "data", @connection.primary_key("ex") end end def test_primary_key_returns_nil_for_no_pk - with_example_table 'id integer' do - assert_nil @connection.primary_key('ex') + with_example_table "id integer" do + assert_nil @connection.primary_key("ex") end end def test_primary_key_raises_error_if_table_not_found assert_raises(ActiveRecord::StatementInvalid) do - @connection.primary_key('unobtainium') + @connection.primary_key("unobtainium") end end def test_exec_insert_with_returning_disabled connection = connection_without_insert_returning - result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id', 'postgresql_partitioned_table_parent_id_seq') - expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first + result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], "id", "postgresql_partitioned_table_parent_id_seq") + expect = connection.query("select max(id) from postgresql_partitioned_table_parent").first.first assert_equal expect.to_i, result.rows.first.first end def test_exec_insert_with_returning_disabled_and_no_sequence_name_given connection = connection_without_insert_returning - result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id') - expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first + result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], "id") + expect = connection.query("select max(id) from postgresql_partitioned_table_parent").first.first assert_equal expect.to_i, result.rows.first.first end def test_exec_insert_default_values_with_returning_disabled_and_no_sequence_name_given connection = connection_without_insert_returning - result = connection.exec_insert("insert into postgresql_partitioned_table_parent DEFAULT VALUES", nil, [], 'id') - expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first + result = connection.exec_insert("insert into postgresql_partitioned_table_parent DEFAULT VALUES", nil, [], "id") + expect = connection.query("select max(id) from postgresql_partitioned_table_parent").first.first assert_equal expect.to_i, result.rows.first.first end def test_exec_insert_default_values_quoted_schema_with_returning_disabled_and_no_sequence_name_given connection = connection_without_insert_returning - result = connection.exec_insert('insert into "public"."postgresql_partitioned_table_parent" DEFAULT VALUES', nil, [], 'id') - expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first + result = connection.exec_insert('insert into "public"."postgresql_partitioned_table_parent" DEFAULT VALUES', nil, [], "id") + expect = connection.query("select max(id) from postgresql_partitioned_table_parent").first.first assert_equal expect.to_i, result.rows.first.first end - def test_sql_for_insert_with_returning_disabled - connection = connection_without_insert_returning - sql, binds = connection.sql_for_insert('sql', nil, nil, nil, 'binds') - assert_equal ['sql', 'binds'], [sql, binds] - end - def test_serial_sequence - assert_equal 'public.accounts_id_seq', - @connection.serial_sequence('accounts', 'id') + assert_equal "public.accounts_id_seq", + @connection.serial_sequence("accounts", "id") assert_raises(ActiveRecord::StatementInvalid) do - @connection.serial_sequence('zomg', 'id') + @connection.serial_sequence("zomg", "id") end end def test_default_sequence_name - assert_equal 'public.accounts_id_seq', - @connection.default_sequence_name('accounts', 'id') + assert_equal "public.accounts_id_seq", + @connection.default_sequence_name("accounts", "id") - assert_equal 'public.accounts_id_seq', - @connection.default_sequence_name('accounts') + assert_equal "public.accounts_id_seq", + @connection.default_sequence_name("accounts") end def test_default_sequence_name_bad_table - assert_equal 'zomg_id_seq', - @connection.default_sequence_name('zomg', 'id') + assert_equal "zomg_id_seq", + @connection.default_sequence_name("zomg", "id") - assert_equal 'zomg_id_seq', - @connection.default_sequence_name('zomg') + assert_equal "zomg_id_seq", + @connection.default_sequence_name("zomg") end def test_pk_and_sequence_for with_example_table do - pk, seq = @connection.pk_and_sequence_for('ex') - assert_equal 'id', pk - assert_equal @connection.default_sequence_name('ex', 'id'), seq.to_s + pk, seq = @connection.pk_and_sequence_for("ex") + assert_equal "id", pk + assert_equal @connection.default_sequence_name("ex", "id"), seq.to_s end end def test_pk_and_sequence_for_with_non_standard_primary_key - with_example_table 'code serial primary key' do - pk, seq = @connection.pk_and_sequence_for('ex') - assert_equal 'code', pk - assert_equal @connection.default_sequence_name('ex', 'code'), seq.to_s + with_example_table "code serial primary key" do + pk, seq = @connection.pk_and_sequence_for("ex") + assert_equal "code", pk + assert_equal @connection.default_sequence_name("ex", "code"), seq.to_s end end def test_pk_and_sequence_for_returns_nil_if_no_seq - with_example_table 'id integer primary key' do - assert_nil @connection.pk_and_sequence_for('ex') + with_example_table "id integer primary key" do + assert_nil @connection.pk_and_sequence_for("ex") end end def test_pk_and_sequence_for_returns_nil_if_no_pk - with_example_table 'id integer' do - assert_nil @connection.pk_and_sequence_for('ex') + with_example_table "id integer" do + assert_nil @connection.pk_and_sequence_for("ex") end end def test_pk_and_sequence_for_returns_nil_if_table_not_found - assert_nil @connection.pk_and_sequence_for('unobtainium') + assert_nil @connection.pk_and_sequence_for("unobtainium") end def test_pk_and_sequence_for_with_collision_pg_class_oid - @connection.exec_query('create table ex(id serial primary key)') - @connection.exec_query('create table ex2(id serial primary key)') + @connection.exec_query("create table ex(id serial primary key)") + @connection.exec_query("create table ex2(id serial primary key)") correct_depend_record = [ "'pg_class'::regclass", "'ex_id_seq'::regclass", - '0', + "0", "'pg_class'::regclass", "'ex'::regclass", - '1', + "1", "'a'" ] collision_depend_record = [ "'pg_attrdef'::regclass", "'ex2_id_seq'::regclass", - '0', + "0", "'pg_class'::regclass", "'ex'::regclass", - '1', + "1", "'a'" ] @@ -185,15 +179,15 @@ module ActiveRecord "INSERT INTO pg_depend VALUES(#{correct_depend_record.join(',')})" ) - seq = @connection.pk_and_sequence_for('ex').last + seq = @connection.pk_and_sequence_for("ex").last assert_equal PostgreSQL::Name.new("public", "ex_id_seq"), seq @connection.exec_query( "DELETE FROM pg_depend WHERE objid = 'ex2_id_seq'::regclass AND refobjid = 'ex'::regclass AND deptype = 'a'" ) ensure - @connection.drop_table 'ex', if_exists: true - @connection.drop_table 'ex2', if_exists: true + @connection.drop_table "ex", if_exists: true + @connection.drop_table "ex2", if_exists: true end def test_table_alias_length @@ -204,74 +198,74 @@ module ActiveRecord def test_exec_no_binds with_example_table do - result = @connection.exec_query('SELECT id, data FROM ex') + result = @connection.exec_query("SELECT id, data FROM ex") assert_equal 0, result.rows.length assert_equal 2, result.columns.length assert_equal %w{ id data }, result.columns - string = @connection.quote('foo') + string = @connection.quote("foo") @connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})") - result = @connection.exec_query('SELECT id, data FROM ex') + result = @connection.exec_query("SELECT id, data FROM ex") assert_equal 1, result.rows.length assert_equal 2, result.columns.length - assert_equal [[1, 'foo']], result.rows + assert_equal [[1, "foo"]], result.rows end end if ActiveRecord::Base.connection.prepared_statements def test_exec_with_binds with_example_table do - string = @connection.quote('foo') + string = @connection.quote("foo") @connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})") bind = Relation::QueryAttribute.new("id", 1, Type::Value.new) - result = @connection.exec_query('SELECT id, data FROM ex WHERE id = $1', nil, [bind]) + result = @connection.exec_query("SELECT id, data FROM ex WHERE id = $1", nil, [bind]) assert_equal 1, result.rows.length assert_equal 2, result.columns.length - assert_equal [[1, 'foo']], result.rows + assert_equal [[1, "foo"]], result.rows end end def test_exec_typecasts_bind_vals with_example_table do - string = @connection.quote('foo') + string = @connection.quote("foo") @connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})") bind = Relation::QueryAttribute.new("id", "1-fuu", Type::Integer.new) - result = @connection.exec_query('SELECT id, data FROM ex WHERE id = $1', nil, [bind]) + result = @connection.exec_query("SELECT id, data FROM ex WHERE id = $1", nil, [bind]) assert_equal 1, result.rows.length assert_equal 2, result.columns.length - assert_equal [[1, 'foo']], result.rows + assert_equal [[1, "foo"]], result.rows end end end def test_partial_index with_example_table do - @connection.add_index 'ex', %w{ id number }, :name => 'partial', :where => "number > 100" - index = @connection.indexes('ex').find { |idx| idx.name == 'partial' } + @connection.add_index "ex", %w{ id number }, name: "partial", where: "number > 100" + index = @connection.indexes("ex").find { |idx| idx.name == "partial" } assert_equal "(number > 100)", index.where end end def test_expression_index with_example_table do - @connection.add_index 'ex', 'mod(id, 10), abs(number)', name: 'expression' - index = @connection.indexes('ex').find { |idx| idx.name == 'expression' } - assert_equal 'mod(id, 10), abs(number)', index.columns + @connection.add_index "ex", "mod(id, 10), abs(number)", name: "expression" + index = @connection.indexes("ex").find { |idx| idx.name == "expression" } + assert_equal "mod(id, 10), abs(number)", index.columns end end def test_index_with_opclass with_example_table do - @connection.add_index 'ex', 'data varchar_pattern_ops', name: 'with_opclass' - index = @connection.indexes('ex').find { |idx| idx.name == 'with_opclass' } - assert_equal 'data varchar_pattern_ops', index.columns + @connection.add_index "ex", "data varchar_pattern_ops", name: "with_opclass" + index = @connection.indexes("ex").find { |idx| idx.name == "with_opclass" } + assert_equal "data varchar_pattern_ops", index.columns end end @@ -292,8 +286,8 @@ module ActiveRecord def test_columns_for_distinct_with_case assert_equal( - 'posts.id, CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END AS alias_0', - @connection.columns_for_distinct('posts.id', + "posts.id, CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END AS alias_0", + @connection.columns_for_distinct("posts.id", ["CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END"]) ) end @@ -374,7 +368,7 @@ module ActiveRecord def test_unparsed_defaults_are_at_least_set_when_saving with_example_table "id SERIAL PRIMARY KEY, number INTEGER NOT NULL DEFAULT (4 + 4) * 2 / 4" do number_klass = Class.new(ActiveRecord::Base) do - self.table_name = 'ex' + self.table_name = "ex" end column = number_klass.columns_hash["number"] assert_nil column.default @@ -390,13 +384,13 @@ module ActiveRecord private - def with_example_table(definition = 'id serial primary key, number integer, data character varying(255)', &block) - super(@connection, 'ex', definition, &block) - end + def with_example_table(definition = "id serial primary key, number integer, data character varying(255)", &block) + super(@connection, "ex", definition, &block) + end - def connection_without_insert_returning - ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations['arunit'].merge(:insert_returning => false)) - end + def connection_without_insert_returning + ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(insert_returning: false)) + end end end end diff --git a/activerecord/test/cases/adapters/postgresql/prepared_statements_disabled_test.rb b/activerecord/test/cases/adapters/postgresql/prepared_statements_disabled_test.rb new file mode 100644 index 0000000000..8c62690866 --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/prepared_statements_disabled_test.rb @@ -0,0 +1,25 @@ +require "cases/helper" +require "models/computer" +require "models/developer" + +class PreparedStatementsDisabledTest < ActiveRecord::PostgreSQLTestCase + fixtures :developers + + def setup + @conn = ActiveRecord::Base.establish_connection :arunit_without_prepared_statements + end + + def teardown + @conn.release_connection + ActiveRecord::Base.establish_connection :arunit + end + + def test_select_query_works_even_when_prepared_statements_are_disabled + assert_not Developer.connection.prepared_statements + + david = developers(:david) + + assert_equal david, Developer.where(name: "David").last # With Binds + assert_operator Developer.count, :>, 0 # Without Binds + end +end diff --git a/activerecord/test/cases/adapters/postgresql/prepared_statements_test.rb b/activerecord/test/cases/adapters/postgresql/prepared_statements_test.rb deleted file mode 100644 index f1519db48b..0000000000 --- a/activerecord/test/cases/adapters/postgresql/prepared_statements_test.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "cases/helper" -require "models/developer" - -class PreparedStatementsTest < ActiveRecord::PostgreSQLTestCase - fixtures :developers - - def setup - @default_prepared_statements = Developer.connection_config[:prepared_statements] - Developer.connection_config[:prepared_statements] = false - end - - def teardown - Developer.connection_config[:prepared_statements] = @default_prepared_statements - end - - def nothing_raised_with_falsy_prepared_statements - assert_nothing_raised do - Developer.where(id: 1) - end - end - -end diff --git a/activerecord/test/cases/adapters/postgresql/quoting_test.rb b/activerecord/test/cases/adapters/postgresql/quoting_test.rb index 5e6f4dbbb8..141baffa5b 100644 --- a/activerecord/test/cases/adapters/postgresql/quoting_test.rb +++ b/activerecord/test/cases/adapters/postgresql/quoting_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'ipaddr' +require "ipaddr" module ActiveRecord module ConnectionAdapters @@ -10,20 +10,20 @@ module ActiveRecord end def test_type_cast_true - assert_equal 't', @conn.type_cast(true) + assert_equal "t", @conn.type_cast(true) end def test_type_cast_false - assert_equal 'f', @conn.type_cast(false) + assert_equal "f", @conn.type_cast(false) end def test_quote_float_nan - nan = 0.0/0 + nan = 0.0 / 0 assert_equal "'NaN'", @conn.quote(nan) end def test_quote_float_infinity - infinity = 1.0/0 + infinity = 1.0 / 0 assert_equal "'Infinity'", @conn.quote(infinity) end @@ -36,7 +36,7 @@ module ActiveRecord def test_quote_bit_string value = "'); SELECT * FROM users; /*\n01\n*/--" type = OID::Bit.new - assert_equal nil, @conn.quote(type.serialize(value)) + assert_nil @conn.quote(type.serialize(value)) end end end diff --git a/activerecord/test/cases/adapters/postgresql/range_test.rb b/activerecord/test/cases/adapters/postgresql/range_test.rb index 0edfa4ed9d..f411884dfd 100644 --- a/activerecord/test/cases/adapters/postgresql/range_test.rb +++ b/activerecord/test/cases/adapters/postgresql/range_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" if ActiveRecord::Base.connection.respond_to?(:supports_ranges?) && ActiveRecord::Base.connection.supports_ranges? class PostgresqlRange < ActiveRecord::Base @@ -23,7 +23,7 @@ if ActiveRecord::Base.connection.respond_to?(:supports_ranges?) && ActiveRecord: ); _SQL - @connection.create_table('postgresql_ranges') do |t| + @connection.create_table("postgresql_ranges") do |t| t.daterange :date_range t.numrange :num_range t.tsrange :ts_range @@ -32,7 +32,7 @@ _SQL t.int8range :int8_range end - @connection.add_column 'postgresql_ranges', 'float_range', 'floatrange' + @connection.add_column "postgresql_ranges", "float_range", "floatrange" end PostgresqlRange.reset_column_information rescue ActiveRecord::StatementInvalid @@ -93,8 +93,8 @@ _SQL end teardown do - @connection.drop_table 'postgresql_ranges', if_exists: true - @connection.execute 'DROP TYPE IF EXISTS floatrange' + @connection.drop_table "postgresql_ranges", if_exists: true + @connection.execute "DROP TYPE IF EXISTS floatrange" reset_connection end @@ -132,10 +132,10 @@ _SQL end def test_numrange_values - assert_equal BigDecimal.new('0.1')..BigDecimal.new('0.2'), @first_range.num_range - assert_equal BigDecimal.new('0.1')...BigDecimal.new('0.2'), @second_range.num_range - assert_equal BigDecimal.new('0.1')...BigDecimal.new('Infinity'), @third_range.num_range - assert_equal BigDecimal.new('-Infinity')...BigDecimal.new('Infinity'), @fourth_range.num_range + assert_equal BigDecimal.new("0.1")..BigDecimal.new("0.2"), @first_range.num_range + assert_equal BigDecimal.new("0.1")...BigDecimal.new("0.2"), @second_range.num_range + assert_equal BigDecimal.new("0.1")...BigDecimal.new("Infinity"), @third_range.num_range + assert_equal BigDecimal.new("-Infinity")...BigDecimal.new("Infinity"), @fourth_range.num_range assert_nil @empty_range.num_range end @@ -148,8 +148,8 @@ _SQL end def test_tstzrange_values - assert_equal Time.parse('2010-01-01 09:30:00 UTC')..Time.parse('2011-01-01 17:30:00 UTC'), @first_range.tstz_range - assert_equal Time.parse('2010-01-01 09:30:00 UTC')...Time.parse('2011-01-01 17:30:00 UTC'), @second_range.tstz_range + assert_equal Time.parse("2010-01-01 09:30:00 UTC")..Time.parse("2011-01-01 17:30:00 UTC"), @first_range.tstz_range + assert_equal Time.parse("2010-01-01 09:30:00 UTC")...Time.parse("2011-01-01 17:30:00 UTC"), @second_range.tstz_range assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.tstz_range) assert_nil @empty_range.tstz_range end @@ -183,17 +183,17 @@ _SQL end def test_create_tstzrange - tstzrange = Time.parse('2010-01-01 14:30:00 +0100')...Time.parse('2011-02-02 14:30:00 CDT') + tstzrange = Time.parse("2010-01-01 14:30:00 +0100")...Time.parse("2011-02-02 14:30:00 CDT") round_trip(@new_range, :tstz_range, tstzrange) assert_equal @new_range.tstz_range, tstzrange - assert_equal @new_range.tstz_range, Time.parse('2010-01-01 13:30:00 UTC')...Time.parse('2011-02-02 19:30:00 UTC') + assert_equal @new_range.tstz_range, Time.parse("2010-01-01 13:30:00 UTC")...Time.parse("2011-02-02 19:30:00 UTC") end def test_update_tstzrange assert_equal_round_trip(@first_range, :tstz_range, - Time.parse('2010-01-01 14:30:00 CDT')...Time.parse('2011-02-02 14:30:00 CET')) + Time.parse("2010-01-01 14:30:00 CDT")...Time.parse("2011-02-02 14:30:00 CET")) assert_nil_round_trip(@first_range, :tstz_range, - Time.parse('2010-01-01 14:30:00 +0100')...Time.parse('2010-01-01 13:30:00 +0000')) + Time.parse("2010-01-01 14:30:00 +0100")...Time.parse("2010-01-01 13:30:00 +0000")) end def test_create_tsrange @@ -232,14 +232,14 @@ _SQL def test_create_numrange assert_equal_round_trip(@new_range, :num_range, - BigDecimal.new('0.5')...BigDecimal.new('1')) + BigDecimal.new("0.5")...BigDecimal.new("1")) end def test_update_numrange assert_equal_round_trip(@first_range, :num_range, - BigDecimal.new('0.5')...BigDecimal.new('1')) + BigDecimal.new("0.5")...BigDecimal.new("1")) assert_nil_round_trip(@first_range, :num_range, - BigDecimal.new('0.5')...BigDecimal.new('0.5')) + BigDecimal.new("0.5")...BigDecimal.new("0.5")) end def test_create_daterange @@ -282,6 +282,12 @@ _SQL assert_raises(ArgumentError) { PostgresqlRange.create!(tstz_range: "(''2010-01-01 14:30:00+05'', ''2011-01-01 14:30:00-03'']") } end + def test_where_by_attribute_with_range + range = 1..100 + record = PostgresqlRange.create!(int4_range: range) + assert_equal record, PostgresqlRange.where(int4_range: range).take + end + def test_update_all_with_ranges PostgresqlRange.create! diff --git a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb index c895ab9db5..0ff04bfa27 100644 --- a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb @@ -1,5 +1,5 @@ -require 'cases/helper' -require 'support/connection_helper' +require "cases/helper" +require "support/connection_helper" class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase self.use_transactional_tests = false @@ -14,7 +14,7 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase def execute(sql) if IS_REFERENTIAL_INTEGRITY_SQL.call(sql) super "BROKEN;" rescue nil # put transaction in broken state - raise ActiveRecord::StatementInvalid, 'PG::InsufficientPrivilege' + raise ActiveRecord::StatementInvalid, "PG::InsufficientPrivilege" else super end @@ -24,7 +24,7 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase module ProgrammerMistake def execute(sql) if IS_REFERENTIAL_INTEGRITY_SQL.call(sql) - raise ArgumentError, 'something is not right.' + raise ArgumentError, "something is not right." else super end @@ -48,10 +48,10 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase warning = capture(:stderr) do e = assert_raises(ActiveRecord::InvalidForeignKey) do @connection.disable_referential_integrity do - raise ActiveRecord::InvalidForeignKey, 'Should be re-raised' + raise ActiveRecord::InvalidForeignKey, "Should be re-raised" end end - assert_equal 'Should be re-raised', e.message + assert_equal "Should be re-raised", e.message end assert_match (/WARNING: Rails was not able to disable referential integrity/), warning assert_match (/cause: PG::InsufficientPrivilege/), warning @@ -63,10 +63,10 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase warning = capture(:stderr) do e = assert_raises(ActiveRecord::StatementInvalid) do @connection.disable_referential_integrity do - raise ActiveRecord::StatementInvalid, 'Should be re-raised' + raise ActiveRecord::StatementInvalid, "Should be re-raised" end end - assert_equal 'Should be re-raised', e.message + assert_equal "Should be re-raised", e.message end assert warning.blank?, "expected no warnings but got:\n#{warning}" end @@ -105,7 +105,7 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase private - def assert_transaction_is_not_broken - assert_equal 1, @connection.select_value("SELECT 1") - end + def assert_transaction_is_not_broken + assert_equal 1, @connection.select_value("SELECT 1") + end end diff --git a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb index bd64bae308..e9e7f717ac 100644 --- a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb +++ b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb @@ -24,11 +24,11 @@ class PostgresqlRenameTableTest < ActiveRecord::PostgreSQLTestCase private - def num_indices_named(name) - @connection.execute(<<-SQL).values.length - SELECT 1 FROM "pg_index" - JOIN "pg_class" ON "pg_index"."indexrelid" = "pg_class"."oid" - WHERE "pg_class"."relname" = '#{name}' - SQL - end + def num_indices_named(name) + @connection.execute(<<-SQL).values.length + SELECT 1 FROM "pg_index" + JOIN "pg_class" ON "pg_index"."indexrelid" = "pg_class"."oid" + WHERE "pg_class"."relname" = '#{name}' + SQL + end end diff --git a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb index 285a92f60e..f6a07da85f 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb @@ -6,12 +6,12 @@ end class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase self.use_transactional_tests = false - TABLE_NAME = 'schema_things' + TABLE_NAME = "schema_things" COLUMNS = [ - 'id serial primary key', - 'name character varying(50)' + "id serial primary key", + "name character varying(50)" ] - USERS = ['rails_pg_schema_user1', 'rails_pg_schema_user2'] + USERS = ["rails_pg_schema_user1", "rails_pg_schema_user2"] def setup @connection = ActiveRecord::Base.connection @@ -45,7 +45,7 @@ class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase def test_session_auth= assert_raise(ActiveRecord::StatementInvalid) do - @connection.session_auth = 'DEFAULT' + @connection.session_auth = "DEFAULT" @connection.execute "SELECT * FROM #{TABLE_NAME}" end end @@ -68,7 +68,7 @@ class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase USERS.each do |u| @connection.clear_cache! set_session_auth u - assert_equal u, @connection.select_value("SELECT name FROM #{TABLE_NAME} WHERE id = $1", 'SQL', [bind_param(1)]) + assert_equal u, @connection.select_value("SELECT name FROM #{TABLE_NAME} WHERE id = $1", "SQL", [bind_param(1)]) set_session_auth end end @@ -90,9 +90,9 @@ class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase assert_nothing_raised do USERS.each do |u| set_session_auth u - st = SchemaThing.new :name => 'TEST1' + st = SchemaThing.new name: "TEST1" st.save! - st = SchemaThing.new :id => 5, :name => 'TEST2' + st = SchemaThing.new id: 5, name: "TEST2" st.save! set_session_auth end @@ -100,17 +100,17 @@ class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase end def test_tables_in_current_schemas - assert !@connection.tables.include?(TABLE_NAME) + assert_not_includes @connection.tables, TABLE_NAME USERS.each do |u| set_session_auth u - assert @connection.tables.include?(TABLE_NAME) + assert_includes @connection.tables, TABLE_NAME set_session_auth end end private - def set_session_auth auth = nil - @connection.session_auth = auth || 'default' + def set_session_auth(auth = nil) + @connection.session_auth = auth || "default" end def bind_param(value) diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 52ef07f654..237e9ff6a5 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -1,6 +1,6 @@ require "cases/helper" -require 'models/default' -require 'support/schema_dumping_helper' +require "models/default" +require "support/schema_dumping_helper" module PGSchemaHelper def with_schema_search_path(schema_search_path) @@ -17,32 +17,32 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase include PGSchemaHelper self.use_transactional_tests = false - SCHEMA_NAME = 'test_schema' - SCHEMA2_NAME = 'test_schema2' - TABLE_NAME = 'things' - CAPITALIZED_TABLE_NAME = 'Things' - INDEX_A_NAME = 'a_index_things_on_name' - INDEX_B_NAME = 'b_index_things_on_different_columns_in_each_schema' - INDEX_C_NAME = 'c_index_full_text_search' - INDEX_D_NAME = 'd_index_things_on_description_desc' - INDEX_E_NAME = 'e_index_things_on_name_vector' - INDEX_A_COLUMN = 'name' - INDEX_B_COLUMN_S1 = 'email' - INDEX_B_COLUMN_S2 = 'moment' - INDEX_C_COLUMN = %q{(to_tsvector('english', coalesce(things.name, '')))} - INDEX_D_COLUMN = 'description' - INDEX_E_COLUMN = 'name_vector' + SCHEMA_NAME = "test_schema" + SCHEMA2_NAME = "test_schema2" + TABLE_NAME = "things" + CAPITALIZED_TABLE_NAME = "Things" + INDEX_A_NAME = "a_index_things_on_name" + INDEX_B_NAME = "b_index_things_on_different_columns_in_each_schema" + INDEX_C_NAME = "c_index_full_text_search" + INDEX_D_NAME = "d_index_things_on_description_desc" + INDEX_E_NAME = "e_index_things_on_name_vector" + INDEX_A_COLUMN = "name" + INDEX_B_COLUMN_S1 = "email" + INDEX_B_COLUMN_S2 = "moment" + INDEX_C_COLUMN = "(to_tsvector('english', coalesce(things.name, '')))" + INDEX_D_COLUMN = "description" + INDEX_E_COLUMN = "name_vector" COLUMNS = [ - 'id integer', - 'name character varying(50)', - 'email character varying(50)', - 'description character varying(100)', - 'name_vector tsvector', - 'moment timestamp without time zone default now()' + "id integer", + "name character varying(50)", + "email character varying(50)", + "description character varying(100)", + "name_vector tsvector", + "moment timestamp without time zone default now()" ] - PK_TABLE_NAME = 'table_with_pk' - UNMATCHED_SEQUENCE_NAME = 'unmatched_primary_key_default_value_seq' - UNMATCHED_PK_TABLE_NAME = 'table_with_unmatched_sequence_for_pk' + PK_TABLE_NAME = "table_with_pk" + UNMATCHED_SEQUENCE_NAME = "unmatched_primary_key_default_value_seq" + UNMATCHED_PK_TABLE_NAME = "table_with_unmatched_sequence_for_pk" class Thing1 < ActiveRecord::Base self.table_name = "test_schema.things" @@ -61,7 +61,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase end class Thing5 < ActiveRecord::Base - self.table_name = 'things' + self.table_name = "things" end class Song < ActiveRecord::Base @@ -130,7 +130,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase ensure @connection.drop_schema "test_schema3" end - assert !@connection.schema_names.include?("test_schema3") + assert_not_includes @connection.schema_names, "test_schema3" end def test_drop_schema_if_exists @@ -168,21 +168,21 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase def test_raise_wrapped_exception_on_bad_prepare assert_raises(ActiveRecord::StatementInvalid) do - @connection.exec_query "select * from developers where id = ?", 'sql', [bind_param(1)] + @connection.exec_query "select * from developers where id = ?", "sql", [bind_param(1)] end end if ActiveRecord::Base.connection.prepared_statements def test_schema_change_with_prepared_stmt altered = false - @connection.exec_query "select * from developers where id = $1", 'sql', [bind_param(1)] - @connection.exec_query "alter table developers add column zomg int", 'sql', [] + @connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)] + @connection.exec_query "alter table developers add column zomg int", "sql", [] altered = true - @connection.exec_query "select * from developers where id = $1", 'sql', [bind_param(1)] + @connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)] ensure # We are not using DROP COLUMN IF EXISTS because that syntax is only # supported by pg 9.X - @connection.exec_query("alter table developers drop column zomg", 'sql', []) if altered + @connection.exec_query("alter table developers drop column zomg", "sql", []) if altered end end @@ -200,7 +200,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase end def test_data_source_exists_when_not_on_schema_search_path - with_schema_search_path('PUBLIC') do + with_schema_search_path("PUBLIC") do assert(!@connection.data_source_exists?(TABLE_NAME), "data_source exists but should not be found") end end @@ -246,9 +246,9 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase end def test_proper_encoding_of_table_name - assert_equal '"table_name"', @connection.quote_table_name('table_name') + assert_equal '"table_name"', @connection.quote_table_name("table_name") assert_equal '"table.name"', @connection.quote_table_name('"table.name"') - assert_equal '"schema_name"."table_name"', @connection.quote_table_name('schema_name.table_name') + assert_equal '"schema_name"."table_name"', @connection.quote_table_name("schema_name.table_name") assert_equal '"schema_name"."table.name"', @connection.quote_table_name('schema_name."table.name"') assert_equal '"schema.name"."table_name"', @connection.quote_table_name('"schema.name".table_name') assert_equal '"schema.name"."table.name"', @connection.quote_table_name('"schema.name"."table.name"') @@ -260,25 +260,25 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase assert_equal 0, Thing3.count assert_equal 0, Thing4.count - Thing1.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now) + Thing1.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now) assert_equal 1, Thing1.count assert_equal 0, Thing2.count assert_equal 0, Thing3.count assert_equal 0, Thing4.count - Thing2.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now) + Thing2.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now) assert_equal 1, Thing1.count assert_equal 1, Thing2.count assert_equal 0, Thing3.count assert_equal 0, Thing4.count - Thing3.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now) + Thing3.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now) assert_equal 1, Thing1.count assert_equal 1, Thing2.count assert_equal 1, Thing3.count assert_equal 0, Thing4.count - Thing4.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now) + Thing4.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now) assert_equal 1, Thing1.count assert_equal 1, Thing2.count assert_equal 1, Thing3.count @@ -287,7 +287,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase def test_raise_on_unquoted_schema_name assert_raises(ActiveRecord::StatementInvalid) do - with_schema_search_path '$user,public' + with_schema_search_path "$user,public" end end @@ -307,7 +307,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase assert @connection.index_name_exists?(TABLE_NAME, INDEX_D_NAME, true) assert @connection.index_name_exists?(TABLE_NAME, INDEX_E_NAME, true) assert @connection.index_name_exists?(TABLE_NAME, INDEX_E_NAME, true) - assert_not @connection.index_name_exists?(TABLE_NAME, 'missing_index', true) + assert_not @connection.index_name_exists?(TABLE_NAME, "missing_index", true) end end @@ -332,7 +332,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase @connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)" with_schema_search_path SCHEMA_NAME do - assert_nothing_raised { @connection.remove_index "things", name: "things_Index"} + assert_nothing_raised { @connection.remove_index "things", name: "things_Index" } end end @@ -356,13 +356,13 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase %(#{SCHEMA_NAME}."#{PK_TABLE_NAME}"), %(#{SCHEMA_NAME}.#{PK_TABLE_NAME}) ].each do |given| - assert_equal 'id', @connection.primary_key(given), "primary key should be found when table referenced as #{given}" + assert_equal "id", @connection.primary_key(given), "primary key should be found when table referenced as #{given}" end end def test_primary_key_assuming_schema_search_path with_schema_search_path(SCHEMA_NAME) do - assert_equal 'id', @connection.primary_key(PK_TABLE_NAME), "primary key should be found" + assert_equal "id", @connection.primary_key(PK_TABLE_NAME), "primary key should be found" end end @@ -381,19 +381,19 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase %("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}") ].each do |given| pk, seq = @connection.pk_and_sequence_for(given) - assert_equal 'id', pk, "primary key should be found when table referenced as #{given}" + assert_equal "id", pk, "primary key should be found when table referenced as #{given}" assert_equal pg_name.new(SCHEMA_NAME, "#{PK_TABLE_NAME}_id_seq"), seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}") - assert_equal pg_name.new(SCHEMA_NAME, UNMATCHED_SEQUENCE_NAME), seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}") + assert_equal pg_name.new(SCHEMA_NAME, UNMATCHED_SEQUENCE_NAME), seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}") end end def test_current_schema { - %('$user',public) => 'public', + %('$user',public) => "public", SCHEMA_NAME => SCHEMA_NAME, %(#{SCHEMA2_NAME},#{SCHEMA_NAME},public) => SCHEMA2_NAME, - %(public,#{SCHEMA2_NAME},#{SCHEMA_NAME}) => 'public' - }.each do |given,expect| + %(public,#{SCHEMA2_NAME},#{SCHEMA_NAME}) => "public" + }.each do |given, expect| with_schema_search_path(given) { assert_equal expect, @connection.current_schema } end end @@ -401,7 +401,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase def test_prepared_statements_with_multiple_schemas [SCHEMA_NAME, SCHEMA2_NAME].each do |schema_name| with_schema_search_path schema_name do - Thing5.create(:id => 1, :name => "thing inside #{SCHEMA_NAME}", :email => "thing1@localhost", :moment => Time.now) + Thing5.create(id: 1, name: "thing inside #{SCHEMA_NAME}", email: "thing1@localhost", moment: Time.now) end end @@ -414,11 +414,11 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase def test_schema_exists? { - 'public' => true, + "public" => true, SCHEMA_NAME => true, SCHEMA2_NAME => true, - 'darkside' => false - }.each do |given,expect| + "darkside" => false + }.each do |given, expect| assert_equal expect, @connection.schema_exists?(given) end end @@ -442,7 +442,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase private def columns(table_name) @connection.send(:column_definitions, table_name).map do |name, type, default| - "#{name} #{type}" + (default ? " default #{default}" : '') + "#{name} #{type}" + (default ? " default #{default}" : "") end end diff --git a/activerecord/test/cases/adapters/postgresql/serial_test.rb b/activerecord/test/cases/adapters/postgresql/serial_test.rb index 8abe064bf1..d711b3b729 100644 --- a/activerecord/test/cases/adapters/postgresql/serial_test.rb +++ b/activerecord/test/cases/adapters/postgresql/serial_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class PostgresqlSerialTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper diff --git a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb index 5aab246c99..eb9978a898 100644 --- a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb +++ b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require "cases/helper" module ActiveRecord module ConnectionAdapters @@ -17,22 +17,22 @@ module ActiveRecord if Process.respond_to?(:fork) def test_cache_is_per_pid cache = StatementPool.new nil, 10 - cache['foo'] = 'bar' - assert_equal 'bar', cache['foo'] + cache["foo"] = "bar" + assert_equal "bar", cache["foo"] pid = fork { - lookup = cache['foo']; + lookup = cache["foo"]; exit!(!lookup) } Process.waitpid pid - assert $?.success?, 'process should exit successfully' + assert $?.success?, "process should exit successfully" end end def test_dealloc_does_not_raise_on_inactive_connection cache = StatementPool.new InactivePGconn.new, 10 - cache['foo'] = 'bar' + cache["foo"] = "bar" assert_nothing_raised { cache.clear } end end diff --git a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb index 4c4866b46b..962450aada 100644 --- a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb +++ b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb @@ -1,6 +1,6 @@ -require 'cases/helper' -require 'models/developer' -require 'models/topic' +require "cases/helper" +require "models/developer" +require "models/topic" class PostgresqlTimestampTest < ActiveRecord::PostgreSQLTestCase class PostgresqlTimestampWithZone < ActiveRecord::Base; end @@ -21,7 +21,7 @@ class PostgresqlTimestampTest < ActiveRecord::PostgreSQLTestCase @connection.reconnect! timestamp = PostgresqlTimestampWithZone.find(1) - assert_equal Time.utc(2010,1,1, 11,0,0), timestamp.time + assert_equal Time.utc(2010, 1, 1, 11, 0, 0), timestamp.time assert_instance_of Time, timestamp.time end ensure @@ -32,10 +32,10 @@ class PostgresqlTimestampTest < ActiveRecord::PostgreSQLTestCase with_timezone_config default: :local, aware_attributes: false do @connection.reconnect! # make sure to use a non-UTC time zone - @connection.execute("SET time zone 'America/Jamaica'", 'SCHEMA') + @connection.execute("SET time zone 'America/Jamaica'", "SCHEMA") timestamp = PostgresqlTimestampWithZone.find(1) - assert_equal Time.utc(2010,1,1, 11,0,0), timestamp.time + assert_equal Time.utc(2010, 1, 1, 11, 0, 0), timestamp.time assert_instance_of Time, timestamp.time end ensure @@ -54,37 +54,37 @@ class PostgresqlTimestampFixtureTest < ActiveRecord::PostgreSQLTestCase def test_load_infinity_and_beyond d = Developer.find_by_sql("select 'infinity'::timestamp as updated_at") - assert d.first.updated_at.infinite?, 'timestamp should be infinite' + assert d.first.updated_at.infinite?, "timestamp should be infinite" d = Developer.find_by_sql("select '-infinity'::timestamp as updated_at") time = d.first.updated_at - assert time.infinite?, 'timestamp should be infinite' + assert time.infinite?, "timestamp should be infinite" assert_operator time, :<, 0 end def test_save_infinity_and_beyond - d = Developer.create!(:name => 'aaron', :updated_at => 1.0 / 0.0) + d = Developer.create!(name: "aaron", updated_at: 1.0 / 0.0) assert_equal(1.0 / 0.0, d.updated_at) - d = Developer.create!(:name => 'aaron', :updated_at => -1.0 / 0.0) + d = Developer.create!(name: "aaron", updated_at: -1.0 / 0.0) assert_equal(-1.0 / 0.0, d.updated_at) end def test_bc_timestamp date = Date.new(0) - 1.week - Developer.create!(:name => "aaron", :updated_at => date) + Developer.create!(name: "aaron", updated_at: date) assert_equal date, Developer.find_by_name("aaron").updated_at end def test_bc_timestamp_leap_year date = Time.utc(-4, 2, 29) - Developer.create!(:name => "taihou", :updated_at => date) + Developer.create!(name: "taihou", updated_at: date) assert_equal date, Developer.find_by_name("taihou").updated_at end def test_bc_timestamp_year_zero date = Time.utc(0, 4, 7) - Developer.create!(:name => "yahagi", :updated_at => date) + Developer.create!(name: "yahagi", updated_at: date) assert_equal date, Developer.find_by_name("yahagi").updated_at end end diff --git a/activerecord/test/cases/adapters/postgresql/transaction_test.rb b/activerecord/test/cases/adapters/postgresql/transaction_test.rb index e76705a802..9b42d0383d 100644 --- a/activerecord/test/cases/adapters/postgresql/transaction_test.rb +++ b/activerecord/test/cases/adapters/postgresql/transaction_test.rb @@ -1,21 +1,24 @@ require "cases/helper" -require 'support/connection_helper' +require "support/connection_helper" +require "concurrent/atomic/cyclic_barrier" module ActiveRecord class PostgresqlTransactionTest < ActiveRecord::PostgreSQLTestCase self.use_transactional_tests = false class Sample < ActiveRecord::Base - self.table_name = 'samples' + self.table_name = "samples" end setup do + @abort, Thread.abort_on_exception = Thread.abort_on_exception, false + @connection = ActiveRecord::Base.connection @connection.transaction do - @connection.drop_table 'samples', if_exists: true - @connection.create_table('samples') do |t| - t.integer 'value' + @connection.drop_table "samples", if_exists: true + @connection.create_table("samples") do |t| + t.integer "value" end end @@ -23,50 +26,77 @@ module ActiveRecord end teardown do - @connection.drop_table 'samples', if_exists: true - end + @connection.drop_table "samples", if_exists: true - test "raises error when a serialization failure occurs" do - with_warning_suppression do - assert_raises(ActiveRecord::TransactionSerializationError) do - thread = Thread.new do - Sample.transaction isolation: :serializable do - Sample.delete_all + Thread.abort_on_exception = @abort + end - 10.times do |i| - sleep 0.1 + test "raises SerializationFailure when a serialization failure occurs" do + assert_raises(ActiveRecord::SerializationFailure) do + before = Concurrent::CyclicBarrier.new(2) + after = Concurrent::CyclicBarrier.new(2) - Sample.create value: i - end + thread = Thread.new do + with_warning_suppression do + Sample.transaction isolation: :serializable do + before.wait + Sample.create value: Sample.sum(:value) + after.wait end end + end - sleep 0.1 + begin + with_warning_suppression do + Sample.transaction isolation: :serializable do + before.wait + Sample.create value: Sample.sum(:value) + after.wait + end + end + ensure + thread.join + end + end + end - Sample.transaction isolation: :serializable do - Sample.delete_all + test "raises Deadlocked when a deadlock is encountered" do + with_warning_suppression do + assert_raises(ActiveRecord::Deadlocked) do + barrier = Concurrent::CyclicBarrier.new(2) - 10.times do |i| - sleep 0.1 + s1 = Sample.create value: 1 + s2 = Sample.create value: 2 - Sample.create value: i + thread = Thread.new do + Sample.transaction do + s1.lock! + barrier.wait + s2.update_attributes value: 1 end - - sleep 1 end - thread.join + begin + Sample.transaction do + s2.lock! + barrier.wait + s1.update_attributes value: 2 + end + ensure + thread.join + end end end end - protected + private - def with_warning_suppression - log_level = @connection.client_min_messages - @connection.client_min_messages = 'error' - yield - @connection.client_min_messages = log_level - end + def with_warning_suppression + log_level = ActiveRecord::Base.connection.client_min_messages + ActiveRecord::Base.connection.client_min_messages = "error" + yield + ensure + ActiveRecord::Base.connection.client_min_messages = log_level + end end end diff --git a/activerecord/test/cases/adapters/postgresql/type_lookup_test.rb b/activerecord/test/cases/adapters/postgresql/type_lookup_test.rb index ea0f0b8fa5..784d77a8d1 100644 --- a/activerecord/test/cases/adapters/postgresql/type_lookup_test.rb +++ b/activerecord/test/cases/adapters/postgresql/type_lookup_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require "cases/helper" class PostgresqlTypeLookupTest < ActiveRecord::PostgreSQLTestCase setup do @@ -9,8 +9,8 @@ class PostgresqlTypeLookupTest < ActiveRecord::PostgreSQLTestCase box_array = @connection.type_map.lookup(1020) int_array = @connection.type_map.lookup(1007) - assert_equal ';', box_array.delimiter - assert_equal ',', int_array.delimiter + assert_equal ";", box_array.delimiter + assert_equal ",", int_array.delimiter end test "array types correctly respect registration of subtypes" do @@ -19,7 +19,7 @@ class PostgresqlTypeLookupTest < ActiveRecord::PostgreSQLTestCase big_array = [123456789123456789] assert_raises(ActiveModel::RangeError) { int_array.serialize(big_array) } - assert_equal "{123456789123456789}", bigint_array.serialize(big_array) + assert_equal "{123456789123456789}", @connection.type_cast(bigint_array.serialize(big_array)) end test "range types correctly respect registration of subtypes" do diff --git a/activerecord/test/cases/adapters/postgresql/utils_test.rb b/activerecord/test/cases/adapters/postgresql/utils_test.rb index 095c1826e5..9f9e3bda2f 100644 --- a/activerecord/test/cases/adapters/postgresql/utils_test.rb +++ b/activerecord/test/cases/adapters/postgresql/utils_test.rb @@ -1,5 +1,5 @@ -require 'cases/helper' -require 'active_record/connection_adapters/postgresql/utils' +require "cases/helper" +require "active_record/connection_adapters/postgresql/utils" class PostgreSQLUtilsTest < ActiveRecord::PostgreSQLTestCase Name = ActiveRecord::ConnectionAdapters::PostgreSQL::Name @@ -7,14 +7,14 @@ class PostgreSQLUtilsTest < ActiveRecord::PostgreSQLTestCase def test_extract_schema_qualified_name { - %(table_name) => [nil,'table_name'], - %("table.name") => [nil,'table.name'], + %(table_name) => [nil, "table_name"], + %("table.name") => [nil, "table.name"], %(schema.table_name) => %w{schema table_name}, %("schema".table_name) => %w{schema table_name}, %(schema."table_name") => %w{schema table_name}, %("schema"."table_name") => %w{schema table_name}, - %("even spaces".table) => ['even spaces','table'], - %(schema."table.name") => ['schema', 'table.name'] + %("even spaces".table) => ["even spaces", "table"], + %(schema."table.name") => ["schema", "table.name"] }.each do |given, expect| assert_equal Name.new(*expect), extract_schema_qualified_name(given) end @@ -54,9 +54,9 @@ class PostgreSQLNameTest < ActiveRecord::PostgreSQLTestCase end test "can be used as hash key" do - hash = {Name.new("schema", "article_seq") => "success"} + hash = { Name.new("schema", "article_seq") => "success" } assert_equal "success", hash[Name.new("schema", "article_seq")] - assert_equal nil, hash[Name.new("schema", "articles")] - assert_equal nil, hash[Name.new("public", "article_seq")] + assert_nil hash[Name.new("schema", "articles")] + assert_nil hash[Name.new("public", "article_seq")] end end diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index 7628075ad2..f34d50e25c 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" module PostgresqlUUIDHelper def connection @@ -9,6 +9,10 @@ module PostgresqlUUIDHelper def drop_table(name) connection.drop_table name, if_exists: true end + + def uuid_function + connection.supports_pgcrypto_uuid? ? "gen_random_uuid()" : "uuid_generate_v4()" + end end class PostgresqlUUIDTest < ActiveRecord::PostgreSQLTestCase @@ -20,10 +24,11 @@ class PostgresqlUUIDTest < ActiveRecord::PostgreSQLTestCase end setup do - enable_extension!('uuid-ossp', connection) + enable_extension!("uuid-ossp", connection) + enable_extension!("pgcrypto", connection) if connection.supports_pgcrypto_uuid? connection.create_table "uuid_data_type" do |t| - t.uuid 'guid' + t.uuid "guid" end end @@ -31,16 +36,24 @@ class PostgresqlUUIDTest < ActiveRecord::PostgreSQLTestCase drop_table "uuid_data_type" end + if ActiveRecord::Base.connection.supports_pgcrypto_uuid? + def test_uuid_column_default + connection.add_column :uuid_data_type, :thingy, :uuid, null: false, default: "gen_random_uuid()" + UUIDType.reset_column_information + column = UUIDType.columns_hash["thingy"] + assert_equal "gen_random_uuid()", column.default_function + end + end + def test_change_column_default - @connection.add_column :uuid_data_type, :thingy, :uuid, null: false, default: "uuid_generate_v1()" + connection.add_column :uuid_data_type, :thingy, :uuid, null: false, default: "uuid_generate_v1()" UUIDType.reset_column_information - column = UUIDType.columns_hash['thingy'] + column = UUIDType.columns_hash["thingy"] assert_equal "uuid_generate_v1()", column.default_function - @connection.change_column :uuid_data_type, :thingy, :uuid, null: false, default: "uuid_generate_v4()" - + connection.change_column :uuid_data_type, :thingy, :uuid, null: false, default: "uuid_generate_v4()" UUIDType.reset_column_information - column = UUIDType.columns_hash['thingy'] + column = UUIDType.columns_hash["thingy"] assert_equal "uuid_generate_v4()", column.default_function ensure UUIDType.reset_column_information @@ -57,46 +70,46 @@ class PostgresqlUUIDTest < ActiveRecord::PostgreSQLTestCase end def test_treat_blank_uuid_as_nil - UUIDType.create! guid: '' - assert_equal(nil, UUIDType.last.guid) + UUIDType.create! guid: "" + assert_nil(UUIDType.last.guid) end def test_treat_invalid_uuid_as_nil - uuid = UUIDType.create! guid: 'foobar' - assert_equal(nil, uuid.guid) + uuid = UUIDType.create! guid: "foobar" + assert_nil(uuid.guid) end def test_invalid_uuid_dont_modify_before_type_cast - uuid = UUIDType.new guid: 'foobar' - assert_equal 'foobar', uuid.guid_before_type_cast + uuid = UUIDType.new guid: "foobar" + assert_equal "foobar", uuid.guid_before_type_cast end def test_acceptable_uuid_regex # Valid uuids - ['A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11', - '{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}', - 'a0eebc999c0b4ef8bb6d6bb9bd380a11', - 'a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11', - '{a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11}', + ["A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11", + "{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}", + "a0eebc999c0b4ef8bb6d6bb9bd380a11", + "a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11", + "{a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11}", # The following is not a valid RFC 4122 UUID, but PG doesn't seem to care, # so we shouldn't block it either. (Pay attention to "fb6d" – the "f" here # is invalid – it must be one of 8, 9, A, B, a, b according to the spec.) - '{a0eebc99-9c0b-4ef8-fb6d-6bb9bd380a11}', + "{a0eebc99-9c0b-4ef8-fb6d-6bb9bd380a11}", ].each do |valid_uuid| uuid = UUIDType.new guid: valid_uuid assert_not_nil uuid.guid end # Invalid uuids - [['A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'], + [["A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"], Hash.new, 0, 0.0, true, - 'Z0000C99-9C0B-4EF8-BB6D-6BB9BD380A11', - 'a0eebc999r0b4ef8ab6d6bb9bd380a11', - 'a0ee-bc99------4ef8-bb6d-6bb9-bd38-0a11', - '{a0eebc99-bb6d6bb9-bd380a11}'].each do |invalid_uuid| + "Z0000C99-9C0B-4EF8-BB6D-6BB9BD380A11", + "a0eebc999r0b4ef8ab6d6bb9bd380a11", + "a0ee-bc99------4ef8-bb6d-6bb9-bd38-0a11", + "{a0eebc99-bb6d6bb9-bd380a11}"].each do |invalid_uuid| uuid = UUIDType.new guid: invalid_uuid assert_nil uuid.guid end @@ -142,39 +155,44 @@ class PostgresqlUUIDGenerationTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper class UUID < ActiveRecord::Base - self.table_name = 'pg_uuids' + self.table_name = "pg_uuids" end setup do - connection.create_table('pg_uuids', id: :uuid, default: 'uuid_generate_v1()') do |t| - t.string 'name' - t.uuid 'other_uuid', default: 'uuid_generate_v4()' + connection.create_table("pg_uuids", id: :uuid, default: "uuid_generate_v1()") do |t| + t.string "name" + t.uuid "other_uuid", default: "uuid_generate_v4()" end # Create custom PostgreSQL function to generate UUIDs # to test dumping tables which columns have defaults with custom functions connection.execute <<-SQL CREATE OR REPLACE FUNCTION my_uuid_generator() RETURNS uuid - AS $$ SELECT * FROM uuid_generate_v4() $$ + AS $$ SELECT * FROM #{uuid_function} $$ LANGUAGE SQL VOLATILE; SQL # Create such a table with custom function as default value generator - connection.create_table('pg_uuids_2', id: :uuid, default: 'my_uuid_generator()') do |t| - t.string 'name' - t.uuid 'other_uuid_2', default: 'my_uuid_generator()' + connection.create_table("pg_uuids_2", id: :uuid, default: "my_uuid_generator()") do |t| + t.string "name" + t.uuid "other_uuid_2", default: "my_uuid_generator()" + end + + connection.create_table("pg_uuids_3", id: :uuid) do |t| + t.string "name" end end teardown do drop_table "pg_uuids" - drop_table 'pg_uuids_2' - connection.execute 'DROP FUNCTION IF EXISTS my_uuid_generator();' + drop_table "pg_uuids_2" + drop_table "pg_uuids_3" + connection.execute "DROP FUNCTION IF EXISTS my_uuid_generator();" end if ActiveRecord::Base.connection.supports_extensions? def test_id_is_uuid - assert_equal :uuid, UUID.columns_hash['id'].type + assert_equal :uuid, UUID.columns_hash["id"].type assert UUID.primary_key end @@ -190,21 +208,51 @@ class PostgresqlUUIDGenerationTest < ActiveRecord::PostgreSQLTestCase end def test_pk_and_sequence_for_uuid_primary_key - pk, seq = connection.pk_and_sequence_for('pg_uuids') - assert_equal 'id', pk - assert_equal nil, seq + pk, seq = connection.pk_and_sequence_for("pg_uuids") + assert_equal "id", pk + assert_nil seq end def test_schema_dumper_for_uuid_primary_key schema = dump_table_schema "pg_uuids" assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: -> { "uuid_generate_v1\(\)" }/, schema) - assert_match(/t\.uuid "other_uuid", default: -> { "uuid_generate_v4\(\)" }/, schema) + assert_match(/t\.uuid "other_uuid", default: -> { "uuid_generate_v4\(\)" }/, schema) end def test_schema_dumper_for_uuid_primary_key_with_custom_default schema = dump_table_schema "pg_uuids_2" assert_match(/\bcreate_table "pg_uuids_2", id: :uuid, default: -> { "my_uuid_generator\(\)" }/, schema) - assert_match(/t\.uuid "other_uuid_2", default: -> { "my_uuid_generator\(\)" }/, schema) + assert_match(/t\.uuid "other_uuid_2", default: -> { "my_uuid_generator\(\)" }/, schema) + end + + def test_schema_dumper_for_uuid_primary_key_default + schema = dump_table_schema "pg_uuids_3" + if connection.supports_pgcrypto_uuid? + assert_match(/\bcreate_table "pg_uuids_3", id: :uuid, default: -> { "gen_random_uuid\(\)" }/, schema) + else + assert_match(/\bcreate_table "pg_uuids_3", id: :uuid, default: -> { "uuid_generate_v4\(\)" }/, schema) + end + end + + if ActiveRecord::Base.connection.supports_pgcrypto_uuid? + def test_schema_dumper_for_uuid_primary_key_default_in_legacy_migration + @verbose_was = ActiveRecord::Migration.verbose + ActiveRecord::Migration.verbose = false + + migration = Class.new(ActiveRecord::Migration[4.2]) do + def version; 101 end + def migrate(x) + create_table("pg_uuids_4", id: :uuid) + end + end.new + ActiveRecord::Migrator.new(:up, [migration]).migrate + + schema = dump_table_schema "pg_uuids_4" + assert_match(/\bcreate_table "pg_uuids_4", id: :uuid, default: -> { "uuid_generate_v4\(\)" }/, schema) + ensure + drop_table "pg_uuids_4" + ActiveRecord::Migration.verbose = @verbose_was + end end end end @@ -214,9 +262,9 @@ class PostgresqlUUIDTestNilDefault < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper setup do - connection.create_table('pg_uuids', id: false) do |t| + connection.create_table("pg_uuids", id: false) do |t| t.primary_key :id, :uuid, default: nil - t.string 'name' + t.string "name" end end @@ -244,30 +292,30 @@ class PostgresqlUUIDTestInverseOf < ActiveRecord::PostgreSQLTestCase include PostgresqlUUIDHelper class UuidPost < ActiveRecord::Base - self.table_name = 'pg_uuid_posts' + self.table_name = "pg_uuid_posts" has_many :uuid_comments, inverse_of: :uuid_post end class UuidComment < ActiveRecord::Base - self.table_name = 'pg_uuid_comments' + self.table_name = "pg_uuid_comments" belongs_to :uuid_post end setup do connection.transaction do - connection.create_table('pg_uuid_posts', id: :uuid) do |t| - t.string 'title' + connection.create_table("pg_uuid_posts", id: :uuid) do |t| + t.string "title" end - connection.create_table('pg_uuid_comments', id: :uuid) do |t| + connection.create_table("pg_uuid_comments", id: :uuid) do |t| t.references :uuid_post, type: :uuid - t.string 'content' + t.string "content" end end end teardown do - drop_table "pg_uuid_comments" - drop_table "pg_uuid_posts" + drop_table "pg_uuid_comments" + drop_table "pg_uuid_posts" end if ActiveRecord::Base.connection.supports_extensions? @@ -290,5 +338,4 @@ class PostgresqlUUIDTestInverseOf < ActiveRecord::PostgreSQLTestCase assert_nil UuidPost.find_by(id: 789) end end - end diff --git a/activerecord/test/cases/adapters/postgresql/xml_test.rb b/activerecord/test/cases/adapters/postgresql/xml_test.rb index add32699fa..826b384fb3 100644 --- a/activerecord/test/cases/adapters/postgresql/xml_test.rb +++ b/activerecord/test/cases/adapters/postgresql/xml_test.rb @@ -1,28 +1,28 @@ -require 'cases/helper' -require 'support/schema_dumping_helper' +require "cases/helper" +require "support/schema_dumping_helper" class PostgresqlXMLTest < ActiveRecord::PostgreSQLTestCase include SchemaDumpingHelper class XmlDataType < ActiveRecord::Base - self.table_name = 'xml_data_type' + self.table_name = "xml_data_type" end def setup @connection = ActiveRecord::Base.connection begin @connection.transaction do - @connection.create_table('xml_data_type') do |t| - t.xml 'payload' + @connection.create_table("xml_data_type") do |t| + t.xml "payload" end end rescue ActiveRecord::StatementInvalid skip "do not test on PG without xml" end - @column = XmlDataType.columns_hash['payload'] + @column = XmlDataType.columns_hash["payload"] end teardown do - @connection.drop_table 'xml_data_type', if_exists: true + @connection.drop_table "xml_data_type", if_exists: true end def test_column @@ -30,7 +30,7 @@ class PostgresqlXMLTest < ActiveRecord::PostgreSQLTestCase end def test_null_xml - @connection.execute %q|insert into xml_data_type (payload) VALUES(null)| + @connection.execute "insert into xml_data_type (payload) VALUES(null)" assert_nil XmlDataType.first.payload end diff --git a/activerecord/test/cases/adapters/sqlite3/collation_test.rb b/activerecord/test/cases/adapters/sqlite3/collation_test.rb index 58a9469ce5..28e8f12c18 100644 --- a/activerecord/test/cases/adapters/sqlite3/collation_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/collation_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'support/schema_dumping_helper' +require "support/schema_dumping_helper" class SQLite3CollationTest < ActiveRecord::SQLite3TestCase include SchemaDumpingHelper @@ -7,8 +7,8 @@ class SQLite3CollationTest < ActiveRecord::SQLite3TestCase def setup @connection = ActiveRecord::Base.connection @connection.create_table :collation_table_sqlite3, force: true do |t| - t.string :string_nocase, collation: 'NOCASE' - t.text :text_rtrim, collation: 'RTRIM' + t.string :string_nocase, collation: "NOCASE" + t.text :text_rtrim, collation: "RTRIM" end end @@ -17,32 +17,32 @@ class SQLite3CollationTest < ActiveRecord::SQLite3TestCase end test "string column with collation" do - column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == 'string_nocase' } + column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == "string_nocase" } assert_equal :string, column.type - assert_equal 'NOCASE', column.collation + assert_equal "NOCASE", column.collation end test "text column with collation" do - column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == 'text_rtrim' } + column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == "text_rtrim" } assert_equal :text, column.type - assert_equal 'RTRIM', column.collation + assert_equal "RTRIM", column.collation end test "add column with collation" do - @connection.add_column :collation_table_sqlite3, :title, :string, collation: 'RTRIM' + @connection.add_column :collation_table_sqlite3, :title, :string, collation: "RTRIM" - column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == 'title' } + column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == "title" } assert_equal :string, column.type - assert_equal 'RTRIM', column.collation + assert_equal "RTRIM", column.collation end test "change column with collation" do @connection.add_column :collation_table_sqlite3, :description, :string - @connection.change_column :collation_table_sqlite3, :description, :text, collation: 'RTRIM' + @connection.change_column :collation_table_sqlite3, :description, :text, collation: "RTRIM" - column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == 'description' } + column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == "description" } assert_equal :text, column.type - assert_equal 'RTRIM', column.collation + assert_equal "RTRIM", column.collation end test "schema dump includes collation" do diff --git a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb index 34e3b2e023..91967c1e33 100644 --- a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb @@ -10,8 +10,8 @@ class CopyTableTest < ActiveRecord::SQLite3TestCase end end - def test_copy_table(from = 'customers', to = 'customers2', options = {}) - assert_nothing_raised {copy_table(from, to, options)} + def test_copy_table(from = "customers", to = "customers2", options = {}) + assert_nothing_raised { copy_table(from, to, options) } assert_equal row_count(from), row_count(to) if block_given? @@ -24,39 +24,39 @@ class CopyTableTest < ActiveRecord::SQLite3TestCase end def test_copy_table_renaming_column - test_copy_table('customers', 'customers2', - :rename => {'name' => 'person_name'}) do |from, to, options| - expected = column_values(from, 'name') - assert_equal expected, column_values(to, 'person_name') + test_copy_table("customers", "customers2", + rename: { "name" => "person_name" }) do |from, to, options| + expected = column_values(from, "name") + assert_equal expected, column_values(to, "person_name") assert expected.any?, "No values in table: #{expected.inspect}" end end def test_copy_table_allows_to_pass_options_to_create_table - @connection.create_table('blocker_table') - test_copy_table('customers', 'blocker_table', force: true) + @connection.create_table("blocker_table") + test_copy_table("customers", "blocker_table", force: true) end def test_copy_table_with_index - test_copy_table('comments', 'comments_with_index') do - @connection.add_index('comments_with_index', ['post_id', 'type']) - test_copy_table('comments_with_index', 'comments_with_index2') do - assert_equal table_indexes_without_name('comments_with_index'), - table_indexes_without_name('comments_with_index2') + test_copy_table("comments", "comments_with_index") do + @connection.add_index("comments_with_index", ["post_id", "type"]) + test_copy_table("comments_with_index", "comments_with_index2") do + assert_equal table_indexes_without_name("comments_with_index"), + table_indexes_without_name("comments_with_index2") end end end def test_copy_table_without_primary_key - test_copy_table('developers_projects', 'programmers_projects') do - assert_nil @connection.primary_key('programmers_projects') + test_copy_table("developers_projects", "programmers_projects") do + assert_nil @connection.primary_key("programmers_projects") end end def test_copy_table_with_id_col_that_is_not_primary_key - test_copy_table('goofy_string_id', 'goofy_string_id2') do - original_id = @connection.columns('goofy_string_id').detect{|col| col.name == 'id' } - copied_id = @connection.columns('goofy_string_id2').detect{|col| col.name == 'id' } + test_copy_table("goofy_string_id", "goofy_string_id2") do + original_id = @connection.columns("goofy_string_id").detect { |col| col.name == "id" } + copied_id = @connection.columns("goofy_string_id2").detect { |col| col.name == "id" } assert_equal original_id.type, copied_id.type assert_equal original_id.sql_type, copied_id.sql_type assert_equal original_id.limit, copied_id.limit @@ -64,28 +64,28 @@ class CopyTableTest < ActiveRecord::SQLite3TestCase end def test_copy_table_with_unconventional_primary_key - test_copy_table('owners', 'owners_unconventional') do - original_pk = @connection.primary_key('owners') - copied_pk = @connection.primary_key('owners_unconventional') + test_copy_table("owners", "owners_unconventional") do + original_pk = @connection.primary_key("owners") + copied_pk = @connection.primary_key("owners_unconventional") assert_equal original_pk, copied_pk end end def test_copy_table_with_binary_column - test_copy_table 'binaries', 'binaries2' + test_copy_table "binaries", "binaries2" end -protected +private def copy_table(from, to, options = {}) - @connection.copy_table(from, to, {:temporary => true}.merge(options)) + @connection.copy_table(from, to, { temporary: true }.merge(options)) end def column_names(table) - @connection.table_structure(table).map {|column| column['name']} + @connection.table_structure(table).map { |column| column["name"] } end def column_values(table, column) - @connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map {|row| row[column]} + @connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map { |row| row[column] } end def table_indexes_without_name(table) @@ -93,6 +93,6 @@ protected end def row_count(table) - @connection.select_one("SELECT COUNT(*) AS count FROM #{table}")['count'] + @connection.select_one("SELECT COUNT(*) AS count FROM #{table}")["count"] end end diff --git a/activerecord/test/cases/adapters/sqlite3/explain_test.rb b/activerecord/test/cases/adapters/sqlite3/explain_test.rb index a1a6e5f16a..128acb79cf 100644 --- a/activerecord/test/cases/adapters/sqlite3/explain_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/explain_test.rb @@ -1,19 +1,19 @@ require "cases/helper" -require 'models/developer' -require 'models/computer' +require "models/developer" +require "models/computer" class SQLite3ExplainTest < ActiveRecord::SQLite3TestCase fixtures :developers def test_explain_for_one_query explain = Developer.where(id: 1).explain - assert_match %r(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = (?:\?|1)), explain + assert_match %r(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = (?:\? \[\["id", 1\]\]|1)), explain assert_match(/(SEARCH )?TABLE developers USING (INTEGER )?PRIMARY KEY/, explain) end def test_explain_with_eager_loading explain = Developer.where(id: 1).includes(:audit_logs).explain - assert_match %r(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = (?:\?|1)), explain + assert_match %r(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = (?:\? \[\["id", 1\]\]|1)), explain assert_match(/(SEARCH )?TABLE developers USING (INTEGER )?PRIMARY KEY/, explain) assert_match %(EXPLAIN for: SELECT "audit_logs".* FROM "audit_logs" WHERE "audit_logs"."developer_id" = 1), explain assert_match(/(SCAN )?TABLE audit_logs/, explain) diff --git a/activerecord/test/cases/adapters/sqlite3/legacy_migration_test.rb b/activerecord/test/cases/adapters/sqlite3/legacy_migration_test.rb new file mode 100644 index 0000000000..fcca8d66b5 --- /dev/null +++ b/activerecord/test/cases/adapters/sqlite3/legacy_migration_test.rb @@ -0,0 +1,59 @@ +require "cases/helper" + +class SqliteLegacyMigrationTest < ActiveRecord::SQLite3TestCase + self.use_transactional_tests = false + + class GenerateTableWithoutBigint < ActiveRecord::Migration[5.0] + def change + create_table :legacy_integer_pk do |table| + table.string :foo + end + + create_table :override_pk, id: :bigint do |table| + table.string :bar + end + end + end + + def setup + super + @connection = ActiveRecord::Base.connection + + @migration_verbose_old = ActiveRecord::Migration.verbose + ActiveRecord::Migration.verbose = false + + migrations = [GenerateTableWithoutBigint.new(nil, 1)] + + ActiveRecord::Migrator.new(:up, migrations).migrate + end + + def teardown + ActiveRecord::Migration.verbose = @migration_verbose_old + @connection.drop_table("legacy_integer_pk") + @connection.drop_table("override_pk") + ActiveRecord::SchemaMigration.delete_all rescue nil + super + end + + def test_create_table_uses_integer_as_pkey_by_default + col = column(:legacy_integer_pk, :id) + assert_equal "INTEGER", sql_type_for(col) + assert primary_key?(:legacy_integer_pk, "id"), "id is not primary key" + end + + private + + def column(table_name, column_name) + ActiveRecord::Base.connection + .columns(table_name.to_s) + .detect { |c| c.name == column_name.to_s } + end + + def sql_type_for(col) + col && col.sql_type + end + + def primary_key?(table_name, column) + ActiveRecord::Base.connection.execute("PRAGMA table_info(#{table_name})").find { |col| col["name"] == column }["pk"] == 1 + end +end diff --git a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb index fe2425b845..9750840051 100644 --- a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb @@ -1,7 +1,7 @@ require "cases/helper" -require 'bigdecimal' -require 'yaml' -require 'securerandom' +require "bigdecimal" +require "yaml" +require "securerandom" class SQLite3QuotingTest < ActiveRecord::SQLite3TestCase def setup @@ -16,7 +16,7 @@ class SQLite3QuotingTest < ActiveRecord::SQLite3TestCase end def test_type_cast_symbol - assert_equal 'foo', @conn.type_cast(:foo) + assert_equal "foo", @conn.type_cast(:foo) end def test_type_cast_date @@ -37,19 +37,19 @@ class SQLite3QuotingTest < ActiveRecord::SQLite3TestCase end def test_type_cast_nil - assert_equal nil, @conn.type_cast(nil) + assert_nil @conn.type_cast(nil) end def test_type_cast_true - assert_equal 't', @conn.type_cast(true) + assert_equal "t", @conn.type_cast(true) end def test_type_cast_false - assert_equal 'f', @conn.type_cast(false) + assert_equal "f", @conn.type_cast(false) end def test_type_cast_bigdecimal - bd = BigDecimal.new '10.0' + bd = BigDecimal.new "10.0" assert_equal bd.to_f, @conn.type_cast(bd) end @@ -79,7 +79,7 @@ class SQLite3QuotingTest < ActiveRecord::SQLite3TestCase end def test_quoting_binary_strings - value = "hello".encode('ascii-8bit') + value = "hello".encode("ascii-8bit") type = ActiveRecord::Type::String.new assert_equal "'hello'", @conn.quote(type.serialize(value)) diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index bbc9f978bf..a6109348cc 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -1,7 +1,7 @@ require "cases/helper" -require 'models/owner' -require 'tempfile' -require 'support/ddl_helper' +require "models/owner" +require "tempfile" +require "support/ddl_helper" module ActiveRecord module ConnectionAdapters @@ -14,22 +14,22 @@ module ActiveRecord end def setup - @conn = Base.sqlite3_connection database: ':memory:', - adapter: 'sqlite3', + @conn = Base.sqlite3_connection database: ":memory:", + adapter: "sqlite3", timeout: 100 end def test_bad_connection assert_raise ActiveRecord::NoDatabaseError do connection = ActiveRecord::Base.sqlite3_connection(adapter: "sqlite3", database: "/tmp/should/_not/_exist/-cinco-dog.db") - connection.drop_table 'ex', if_exists: true + connection.drop_table "ex", if_exists: true end end unless in_memory_db? def test_connect_with_url original_connection = ActiveRecord::Base.remove_connection - tf = Tempfile.open 'whatever' + tf = Tempfile.open "whatever" url = "sqlite3:#{tf.path}" ActiveRecord::Base.establish_connection(url) assert ActiveRecord::Base.connection @@ -51,7 +51,7 @@ module ActiveRecord def test_valid_column with_example_table do - column = @conn.columns('ex').find { |col| col.name == 'id' } + column = @conn.columns("ex").find { |col| col.name == "id" } assert @conn.valid_type?(column.type) end end @@ -66,9 +66,9 @@ module ActiveRecord end def test_column_types - owner = Owner.create!(name: "hello".encode('ascii-8bit')) + owner = Owner.create!(name: "hello".encode("ascii-8bit")) owner.reload - select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ', ' + select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ", " result = Owner.connection.exec_query <<-esql SELECT #{select} FROM #{Owner.table_name} @@ -83,10 +83,10 @@ module ActiveRecord def test_exec_insert with_example_table do vals = [Relation::QueryAttribute.new("number", 10, Type::Value.new)] - @conn.exec_insert('insert into ex (number) VALUES (?)', 'SQL', vals) + @conn.exec_insert("insert into ex (number) VALUES (?)", "SQL", vals) result = @conn.exec_query( - 'select number from ex where number = ?', 'SQL', vals) + "select number from ex where number = ?", "SQL", vals) assert_equal 1, result.rows.length assert_equal 10, result.rows.first.first @@ -94,8 +94,8 @@ module ActiveRecord end def test_primary_key_returns_nil_for_no_pk - with_example_table 'id int, data string' do - assert_nil @conn.primary_key('ex') + with_example_table "id int, data string" do + assert_nil @conn.primary_key("ex") end end @@ -107,69 +107,69 @@ module ActiveRecord def test_bad_timeout assert_raises(TypeError) do - Base.sqlite3_connection database: ':memory:', - adapter: 'sqlite3', - timeout: 'usa' + Base.sqlite3_connection database: ":memory:", + adapter: "sqlite3", + timeout: "usa" end end # connection is OK with a nil timeout def test_nil_timeout - conn = Base.sqlite3_connection database: ':memory:', - adapter: 'sqlite3', + conn = Base.sqlite3_connection database: ":memory:", + adapter: "sqlite3", timeout: nil - assert conn, 'made a connection' + assert conn, "made a connection" end def test_connect - assert @conn, 'should have connection' + assert @conn, "should have connection" end # sqlite3 defaults to UTF-8 encoding def test_encoding - assert_equal 'UTF-8', @conn.encoding + assert_equal "UTF-8", @conn.encoding end def test_exec_no_binds - with_example_table 'id int, data string' do - result = @conn.exec_query('SELECT id, data FROM ex') + with_example_table "id int, data string" do + result = @conn.exec_query("SELECT id, data FROM ex") assert_equal 0, result.rows.length assert_equal 2, result.columns.length assert_equal %w{ id data }, result.columns @conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")') - result = @conn.exec_query('SELECT id, data FROM ex') + result = @conn.exec_query("SELECT id, data FROM ex") assert_equal 1, result.rows.length assert_equal 2, result.columns.length - assert_equal [[1, 'foo']], result.rows + assert_equal [[1, "foo"]], result.rows end end def test_exec_query_with_binds - with_example_table 'id int, data string' do + with_example_table "id int, data string" do @conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")') result = @conn.exec_query( - 'SELECT id, data FROM ex WHERE id = ?', nil, [Relation::QueryAttribute.new(nil, 1, Type::Value.new)]) + "SELECT id, data FROM ex WHERE id = ?", nil, [Relation::QueryAttribute.new(nil, 1, Type::Value.new)]) assert_equal 1, result.rows.length assert_equal 2, result.columns.length - assert_equal [[1, 'foo']], result.rows + assert_equal [[1, "foo"]], result.rows end end def test_exec_query_typecasts_bind_vals - with_example_table 'id int, data string' do + with_example_table "id int, data string" do @conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")') result = @conn.exec_query( - 'SELECT id, data FROM ex WHERE id = ?', nil, [Relation::QueryAttribute.new("id", "1-fuu", Type::Integer.new)]) + "SELECT id, data FROM ex WHERE id = ?", nil, [Relation::QueryAttribute.new("id", "1-fuu", Type::Integer.new)]) assert_equal 1, result.rows.length assert_equal 2, result.columns.length - assert_equal [[1, 'foo']], result.rows + assert_equal [[1, "foo"]], result.rows end end @@ -182,15 +182,15 @@ module ActiveRecord ) eosql str = "\x80".force_encoding("ASCII-8BIT") - binary = DualEncoding.new name: 'いただきます!', data: str + binary = DualEncoding.new name: "いただきます!", data: str binary.save! assert_equal str, binary.data ensure - DualEncoding.connection.drop_table 'dual_encodings', if_exists: true + DualEncoding.connection.drop_table "dual_encodings", if_exists: true end def test_type_cast_should_not_mutate_encoding - name = 'hello'.force_encoding(Encoding::ASCII_8BIT) + name = "hello".force_encoding(Encoding::ASCII_8BIT) Owner.create(name: name) assert_equal Encoding::ASCII_8BIT, name.encoding ensure @@ -204,8 +204,8 @@ module ActiveRecord assert_equal 1, records.length record = records.first - assert_equal 10, record['number'] - assert_equal 1, record['id'] + assert_equal 10, record["number"] + assert_equal 1, record["id"] end end @@ -226,7 +226,7 @@ module ActiveRecord def test_insert_id_value_returned with_example_table do sql = "INSERT INTO ex (number) VALUES (10)" - idval = 'vuvuzela' + idval = "vuvuzela" id = @conn.insert(sql, nil, nil, idval) assert_equal idval, id end @@ -237,7 +237,7 @@ module ActiveRecord 2.times do |i| @conn.create "INSERT INTO ex (number) VALUES (#{i})" end - rows = @conn.select_rows 'select number, id from ex' + rows = @conn.select_rows "select number, id from ex" assert_equal [[0, 1], [1, 2]], rows end end @@ -254,7 +254,7 @@ module ActiveRecord def test_transaction with_example_table do - count_sql = 'select count(*) from ex' + count_sql = "select count(*) from ex" @conn.begin_db_transaction @conn.create "INSERT INTO ex (number) VALUES (10)" @@ -267,9 +267,9 @@ module ActiveRecord def test_tables with_example_table do - ActiveSupport::Deprecation.silence { assert_equal %w{ ex }, @conn.tables } - with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer', 'people' do - ActiveSupport::Deprecation.silence { assert_equal %w{ ex people }.sort, @conn.tables.sort } + assert_equal %w{ ex }, @conn.tables + with_example_table "id integer PRIMARY KEY AUTOINCREMENT, number integer", "people" do + assert_equal %w{ ex people }.sort, @conn.tables.sort end end end @@ -277,19 +277,17 @@ module ActiveRecord def test_tables_logs_name sql = <<-SQL SELECT name FROM sqlite_master - WHERE type IN ('table','view') AND name <> 'sqlite_sequence' + WHERE type = 'table' AND name <> 'sqlite_sequence' SQL - assert_logged [[sql.squish, 'SCHEMA', []]] do - ActiveSupport::Deprecation.silence do - @conn.tables('hello') - end + assert_logged [[sql.squish, "SCHEMA", []]] do + @conn.tables end end def test_indexes_logs_name with_example_table do - assert_logged [["PRAGMA index_list(\"ex\")", 'SCHEMA', []]] do - @conn.indexes('ex', 'hello') + assert_logged [["PRAGMA index_list(\"ex\")", "SCHEMA", []]] do + @conn.indexes("ex", "hello") end end end @@ -298,19 +296,17 @@ module ActiveRecord with_example_table do sql = <<-SQL SELECT name FROM sqlite_master - WHERE type IN ('table','view') AND name <> 'sqlite_sequence' AND name = 'ex' + WHERE type = 'table' AND name <> 'sqlite_sequence' AND name = 'ex' SQL - assert_logged [[sql.squish, 'SCHEMA', []]] do - ActiveSupport::Deprecation.silence do - assert @conn.table_exists?('ex') - end + assert_logged [[sql.squish, "SCHEMA", []]] do + assert @conn.table_exists?("ex") end end end def test_columns with_example_table do - columns = @conn.columns('ex').sort_by(&:name) + columns = @conn.columns("ex").sort_by(&:name) assert_equal 2, columns.length assert_equal %w{ id number }.sort, columns.map(&:name) assert_equal [nil, nil], columns.map(&:default) @@ -319,17 +315,17 @@ module ActiveRecord end def test_columns_with_default - with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer default 10' do - column = @conn.columns('ex').find { |x| - x.name == 'number' + with_example_table "id integer PRIMARY KEY AUTOINCREMENT, number integer default 10" do + column = @conn.columns("ex").find { |x| + x.name == "number" } - assert_equal '10', column.default + assert_equal "10", column.default end end def test_columns_with_not_null - with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer not null' do - column = @conn.columns('ex').find { |x| x.name == 'number' } + with_example_table "id integer PRIMARY KEY AUTOINCREMENT, number integer not null" do + column = @conn.columns("ex").find { |x| x.name == "number" } assert_not column.null, "column should not be null" end end @@ -337,59 +333,59 @@ module ActiveRecord def test_indexes_logs with_example_table do assert_logged [["PRAGMA index_list(\"ex\")", "SCHEMA", []]] do - @conn.indexes('ex') + @conn.indexes("ex") end end end def test_no_indexes - assert_equal [], @conn.indexes('items') + assert_equal [], @conn.indexes("items") end def test_index with_example_table do - @conn.add_index 'ex', 'id', unique: true, name: 'fun' - index = @conn.indexes('ex').find { |idx| idx.name == 'fun' } + @conn.add_index "ex", "id", unique: true, name: "fun" + index = @conn.indexes("ex").find { |idx| idx.name == "fun" } - assert_equal 'ex', index.table - assert index.unique, 'index is unique' - assert_equal ['id'], index.columns + assert_equal "ex", index.table + assert index.unique, "index is unique" + assert_equal ["id"], index.columns end end def test_non_unique_index with_example_table do - @conn.add_index 'ex', 'id', name: 'fun' - index = @conn.indexes('ex').find { |idx| idx.name == 'fun' } - assert_not index.unique, 'index is not unique' + @conn.add_index "ex", "id", name: "fun" + index = @conn.indexes("ex").find { |idx| idx.name == "fun" } + assert_not index.unique, "index is not unique" end end def test_compound_index with_example_table do - @conn.add_index 'ex', %w{ id number }, name: 'fun' - index = @conn.indexes('ex').find { |idx| idx.name == 'fun' } + @conn.add_index "ex", %w{ id number }, name: "fun" + index = @conn.indexes("ex").find { |idx| idx.name == "fun" } assert_equal %w{ id number }.sort, index.columns.sort end end def test_primary_key with_example_table do - assert_equal 'id', @conn.primary_key('ex') - with_example_table 'internet integer PRIMARY KEY AUTOINCREMENT, number integer not null', 'foos' do - assert_equal 'internet', @conn.primary_key('foos') + assert_equal "id", @conn.primary_key("ex") + with_example_table "internet integer PRIMARY KEY AUTOINCREMENT, number integer not null", "foos" do + assert_equal "internet", @conn.primary_key("foos") end end end def test_no_primary_key - with_example_table 'number integer not null' do - assert_nil @conn.primary_key('ex') + with_example_table "number integer not null" do + assert_nil @conn.primary_key("ex") end end def test_supports_extensions - assert_not @conn.supports_extensions?, 'does not support extensions' + assert_not @conn.supports_extensions?, "does not support extensions" end def test_respond_to_enable_extension @@ -402,15 +398,15 @@ module ActiveRecord def test_statement_closed db = ::SQLite3::Database.new(ActiveRecord::Base. - configurations['arunit']['database']) + configurations["arunit"]["database"]) statement = ::SQLite3::Statement.new(db, - 'CREATE TABLE statement_test (number integer not null)') - statement.stub(:step, ->{ raise ::SQLite3::BusyException.new('busy') }) do + "CREATE TABLE statement_test (number integer not null)") + statement.stub(:step, -> { raise ::SQLite3::BusyException.new("busy") }) do assert_called(statement, :columns, returns: []) do assert_called(statement, :close) do ::SQLite3::Statement.stub(:new, statement) do assert_raises ActiveRecord::StatementInvalid do - @conn.exec_query 'select * from statement_test' + @conn.exec_query "select * from statement_test" end end end @@ -420,22 +416,22 @@ module ActiveRecord private - def assert_logged logs - subscriber = SQLSubscriber.new - subscription = ActiveSupport::Notifications.subscribe('sql.active_record', subscriber) - yield - assert_equal logs, subscriber.logged - ensure - ActiveSupport::Notifications.unsubscribe(subscription) - end + def assert_logged(logs) + subscriber = SQLSubscriber.new + subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber) + yield + assert_equal logs, subscriber.logged + ensure + ActiveSupport::Notifications.unsubscribe(subscription) + end - def with_example_table(definition = nil, table_name = 'ex', &block) - definition ||= <<-SQL - id integer PRIMARY KEY AUTOINCREMENT, - number integer - SQL - super(@conn, table_name, definition, &block) - end + def with_example_table(definition = nil, table_name = "ex", &block) + definition ||= <<-SQL + id integer PRIMARY KEY AUTOINCREMENT, + number integer + SQL + super(@conn, table_name, definition, &block) + end end end end diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb index 9b675b804b..b1b4463bf1 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb @@ -1,5 +1,5 @@ require "cases/helper" -require 'models/owner' +require "models/owner" module ActiveRecord module ConnectionAdapters @@ -8,12 +8,12 @@ module ActiveRecord Dir.mktmpdir do |dir| begin dir = Pathname.new(dir) - @conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"), - :adapter => 'sqlite3', - :timeout => 100 + @conn = Base.sqlite3_connection database: dir.join("db/foo.sqlite3"), + adapter: "sqlite3", + timeout: 100 - assert Dir.exist? dir.join('db') - assert File.exist? dir.join('db/foo.sqlite3') + assert Dir.exist? dir.join("db") + assert File.exist? dir.join("db/foo.sqlite3") ensure @conn.disconnect! if @conn end diff --git a/activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb b/activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb index 24cc6875ab..aebcce3691 100644 --- a/activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb @@ -1,20 +1,20 @@ -require 'cases/helper' +require "cases/helper" class SQLite3StatementPoolTest < ActiveRecord::SQLite3TestCase if Process.respond_to?(:fork) def test_cache_is_per_pid cache = ActiveRecord::ConnectionAdapters::SQLite3Adapter::StatementPool.new(10) - cache['foo'] = 'bar' - assert_equal 'bar', cache['foo'] + cache["foo"] = "bar" + assert_equal "bar", cache["foo"] pid = fork { - lookup = cache['foo']; + lookup = cache["foo"]; exit!(!lookup) } Process.waitpid pid - assert $?.success?, 'process should exit successfully' + assert $?.success?, "process should exit successfully" end end end |