Prepared statement bug?
Created by: sigra
Hi. I faced with very annoying bug. Let's assume we have the following structure:
create_table :products do |t|
t.string :name
t.integer :code_ids, array: true
end
create_table :codes do |t|
t.string :name
end
And simple models with simple relations:
class Product < ApplicationRecord; belongs_to_many :codes ;end
class Code < ApplicationRecord; has_many :products, array: true; end
Let's prepare some data:
code_ids = Code.pluck(:id)
# create Product with 1 Code (it's important to be first)
Product.create(name: 'one code', code_ids: code_ids.sample)
# create Product with 5 Codes
Product.create(name: 'five codes', code_ids.sample(5))
Now, let's play with collection where first Product has one Code:
Product.order(id: :asc).each do |product|
puts product.codes.map(&:name).to_sentence
end
In the output both Products will have just one Code, but second Product should have 5:
Product Load (2.8ms) SELECT "products".* FROM "products" ORDER BY "products"."id" ASC
Code Load (0.5ms) SELECT "codes".* FROM "codes" WHERE "codes"."id" IN ($1) [["code_ids", 169]]
F-1981
Code Load (0.4ms) SELECT "codes".* FROM "codes" WHERE "codes"."id" IN ($1) [["code_ids", 856]]
Q88
Go ahead and reload our server to clear cache and do vice versa experiment :)
Product.order(id: :desc).each do |product|
puts product.codes.map(&:name).to_sentence
end
Now output seems to be fine, but relation still uses cached prepared statement and puts NULL
in sql:
Product Load (0.3ms) SELECT "products".* FROM "products" ORDER BY "products"."id" DESC
Code Load (0.4ms) SELECT "codes".* FROM "codes" WHERE "codes"."id" IN ($1, $2, $3, $4, $5)
[["code_ids", 564], ["code_ids", 947], ["code_ids", 546], ["code_ids", 888], ["code_ids", 473]]
B54, VN-9122, O-2587, N-8840, X23
Code Load (0.2ms) SELECT "codes".* FROM "codes" WHERE "codes"."id" IN ($1, $2, $3, $4, $5)
[["code_ids", 169], ["code_ids", nil], ["code_ids", nil], ["code_ids", nil], ["code_ids", nil]]
F-1981
Any ideas how to fix this?
—————
My Gemfile:
ruby '2.5.6'
gem 'torque-postgresql', '~> 1.1'
gem 'pg', '= 1.2.3'
gem 'rails', '= 5.2.4.3'