activerecord-import: #import raises PG::NotNullViolation for id field on PostgreSQL
I recently migrated from MySQL to PostgreSQL and now I’m getting this when using #import:
ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint
The INSERT-Statement it produces clearly lists id as one of the fields and a NULL value is provided:
INSERT INTO "metrics_user_top_list_most_active" ("id","object_id","amount","at","created_at","updated_at","customer_id") VALUES (NULL, ...
I’m using activerecord-import 0.5.0 and Rails 4.0.4 so I guess for the id field to be NOT NULL is quite common. Any ideas what’s going wrong here?
Thanks, Chris
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Comments: 20
This happened to me too, but after much debugging, it turns out the issue stemmed from importing a Postgres dump.
To resolve, make sure sequences are owned by the correct column:
Then try running
Model.import
and you should be good.@jabley Thanks for pointing that out.
The issue is: when you
new
a record, theid
attribute is added with valuenil
, and there is no mechanism to remove this column ifsequence_name.nil?
orconnection.prefetch_primary_key? == false
forid
using uuid . Probably better to add some code about this?I find a work around for it. So instead of just passing the records, I also pass column_names excluding the
id
column:Thanks @caifara, Just added rescue block if table doesn’t id sequence.
just to lower the bar somewhat, had the same issue, this migration solved that:
I have this issue with Postgresql as well on a database a table like this:
When AR generates SQL for these records, it simply doesn’t specify the
id
column at all. For example:Whereas
import
generates the following (abbreviated):