db_info_service.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 as qc_err:
  76. corruption = True
  77. corruption_detail = str(qc_err)
  78. health["extra"] = {
  79. "page_size": page_size,
  80. "page_count": page_count,
  81. "freelist_count": freelist_count,
  82. "journal_mode": journal_mode,
  83. "auto_vacuum": _av.get(auto_vacuum_val, str(auto_vacuum_val)),
  84. "fragmentation_pct": fragmentation_pct,
  85. "corruption": corruption,
  86. "corruption_detail": corruption_detail,
  87. }
  88. # ── Table stats (may fail on severely corrupted DBs) ──
  89. try:
  90. stats = get_all_tables_stats(session, engine, db_type)
  91. health["table_count"] = len(stats)
  92. health["total_rows"] = sum(v["rows"] for v in stats.values())
  93. except Exception:
  94. logger.warning(
  95. "Could not read SQLite table stats — database may be corrupted"
  96. )
  97. elif db_type in ("MYSQL", "MARIADB"):
  98. stats = get_all_tables_stats(session, engine, db_type)
  99. health["table_count"] = len(stats)
  100. health["total_rows"] = sum(v["rows"] for v in stats.values())
  101. size = (
  102. session.execute(
  103. text(
  104. "SELECT COALESCE(SUM(data_length + index_length), 0)"
  105. " FROM information_schema.tables WHERE table_schema = DATABASE()"
  106. )
  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": version}
  113. elif db_type in ("POSTGRES", "POSTGRESQL"):
  114. stats = get_all_tables_stats(session, engine, db_type)
  115. health["table_count"] = len(stats)
  116. health["total_rows"] = sum(v["rows"] for v in stats.values())
  117. size = (
  118. session.execute(
  119. text("SELECT pg_database_size(current_database())")
  120. ).scalar()
  121. or 0
  122. )
  123. version = session.execute(text("SELECT version()")).scalar() or "unknown"
  124. health["total_size_bytes"] = int(size)
  125. health["extra"] = {"version": " ".join(version.split()[:2])}
  126. return {"status": "success", "health": health}, 200
  127. except Exception:
  128. logger.exception("Error getting DB health")
  129. return {"status": "error", "message": _("Error interno del servidor")}, 500
  130. finally:
  131. if session:
  132. session.close()
  133. def run_integrity_check():
  134. """Run a quick integrity check. Uses PRAGMA quick_check for SQLite."""
  135. session = None
  136. try:
  137. session = get_session()
  138. db_type = Config.DATABASE_TYPE
  139. errors = []
  140. if db_type == "SQLITE":
  141. rows = session.execute(text("PRAGMA quick_check")).fetchall()
  142. errors = [r[0] for r in rows if r[0] != "ok"]
  143. elif db_type in ("MYSQL", "MARIADB"):
  144. tables = session.execute(
  145. text(
  146. "SELECT table_name FROM information_schema.tables"
  147. " WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'"
  148. )
  149. ).fetchall()
  150. for (t,) in tables:
  151. rows = session.execute(text(f"CHECK TABLE `{t}` FAST QUICK")).fetchall()
  152. for row in rows:
  153. if row[3] not in ("OK", "note"):
  154. errors.append(f"{t}: {row[3]}")
  155. else:
  156. session.execute(text("SELECT 1"))
  157. return {
  158. "status": "success",
  159. "integrity": {
  160. "ok": not errors,
  161. "errors": errors[:10],
  162. "error_count": len(errors),
  163. },
  164. }, 200
  165. except Exception:
  166. logger.exception("Error running integrity check")
  167. return {
  168. "status": "error",
  169. "message": _("Error al ejecutar la verificación"),
  170. }, 500
  171. finally:
  172. if session:
  173. session.close()