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

About on_duplicate_key_update with create or update behavior #652

Closed
berniechiu opened this issue Dec 2, 2019 · 2 comments
Closed

About on_duplicate_key_update with create or update behavior #652

berniechiu opened this issue Dec 2, 2019 · 2 comments

Comments

@berniechiu
Copy link

berniechiu commented Dec 2, 2019

Hi, sorry to bother with an issue, I have a question about on_duplicate_key_update

I have a generated SQL like this in Postgres using the gem

INSERT INTO "products" ("id","identifier","name","length","width","height","weight","item_category_id","input_type","created_at","updated_at")
VALUES 
  ('c76bbcb6-6ec7-454f-8bb2-b35eeaa7df62','B0000DE5931','occaecati','5.0','76.0','10.0','8.0',14,'csv_upload','2019-12-02 15:00:34.836113','2019-12-02 15:00:34.836113'),
  (NULL,'B000A3T3LY2','quia','25','13','64','1',19,'csv_upload','2019-12-02 15:00:34.836113','2019-12-02 15:00:34.836113')
  ON CONFLICT (id) DO UPDATE SET "identifier"=EXCLUDED."identifier","name"=EXCLUDED."name","length"=EXCLUDED."length","width"=EXCLUDED."width","height"=EXCLUDED."height","weight"=EXCLUDED."weight","item_category_id"=EXCLUDED."item_category_id","updated_at"=EXCLUDED."updated_at" RETURNING "id"

And then I got this error

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

I imagined it'll update the record if the id is found or else it creates a new one, but apparently it's not what I thought. I can separate the query of course, but I imagined the purpose of
on_duplicate_key_update is to create or update, I wonder it there's an easier way to still write it into one SQL statement or I'm using it wrong. @@

@jkowens
Copy link
Collaborator

jkowens commented Dec 3, 2019

When doing an insert, you cannot mix records that do not have an id set with those that do because the resulting sql statement will be invalid as you are experiencing. The on_duplicate_key_update option will update existing records instead of the database throwing a duplicate key exception.

@berniechiu
Copy link
Author

Thanks a lot!

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

No branches or pull requests

2 participants