class DefaultsTestWithoutTransactionalFixtures

Public Instance Methods

test_mysql_not_null_defaults_non_strict() click to toggle source

Strict mode controls how MySQL handles invalid or missing values in data-change statements such as INSERT or UPDATE. A value can be invalid for several reasons. For example, it might have the wrong data type for the column, or it might be out of range. A value is missing when a new row to be inserted does not contain a value for a non-NULL column that has no explicit DEFAULT clause in its definition. (For a NULL column, NULL is inserted if the value is missing.)

If strict mode is not in effect, MySQL inserts adjusted values for invalid or missing values and produces warnings. In strict mode, you can produce this behavior by using INSERT IGNORE or UPDATE IGNORE.

dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict

# File activerecord/test/cases/defaults_test.rb, line 160
def test_mysql_not_null_defaults_non_strict
  using_strict(false) do
    with_mysql_not_null_table do |klass|
      record = klass.new
      assert_nil record.non_null_integer
      assert_nil record.non_null_string
      assert_nil record.non_null_text
      assert_nil record.non_null_blob

      record.save!
      record.reload

      assert_equal 0,  record.non_null_integer
      assert_equal "", record.non_null_string
      assert_equal "", record.non_null_text
      assert_equal "", record.non_null_blob
    end
  end
end
test_mysql_not_null_defaults_strict() click to toggle source
# File activerecord/test/cases/defaults_test.rb, line 180
def test_mysql_not_null_defaults_strict
  using_strict(true) do
    with_mysql_not_null_table do |klass|
      record = klass.new
      assert_nil record.non_null_integer
      assert_nil record.non_null_string
      assert_nil record.non_null_text
      assert_nil record.non_null_blob

      assert_raises(ActiveRecord::NotNullViolation) { klass.create }
    end
  end
end
using_strict(strict) { || ... } click to toggle source
# File activerecord/test/cases/defaults_test.rb, line 138
def using_strict(strict)
  connection = ActiveRecord::Base.remove_connection
  ActiveRecord::Base.establish_connection connection.merge(strict: strict)
  yield
ensure
  ActiveRecord::Base.remove_connection
  ActiveRecord::Base.establish_connection connection
end
with_mysql_not_null_table() { |klass| ... } click to toggle source
# File activerecord/test/cases/defaults_test.rb, line 194
def with_mysql_not_null_table
  klass = Class.new(ActiveRecord::Base)
  klass.table_name = "test_mysql_not_null_defaults"
  klass.connection.create_table klass.table_name do |t|
    t.integer :non_null_integer, null: false
    t.string  :non_null_string,  null: false
    t.text    :non_null_text,    null: false
    t.blob    :non_null_blob,    null: false
  end

  yield klass
ensure
  klass.connection.drop_table(klass.table_name) rescue nil
end