Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow multiple triggers on same event #86

Open
jcraigk opened this issue Dec 5, 2019 · 3 comments
Open

Allow multiple triggers on same event #86

jcraigk opened this issue Dec 5, 2019 · 3 comments
Labels

Comments

@jcraigk
Copy link

jcraigk commented Dec 5, 2019

Currently if multiple triggers are defined on :insert, for example, the second trigger overwrites the first one as the trigger naming in the auto-generated migration is based only on model and event. Adding an auto-incrementing integer at the end of the trigger name would allow for multiple triggers.

An example use case here is needing multiple pg_advisory_xact_locks on another table based on different fields in the triggering record. For example, a Message sent from from_user_id to to_user_id would need two separate locks on User to handle messages_received_count and messages_sent_count respectively. If there is another way to handle this or if multiple triggers on :insert is a bad idea, please comment.

@jcraigk
Copy link
Author

jcraigk commented Dec 6, 2019

Update: Using pg_advisory_unlock_all() and related functions (depending on your database) within a given set of SQL in a single trigger seems to work fine. This overcomes the need for multiple triggers for me but interested in others' opinions.

@wwahammy
Copy link

I was just caught by this in migrating to using hair_trigger with my Postgres database. Multiple triggers per-event would be amazing.

@jenseng
Copy link
Owner

jenseng commented Feb 11, 2022

You should be able to define multiple triggers using trigger groups ... e.g.

trigger.after(:update) do |t|
  t.all do # every row
    # some sql
  end
  t.of("foo") do
    # some more sql
  end
  t.where("OLD.bar != NEW.bar AND NEW.bar != 'lol'") do
    # some other sql
  end
end

Would that resolve your use case? One gotcha might be if you're doing this in a migration instead of a model, you may need to drop and recreate all the triggers for the group whenever you want to add a new one 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants