Skip to content

Commit

Permalink
feat: add db_heartbeat
Browse files Browse the repository at this point in the history
  • Loading branch information
panteparak committed Oct 16, 2024
1 parent b0e2c4c commit 2b1a92b
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions health_check/contrib/db_heartbeat/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import django

if django.VERSION < (3, 2):
default_app_config = "health_check.contrib.db_heartbeat.apps.HealthCheckConfig"
10 changes: 10 additions & 0 deletions health_check/contrib/db_heartbeat/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from django.apps import AppConfig
from health_check.plugins import plugin_dir


class HealthCheckConfig(AppConfig):
name = 'health_check.contrib.db_heartbeat'

def ready(self):
from .backends import DatabaseHeartBeatCheck
plugin_dir.register(DatabaseHeartBeatCheck)
21 changes: 21 additions & 0 deletions health_check/contrib/db_heartbeat/backends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from health_check.backends import BaseHealthCheckBackend
from health_check.exceptions import ServiceUnavailable, ServiceReturnedUnexpectedResult
from django.db import connection


class DatabaseHeartBeatCheck(BaseHealthCheckBackend):
"""
Health check that runs a simple SELECT 1; query to test if the database connection is alive.
"""

def check_status(self):
try:
result = None
with connection.cursor() as cursor:
cursor.execute("SELECT 1;")
result = cursor.fetchone()

if result != (1,):
raise ServiceReturnedUnexpectedResult("Health Check query did not return the expected result.")
except Exception as e:
raise ServiceUnavailable(f"Database health check failed: {e}")

0 comments on commit 2b1a92b

Please sign in to comment.