rails-sqlserver / activerecord-sqlserver-adapter

SQL Server Adapter For Rails
MIT License
968 stars 558 forks source link

Default value read from another field #1131

Closed budiljak closed 8 months ago

budiljak commented 8 months ago

Hi @aidanharan.

This was really hard to reproduce. It's a bug that was introduced with version 7.0.5 of activerecord-sqlserver-adapter.

Under certain circumstances the default value is read from another field - if the other field starts with the name of the first field.

Here's the script to reproduce the bug:

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"
  gem "tiny_tds"

  gem "activerecord", "=7.0.4.2"
  gem "activerecord-sqlserver-adapter", "=7.0.5"
end

require "active_record"
require "minitest/autorun"
require "logger"

ActiveRecord::Base.establish_connection(
  adapter:  "sqlserver",
  timeout:  5000,
  pool:     100,
  encoding: "utf8",
  database: "test_database",
  username: "SA",
  password: "StrongPassword!",
  host:     "localhost",
  port:     1433,
)
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  drop_table :bug_test_tables rescue nil

  ActiveRecord::Base.connection.execute("CREATE TABLE [dbo].[bug_test_tables](id [int], dt_field [datetime] NULL, dt_fieldX [bit]);")
  ActiveRecord::Base.connection.execute("ALTER TABLE [dbo].[bug_test_tables] ADD CONSTRAINT [DEFAULT_TEST] DEFAULT (NULL) FOR [dt_field];")
  ActiveRecord::Base.connection.execute("ALTER TABLE [dbo].[bug_test_tables] ADD CONSTRAINT [DEFAULT_TEST_X] DEFAULT ((0)) FOR [dt_fieldX];")
  drop_view = "DROP VIEW IF EXISTS bug_tests;"
  create_view = "CREATE VIEW bug_tests AS SELECT id AS id, dt_field as dt, dt_fieldX as dt_x FROM bug_test_tables"
  ActiveRecord::Base.connection.execute(drop_view)
  ActiveRecord::Base.connection.execute(create_view)
end

class BugTest < ActiveRecord::Base
end

class TestBugTest < Minitest::Test
  def setup
    @bug_test = BugTest.new
  end

  def test_default_value
    assert_nil @bug_test.dt
    @bug_test.save!
  end
end
aidanharan commented 8 months ago

@budiljak This issue has been fixed in v7.0.5.1