Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Activerecord: Insert fails on composed_primary_key model with id as not null Identity column #51821

Closed
rafaelsouza opened this issue May 14, 2024 · 0 comments · Fixed by #51859

Comments

@rafaelsouza
Copy link

Steps to reproduce

With default of 7x config.active_record.partial_inserts = false inserts are failing on a composite primary key with id as IDENTITY column. I can get a workaround by reverting config.active_record.partial_inserts to true.

I also experimented a possible solution on main...rafaelsouza:rails:rafaelsouza/fix-composed-primary-key-bug-with-identity-generated-id . I know it can be solved a couple of different ways, if this is reasonable let me know.

# frozen_string_literal: true

require "bundler/inline"

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

  gem "activerecord", "~> 7.1"
  gem "pg", "~> 1.5.4"
end

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

ActiveRecord::Base.partial_inserts = false

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "postgresql", host: "localhost", database: "rails")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.connection.exec_query("drop table if exists companies");
ActiveRecord::Base.connection.exec_query(<<~SQL)
  create table companies (
    id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
    CONSTRAINT companies_pkey PRIMARY KEY (id)
  );
SQL

ActiveRecord::Base.connection.exec_query("drop table if exists users");
ActiveRecord::Base.connection.exec_query(<<~SQL)
  create table users (
    company_id integer NOT NULL,
    id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
    name text,
    CONSTRAINT users_pkey PRIMARY KEY (company_id, id)
  );
SQL

class Company < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  self.primary_key = [:company_id, :id]
  belongs_to :company
end

class BugTest < Minitest::Test
  def test_error
    company = Company.create!
    company.users.create!(name: "John")

    assert_equal 1, company.users.count
  end
end

Expected behavior

Actual behavior

ActiveRecord::NotNullViolation: PG::NotNullViolation: ERROR: null value in column "id" of relation "users" violates not-null constraint

System configuration

Rails version: 7.1.x

Ruby version: 3.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants