'Is it safe to enable/disable a PSQL trigger in a transaction?

I have a question(s) regarding implementing postgresql triggers, best practices, and general safely for using them. It's difficult for me to ask targeted questions because I don't know what I don't know but I'll do my best to explain my feature and then ask my questions.

In my rails application I have a feature in which a user can upload a large csv file that contains million of records needing to be imported into the app. Occasionally, in these large files, duplicate entries exist and I need to log those duplicate entries into a separate table. In order to implement this feature, I've enabled a trigger in the following manner in my Rails application. The following is some pseudocode to illustrate how I did this.

#1. Rails Migration

def up
  # Create the trigger
  # This is a STATEMENT level AFTER INSERT trigger that writes to a duplicate log table 
    in the event that a duplicate entry is found.
end

def down
  # drop the trigger
end

#2. pseudo code rails/sql code logic for importing the records.

     ActiveRecord::Base.transaction do
       1. Create a temporary table to upload the csv entries into. Drop on commit.
       2. Enable the trigger that I created from the migration.
       3. Import everything into the temporary table.
       4. From the temporary table, insert the data into the real destination table. If
          there is a duplicate unique constraint violation, do nothing.
       5. After the insert is done on the destination table, execute the trigger to copy
          all the duplicated entries into the duplicate table.
       6. Disable the trigger.
     end

My questions are the following for the process.

Is this a generally safe approach for implementing the trigger in the code base? For example, if another user uploads another file while the first is still processing, will this interfere with the previous upload in anyway trigger wise? I read that the temporary table should be fine because psql will make its own 'scope/thread' for the table even if they are named the same, but I'm unsure if chaos will be unleashed with the trigger. Is there danger there?

What I would hate to happen is that this trigger goes hay wire with multiple users uploading files of various lengths at different times with some overlapping. I'm unsure as to whether this will affect every thread or if I've carefully isolated it.

Furthermore, as I'm new to triggers what other pitfalls can this process have that I need to look out for. I would be specific if I could but as I mentioned earlier, I don't know what I don't know. Thank you for the help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source