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.

65 lines
1.9 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. def _sqlite(cursor):
  27. cursor.execute("""
  28. DROP TRIGGER IF EXISTS update_alert_after;
  29. """)
  30. cursor.execute("""
  31. CREATE TRIGGER update_alert_after
  32. AFTER UPDATE OF last_ping, timeout, grace ON api_check
  33. FOR EACH ROW BEGIN
  34. UPDATE api_check
  35. SET alert_after = datetime(strftime('%s', last_ping) + timeout/1000000 + grace/1000000, 'unixepoch')
  36. WHERE id = OLD.id;
  37. END;
  38. """)
  39. class Command(BaseCommand):
  40. help = 'Ensures triggers exist in database'
  41. def handle(self, *args, **options):
  42. cursor = connection.cursor()
  43. if connection.vendor == "postgresql":
  44. _pg(cursor)
  45. return "Created PostgreSQL trigger"
  46. if connection.vendor == "mysql":
  47. _mysql(cursor)
  48. return "Created MySQL trigger"
  49. if connection.vendor == "sqlite":
  50. _sqlite(cursor)
  51. return "Created SQLite trigger"