SQL in compkeys save is syntax error for PG

48 views
Skip to first unread message

masterchief

unread,
May 30, 2012, 4:41:10 PM5/30/12
to Composite Keys for ActiveRecord
I inherited a project this month that also just went through an
upgrade from Rails 3.0.7 to Rails 3.2.3.

This jump between rails versions appears to have
composite_primary_keys doing something very strange in certain cases.
Please observe the following. We have a class we'll call "item", where
three keys are defined:

self.primary_keys = :item_id, :item_type_id, :column_number

While attempting a save or update_attributes on an instance of this
class, using the key of [234,5,1], here is the SQL being generated:

***********************************************
SELECT 1 FROM "item" WHERE
("item"."slug" = 'my-name' AND
(("item"."item_id" != 234 OR "item"."item_type_id" != 5,
"item"."column_number" != 1) OR "item"."item_type_id" != 5,
"item"."column_number" != 1))
LIMIT 1
***********************************************

Postgres throws an error on this with:
PG::Error: ERROR: argument of OR must be type boolean, not type record
referring to the spot right after the AND.

Here's the second weird thing. If I do a find on this class, ie
(Item.find(234,5,1)) using the exact same parameters, the SQL
generated is just fine, like so:

***********************************************
SELECT "item".* FROM "item" WHERE "item"."item_id" = 234 AND
"item"."item_type_id" = 5 AND "item"."column_number" = 1
***********************************************

The class Item simply inherits from ActiveRecord::Base

This happens for both Rails 3.2.0 and Rails 3.2.3.
This is using: Ruby 1.9.3, PG gem 0.13.2, CPK gem 5.0.6

Any help is appreciated!


masterchief

unread,
May 30, 2012, 10:39:54 PM5/30/12
to Composite Keys for ActiveRecord
Ok. Found the issue.

In the declaration of the model for "Item", I have a field/column
called "slug". I'm not using it as a key. But I want it to be unique.
So I have, in the model, several lines below the primary key
declaration:

validates :slug, :uniqueness => true, :presence => true

This causes a huge problem for CPK/Rails and results in the garbage
SQL shown above.

It looks like the problem probably occurs in arel.compile_update.

Note that I have ~20 other models that all use CPK without issue, but
none of them have a uniqueness validator. Commenting out the validates
line solves the problem in this case (although I'd like to be able to
use it).

Lori M Olson

unread,
May 31, 2012, 9:30:13 PM5/31/12
to compos...@googlegroups.com
Well, you can enforce uniqueness and presence at the database level, if that helps...
Reply all
Reply to author
Forward
0 new messages