db_info_service.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. from loguru import logger
  2. from sqlalchemy import text
  3. from config import Config
  4. from database.database import get_engine, get_session
  5. from services.database.admin_helpers import get_all_tables_stats
  6. def get_tables_info():
  7. session = None
  8. try:
  9. engine = get_engine()
  10. session = get_session()
  11. db_type = Config.DATABASE_TYPE
  12. stats = get_all_tables_stats(session, engine, db_type)
  13. table_info = [
  14. {
  15. "name": table_name,
  16. "rows": info["rows"],
  17. "size": info["size"],
  18. "has_data": info["rows"] > 0,
  19. }
  20. for table_name, info in stats.items()
  21. ]
  22. return {"status": "success", "tables": table_info}, 200
  23. except Exception:
  24. logger.exception("Error getting database tables")
  25. return {"status": "error", "message": "Error interno del servidor"}, 500
  26. finally:
  27. if session:
  28. session.close()
  29. def get_db_health():
  30. """Return a health snapshot of the database.
  31. For SQLite, runs PRAGMA quick_check(1) on every call so corruption is
  32. detected automatically without the user having to click the integrity
  33. check button. The query stops after the *first* error it finds, keeping
  34. latency acceptable even on large databases.
  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. # ── Corruption probe: quick_check stops at the first bad page ──
  65. corruption = False
  66. corruption_detail = None
  67. try:
  68. qc_rows = session.execute(text("PRAGMA quick_check(1)")).fetchall()
  69. if not qc_rows or qc_rows[0][0] != "ok":
  70. corruption = True
  71. corruption_detail = (
  72. qc_rows[0][0] if qc_rows else "Sin respuesta del PRAGMA"
  73. )
  74. except Exception as qc_err:
  75. corruption = True
  76. corruption_detail = str(qc_err)
  77. health["extra"] = {
  78. "page_size": page_size,
  79. "page_count": page_count,
  80. "freelist_count": freelist_count,
  81. "journal_mode": journal_mode,
  82. "auto_vacuum": _av.get(auto_vacuum_val, str(auto_vacuum_val)),
  83. "fragmentation_pct": fragmentation_pct,
  84. "corruption": corruption,
  85. "corruption_detail": corruption_detail,
  86. }
  87. # ── Table stats (may fail on severely corrupted DBs) ──
  88. try:
  89. stats = get_all_tables_stats(session, engine, db_type)
  90. health["table_count"] = len(stats)
  91. health["total_rows"] = sum(v["rows"] for v in stats.values())
  92. except Exception:
  93. logger.warning(
  94. "Could not read SQLite table stats — database may be corrupted"
  95. )
  96. elif db_type in ("MYSQL", "MARIADB"):
  97. stats = get_all_tables_stats(session, engine, db_type)
  98. health["table_count"] = len(stats)
  99. health["total_rows"] = sum(v["rows"] for v in stats.values())
  100. size = (
  101. session.execute(
  102. text(
  103. "SELECT COALESCE(SUM(data_length + index_length), 0)"
  104. " FROM information_schema.tables WHERE table_schema = DATABASE()"
  105. )
  106. ).scalar()
  107. or 0
  108. )
  109. version = session.execute(text("SELECT VERSION()")).scalar() or "unknown"
  110. health["total_size_bytes"] = int(size)
  111. health["extra"] = {"version": version}
  112. elif db_type in ("POSTGRES", "POSTGRESQL"):
  113. stats = get_all_tables_stats(session, engine, db_type)
  114. health["table_count"] = len(stats)
  115. health["total_rows"] = sum(v["rows"] for v in stats.values())
  116. size = (
  117. session.execute(
  118. text("SELECT pg_database_size(current_database())")
  119. ).scalar()
  120. or 0
  121. )
  122. version = session.execute(text("SELECT version()")).scalar() or "unknown"
  123. health["total_size_bytes"] = int(size)
  124. health["extra"] = {"version": " ".join(version.split()[:2])}
  125. return {"status": "success", "health": health}, 200
  126. except Exception:
  127. logger.exception("Error getting DB health")
  128. return {"status": "error", "message": "Error interno del servidor"}, 500
  129. finally:
  130. if session:
  131. session.close()
  132. def run_integrity_check():
  133. """Run a quick integrity check. Uses PRAGMA quick_check for SQLite."""
  134. session = None
  135. try:
  136. session = get_session()
  137. db_type = Config.DATABASE_TYPE
  138. errors = []
  139. if db_type == "SQLITE":
  140. rows = session.execute(text("PRAGMA quick_check")).fetchall()
  141. errors = [r[0] for r in rows if r[0] != "ok"]
  142. elif db_type in ("MYSQL", "MARIADB"):
  143. tables = session.execute(
  144. text(
  145. "SELECT table_name FROM information_schema.tables"
  146. " WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'"
  147. )
  148. ).fetchall()
  149. for (t,) in tables:
  150. rows = session.execute(text(f"CHECK TABLE `{t}` FAST QUICK")).fetchall()
  151. for row in rows:
  152. if row[3] not in ("OK", "note"):
  153. errors.append(f"{t}: {row[3]}")
  154. else:
  155. session.execute(text("SELECT 1"))
  156. return {
  157. "status": "success",
  158. "integrity": {
  159. "ok": not errors,
  160. "errors": errors[:10],
  161. "error_count": len(errors),
  162. },
  163. }, 200
  164. except Exception:
  165. logger.exception("Error running integrity check")
  166. return {"status": "error", "message": "Error al ejecutar la verificación"}, 500
  167. finally:
  168. if session:
  169. session.close()