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.

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