0

I'm working on an insert after trigger in Ruby on Rails using the hairtrigger gem, and the trigger is successfully inserting a record into the DB but for some reason the value of the previously inserted record's messages_count column is being added to the previous record's primary key value to calculate the id for the new record instead of a normal incrementation of 1.

Here's the hairtrigger definition:

trigger.after(:insert) do
<<~SQL
  INSERT INTO campaign_stats (campaign_id, messages_count)
  SELECT
      campaign_id as campaign_id,
      1 as messages_count
      FROM campaigns
      INNER JOIN campaign_subscriptions
      ON campaigns.id = campaign_subscriptions.campaign_id
      INNER JOIN conversations
      ON campaign_subscriptions.id = conversations.campaign_subscription_id
      WHERE conversations.id = NEW.conversation_id
      LIMIT 1
  ON CONFLICT (campaign_id) DO UPDATE
  SET
    messages_count = campaign_stats.messages_count + EXCLUDED.messages_count;
SQL


end

And some evidence of the incrementation that's happening using the messages_count:

    CampaignStat Load (0.3ms)  SELECT "campaign_stats".* FROM "campaign_stats"
=> [#<CampaignStat:0x00007fd2da9d96a8 id: 1, campaign_id: 1, messages_count: 5>,
 #<CampaignStat:0x00007fd2da9d9540 id: 6, campaign_id: 2, messages_count: 10>,
 #<CampaignStat:0x00007fd2da9d9400 id: 16, campaign_id: 3, messages_count: 5>,
 #<CampaignStat:0x00007fd2da9d9298 id: 21, campaign_id: 4, messages_count: 2>]

I'm unsure of what portion of my SQL could be causing this issue. Any help would be much appreciated.

Slowbeam
  • 21
  • 1

0 Answers0