migration_helpers.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. #---
  10. # Excerpted from "Agile Web Development with Rails, 4rd Ed.",
  11. # published by The Pragmatic Bookshelf.
  12. # Copyrights apply to this code. It may not be used to create training material,
  13. # courses, books, articles, and the like. Contact us if you are in doubt.
  14. # We make no guarantees that this code is fit for any purpose.
  15. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  16. #---
  17. module MigrationHelpers
  18. def foreign_key(from_table, from_column, to_table)
  19. constraint_name = "fk_#{from_table}_#{to_table}"
  20. execute %{
  21. CREATE TRIGGER #{constraint_name}_insert
  22. BEFORE INSERT ON #{from_table}
  23. FOR EACH ROW BEGIN
  24. SELECT
  25. RAISE(ABORT, "constraint violation: #{constraint_name}")
  26. WHERE
  27. (SELECT id FROM #{to_table} WHERE id = NEW.#{from_column}) IS NULL;
  28. END;
  29. }
  30. execute %{
  31. CREATE TRIGGER #{constraint_name}_update
  32. BEFORE UPDATE ON #{from_table}
  33. FOR EACH ROW BEGIN
  34. SELECT
  35. RAISE(ABORT, "constraint violation: #{constraint_name}")
  36. WHERE
  37. (SELECT id FROM #{to_table} WHERE id = NEW.#{from_column}) IS NULL;
  38. END;
  39. }
  40. execute %{
  41. CREATE TRIGGER #{constraint_name}_delete
  42. BEFORE DELETE ON #{to_table}
  43. FOR EACH ROW BEGIN
  44. SELECT
  45. RAISE(ABORT, "constraint violation: #{constraint_name}")
  46. WHERE
  47. (SELECT id FROM #{from_table} WHERE #{from_column} = OLD.id) IS NOT NULL;
  48. END;
  49. }
  50. end
  51. end