4

I'm using activerecord-import gem to import many records in one DB insert, in the same project I'm using apartment gem to create and use multi postgres schemas and switch between many schemas realtime ...

the issue is sometimes after import records, will be conflict in unique records ids!

ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "table_name_" DETAIL: Key (id)=(43) already exists.

this conflict only happening by using active-record import gem ...

alexisdevarennes
  • 5,437
  • 4
  • 24
  • 38
Yaman ALTareh
  • 286
  • 3
  • 12

1 Answers1

3

After debugging many cases ... I realized that the issue is coming from active record sequence_name after switching schema by apartment gem ..

let's say we have two schemas schema_1 and schema_2, after switching schema by apartment gem, it doesn't change the sequence_name of DB table!!, like following ...

Apartment::Tenant.switch! :schema_1
TableName.sequence_name => "schema_1.table_names_id_seq"
Apartment::Tenant.switch! :schema_2
TableName.sequence_name => "schema_1.table_names_id_seq"

so after switching to schema_2 and using active-record-import gem it takes the sequence id from old schema! (schema_1) ... and could be this id is already used in the schema_2 ... and will be PG::UniqueViolation error ...

I tried creating records by TableName.create or .save ... and it works correctly! and getting new sequence ids from current schema (schema_2) ..

it seems like .create and .save refresh sequence_name automatically but active-records-import doesn't !

I solved this by refreshing sequence_name manually before using .import , by:

TableName.reset_sequence_name
Yaman ALTareh
  • 286
  • 3
  • 12