db_info_service.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. from flask_babel import gettext as _
  2. from loguru import logger
  3. from sqlalchemy import text
  4. from config import Config
  5. from database.database import get_engine, get_session
  6. from services.database.admin_helpers import get_all_tables_stats
  7. def get_tables_info():
  8. session = None
  9. try:
  10. engine = get_engine()
  11. session = get_session()
  12. db_type = Config.DATABASE_TYPE
  13. stats = get_all_tables_stats(session, engine, db_type)
  14. table_info = [
  15. {
  16. "name": table_name,
  17. "rows": info["rows"],
  18. "size": info["size"],
  19. "has_data": info["rows"] > 0,
  20. }
  21. for table_name, info in stats.items()
  22. ]
  23. return {"status": "success", "tables": table_info}, 200
  24. except Exception:
  25. logger.exception("Error getting database tables")
  26. return {"status": "error", "message": _("Error interno del servidor")}, 500
  27. finally:
  28. if session:
  29. session.close()
  30. def get_db_health():
  31. """Return a health snapshot of the database.
  32. SQLite integrity is deliberately not checked here. A quick_check can
  33. scan the complete database, so it is executed only by the explicit
  34. integrity-check action in the administration panel.
  35. """
  36. session = None
  37. try:
  38. engine = get_engine()
  39. session = get_session()
  40. db_type = Config.DATABASE_TYPE
  41. health = {
  42. "db_type": db_type,
  43. "table_count": 0,
  44. "total_rows": 0,
  45. "total_size_bytes": 0,
  46. "extra": {},
  47. }
  48. if db_type == "SQLITE":
  49. # ── Read header-level PRAGMAs first (safe on any DB state) ──
  50. page_size = session.execute(text("PRAGMA page_size")).scalar() or 0
  51. page_count = session.execute(text("PRAGMA page_count")).scalar() or 0
  52. freelist_count = (
  53. session.execute(text("PRAGMA freelist_count")).scalar() or 0
  54. )
  55. journal_mode = (
  56. session.execute(text("PRAGMA journal_mode")).scalar() or "unknown"
  57. )
  58. auto_vacuum_val = session.execute(text("PRAGMA auto_vacuum")).scalar() or 0
  59. _av = {0: "None", 1: "Full", 2: "Incremental"}
  60. fragmentation_pct = (
  61. round(freelist_count / page_count * 100, 2) if page_count else 0.0
  62. )
  63. health["total_size_bytes"] = page_size * page_count
  64. health["extra"] = {
  65. "page_size": page_size,
  66. "page_count": page_count,
  67. "freelist_count": freelist_count,
  68. "journal_mode": journal_mode,
  69. "auto_vacuum": _av.get(auto_vacuum_val, str(auto_vacuum_val)),
  70. "fragmentation_pct": fragmentation_pct,
  71. "corruption": False,
  72. "corruption_detail": None,
  73. "integrity_checked": False,
  74. }
  75. # ── Table stats (may fail on severely corrupted DBs) ──
  76. try:
  77. stats = get_all_tables_stats(session, engine, db_type)
  78. health["table_count"] = len(stats)
  79. health["total_rows"] = sum(v["rows"] for v in stats.values())
  80. except Exception:
  81. logger.warning(
  82. "Could not read SQLite table stats — database may be corrupted"
  83. )
  84. elif db_type in ("MYSQL", "MARIADB"):
  85. stats = get_all_tables_stats(session, engine, db_type)
  86. health["table_count"] = len(stats)
  87. health["total_rows"] = sum(v["rows"] for v in stats.values())
  88. size = (
  89. session.execute(
  90. text(
  91. "SELECT COALESCE(SUM(data_length + index_length), 0)"
  92. " FROM information_schema.tables WHERE table_schema = DATABASE()"
  93. )
  94. ).scalar()
  95. or 0
  96. )
  97. version = session.execute(text("SELECT VERSION()")).scalar() or "unknown"
  98. health["total_size_bytes"] = int(size)
  99. health["extra"] = {"version": version}
  100. elif db_type in ("POSTGRES", "POSTGRESQL"):
  101. stats = get_all_tables_stats(session, engine, db_type)
  102. health["table_count"] = len(stats)
  103. health["total_rows"] = sum(v["rows"] for v in stats.values())
  104. size = (
  105. session.execute(
  106. text("SELECT pg_database_size(current_database())")
  107. ).scalar()
  108. or 0
  109. )
  110. version = session.execute(text("SELECT version()")).scalar() or "unknown"
  111. health["total_size_bytes"] = int(size)
  112. health["extra"] = {"version": " ".join(version.split()[:2])}
  113. return {"status": "success", "health": health}, 200
  114. except Exception:
  115. logger.exception("Error getting DB health")
  116. return {"status": "error", "message": _("Error interno del servidor")}, 500
  117. finally:
  118. if session:
  119. session.close()
  120. def run_integrity_check():
  121. """Run a quick integrity check. Uses PRAGMA quick_check for SQLite."""
  122. session = None
  123. try:
  124. session = get_session()
  125. db_type = Config.DATABASE_TYPE
  126. errors = []
  127. if db_type == "SQLITE":
  128. rows = session.execute(text("PRAGMA quick_check")).fetchall()
  129. errors = [r[0] for r in rows if r[0] != "ok"]
  130. elif db_type in ("MYSQL", "MARIADB"):
  131. tables = session.execute(
  132. text(
  133. "SELECT table_name FROM information_schema.tables"
  134. " WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'"
  135. )
  136. ).fetchall()
  137. for (t,) in tables:
  138. rows = session.execute(text(f"CHECK TABLE `{t}` FAST QUICK")).fetchall()
  139. for row in rows:
  140. if row[3] not in ("OK", "note"):
  141. errors.append(f"{t}: {row[3]}")
  142. else:
  143. session.execute(text("SELECT 1"))
  144. return {
  145. "status": "success",
  146. "integrity": {
  147. "ok": not errors,
  148. "errors": errors[:10],
  149. "error_count": len(errors),
  150. },
  151. }, 200
  152. except Exception:
  153. logger.exception("Error running integrity check")
  154. return {
  155. "status": "error",
  156. "message": _("Error al ejecutar la verificación"),
  157. }, 500
  158. finally:
  159. if session:
  160. session.close()