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