You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.3 KiB

  1. from django.core.management.base import BaseCommand
  2. from django.db import connection
  3. def _pg(cursor):
  4. cursor.execute("""
  5. CREATE OR REPLACE FUNCTION update_alert_after()
  6. RETURNS trigger AS $update_alert_after$
  7. BEGIN
  8. IF NEW.last_ping IS NOT NULL THEN
  9. NEW.alert_after := NEW.last_ping + NEW.timeout + NEW.grace;
  10. END IF;
  11. RETURN NEW;
  12. END;
  13. $update_alert_after$ LANGUAGE plpgsql;
  14. DROP TRIGGER IF EXISTS update_alert_after ON api_check;
  15. CREATE TRIGGER update_alert_after
  16. BEFORE INSERT OR UPDATE OF last_ping, timeout, grace ON api_check
  17. FOR EACH ROW EXECUTE PROCEDURE update_alert_after();
  18. """)
  19. def _mysql(cursor):
  20. cursor.execute("""
  21. DROP TRIGGER IF EXISTS update_alert_after;
  22. CREATE TRIGGER update_alert_after
  23. BEFORE UPDATE ON api_check
  24. FOR EACH ROW SET NEW.alert_after = NEW.last_ping + INTERVAL (NEW.timeout + NEW.grace) MICROSECOND;
  25. """)
  26. class Command(BaseCommand):
  27. help = 'Ensures triggers exist in database'
  28. def handle(self, *args, **options):
  29. cursor = connection.cursor()
  30. if connection.vendor == "postgresql":
  31. _pg(cursor)
  32. print("Created PostgreSQL trigger")
  33. if connection.vendor == "mysql":
  34. _mysql(cursor)
  35. print("Created MySQL trigger")