db_info_service.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. For SQLite, runs PRAGMA quick_check(1) on every call so corruption is
  33. detected automatically without the user having to click the integrity
  34. check button. The query stops after the *first* error it finds, keeping
  35. latency acceptable even on large databases.
  36. """
  37. session = None
  38. try:
  39. engine = get_engine()
  40. session = get_session()
  41. db_type = Config.DATABASE_TYPE
  42. health = {
  43. "db_type": db_type,
  44. "table_count": 0,
  45. "total_rows": 0,
  46. "total_size_bytes": 0,
  47. "extra": {},
  48. }
  49. if db_type == "SQLITE":
  50. # ── Read header-level PRAGMAs first (safe on any DB state) ──
  51. page_size = session.execute(text("PRAGMA page_size")).scalar() or 0
  52. page_count = session.execute(text("PRAGMA page_count")).scalar() or 0
  53. freelist_count = (
  54. session.execute(text("PRAGMA freelist_count")).scalar() or 0
  55. )
  56. journal_mode = (
  57. session.execute(text("PRAGMA journal_mode")).scalar() or "unknown"
  58. )
  59. auto_vacuum_val = session.execute(text("PRAGMA auto_vacuum")).scalar() or 0
  60. _av = {0: "None", 1: "Full", 2: "Incremental"}
  61. fragmentation_pct = (
  62. round(freelist_count / page_count * 100, 2) if page_count else 0.0
  63. )
  64. health["total_size_bytes"] = page_size * page_count
  65. # ── Corruption probe: quick_check stops at the first bad page ──
  66. corruption = False
  67. corruption_detail = None
  68. try:
  69. qc_rows = session.execute(text("PRAGMA quick_check(1)")).fetchall()
  70. if not qc_rows or qc_rows[0][0] != "ok":
  71. corruption = True
  72. corruption_detail = (
  73. qc_rows[0][0] if qc_rows else "Sin respuesta del PRAGMA"
  74. )
  75. except Exception:
  76. corruption = True
  77. corruption_detail = _(
  78. "No se pudo completar la verificación de integridad"
  79. )
  80. health["extra"] = {
  81. "page_size": page_size,
  82. "page_count": page_count,
  83. "freelist_count": freelist_count,
  84. "journal_mode": journal_mode,
  85. "auto_vacuum": _av.get(auto_vacuum_val, str(auto_vacuum_val)),
  86. "fragmentation_pct": fragmentation_pct,
  87. "corruption": corruption,
  88. "corruption_detail": corruption_detail,
  89. }
  90. # ── Table stats (may fail on severely corrupted DBs) ──
  91. try:
  92. stats = get_all_tables_stats(session, engine, db_type)
  93. health["table_count"] = len(stats)
  94. health["total_rows"] = sum(v["rows"] for v in stats.values())
  95. except Exception:
  96. logger.warning(
  97. "Could not read SQLite table stats — database may be corrupted"
  98. )
  99. elif db_type in ("MYSQL", "MARIADB"):
  100. stats = get_all_tables_stats(session, engine, db_type)
  101. health["table_count"] = len(stats)
  102. health["total_rows"] = sum(v["rows"] for v in stats.values())
  103. size = (
  104. session.execute(
  105. text(
  106. "SELECT COALESCE(SUM(data_length + index_length), 0)"
  107. " FROM information_schema.tables WHERE table_schema = DATABASE()"
  108. )
  109. ).scalar()
  110. or 0
  111. )
  112. version = session.execute(text("SELECT VERSION()")).scalar() or "unknown"
  113. health["total_size_bytes"] = int(size)
  114. health["extra"] = {"version": version}
  115. elif db_type in ("POSTGRES", "POSTGRESQL"):
  116. stats = get_all_tables_stats(session, engine, db_type)
  117. health["table_count"] = len(stats)
  118. health["total_rows"] = sum(v["rows"] for v in stats.values())
  119. size = (
  120. session.execute(
  121. text("SELECT pg_database_size(current_database())")
  122. ).scalar()
  123. or 0
  124. )
  125. version = session.execute(text("SELECT version()")).scalar() or "unknown"
  126. health["total_size_bytes"] = int(size)
  127. health["extra"] = {"version": " ".join(version.split()[:2])}
  128. return {"status": "success", "health": health}, 200
  129. except Exception:
  130. logger.exception("Error getting DB health")
  131. return {"status": "error", "message": _("Error interno del servidor")}, 500
  132. finally:
  133. if session:
  134. session.close()
  135. def run_integrity_check():
  136. """Run a quick integrity check. Uses PRAGMA quick_check for SQLite."""
  137. session = None
  138. try:
  139. session = get_session()
  140. db_type = Config.DATABASE_TYPE
  141. errors = []
  142. if db_type == "SQLITE":
  143. rows = session.execute(text("PRAGMA quick_check")).fetchall()
  144. errors = [r[0] for r in rows if r[0] != "ok"]
  145. elif db_type in ("MYSQL", "MARIADB"):
  146. tables = session.execute(
  147. text(
  148. "SELECT table_name FROM information_schema.tables"
  149. " WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'"
  150. )
  151. ).fetchall()
  152. for (t,) in tables:
  153. rows = session.execute(text(f"CHECK TABLE `{t}` FAST QUICK")).fetchall()
  154. for row in rows:
  155. if row[3] not in ("OK", "note"):
  156. errors.append(f"{t}: {row[3]}")
  157. else:
  158. session.execute(text("SELECT 1"))
  159. return {
  160. "status": "success",
  161. "integrity": {
  162. "ok": not errors,
  163. "errors": errors[:10],
  164. "error_count": len(errors),
  165. },
  166. }, 200
  167. except Exception:
  168. logger.exception("Error running integrity check")
  169. return {
  170. "status": "error",
  171. "message": _("Error al ejecutar la verificación"),
  172. }, 500
  173. finally:
  174. if session:
  175. session.close()