4
0

admin_helpers.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import os
  2. from loguru import logger
  3. from sqlalchemy import MetaData, Table, func, select, text
  4. def load_env_vars():
  5. env_vars = {}
  6. env_file = os.path.join(os.getcwd(), ".env")
  7. if os.path.exists(env_file):
  8. with open(env_file) as f:
  9. for line in f:
  10. line = line.strip()
  11. if line and "=" in line:
  12. key, value = line.split("=", 1)
  13. env_vars[key] = value.strip('"')
  14. return env_vars
  15. def save_env_vars(env_vars):
  16. env_file = os.path.join(os.getcwd(), ".env")
  17. with open(env_file, "w") as f:
  18. for key, value in env_vars.items():
  19. f.write(f'{key}="{value}"\n')
  20. def get_table_row_count(session, engine, table_name):
  21. metadata = MetaData()
  22. table = Table(table_name, metadata, autoload_with=engine)
  23. return session.execute(select(func.count()).select_from(table)).scalar_one()
  24. def get_table_size(session, db_type, table_name):
  25. if db_type == "SQLITE":
  26. result = session.execute(
  27. text("SELECT SUM(pgsize) FROM dbstat WHERE name = :name"),
  28. {"name": table_name},
  29. )
  30. return result.scalar() or 0
  31. if db_type in ("MYSQL", "MARIADB"):
  32. result = session.execute(
  33. text("""
  34. SELECT data_length + index_length
  35. FROM information_schema.tables
  36. WHERE table_name = :name
  37. AND table_schema = DATABASE()
  38. """),
  39. {"name": table_name},
  40. )
  41. return result.scalar() or 0
  42. if db_type in ("POSTGRES", "POSTGRESQL"):
  43. result = session.execute(
  44. text("SELECT pg_total_relation_size(:name)"),
  45. {"name": table_name},
  46. )
  47. return result.scalar() or 0
  48. return 0
  49. def get_all_tables_stats(session, engine, db_type):
  50. """
  51. Return {table_name: {"rows": int, "size": int}} for all tables using
  52. a minimal number of queries (1-2 total) instead of N*2 per-table queries.
  53. MySQL/MariaDB and PostgreSQL use the engine's internal statistics so the
  54. response is near-instant regardless of database size. SQLite still needs
  55. one COUNT(*) per table but at least reuses a single reflected metadata
  56. object and batches the size query.
  57. """
  58. if db_type in ("MYSQL", "MARIADB"):
  59. result = session.execute(
  60. text("""
  61. SELECT table_name,
  62. COALESCE(table_rows, 0),
  63. COALESCE(data_length + index_length, 0)
  64. FROM information_schema.tables
  65. WHERE table_schema = DATABASE()
  66. AND table_type = 'BASE TABLE'
  67. """)
  68. )
  69. return {row[0]: {"rows": int(row[1]), "size": int(row[2])} for row in result}
  70. if db_type in ("POSTGRES", "POSTGRESQL"):
  71. result = session.execute(
  72. text("""
  73. SELECT relname,
  74. COALESCE(n_live_tup, 0),
  75. pg_total_relation_size(relid)
  76. FROM pg_stat_user_tables
  77. """)
  78. )
  79. return {row[0]: {"rows": int(row[1]), "size": int(row[2])} for row in result}
  80. if db_type == "SQLITE":
  81. # Batch-fetch all table sizes in one query
  82. try:
  83. size_rows = session.execute(
  84. text("SELECT name, COALESCE(SUM(pgsize), 0) FROM dbstat GROUP BY name")
  85. ).fetchall()
  86. sizes = {row[0]: int(row[1]) for row in size_rows}
  87. except Exception as exc:
  88. # dbstat is an optional SQLite virtual table. Some builds do not
  89. # include it; table row counts should still be available to the
  90. # admin UI, with size shown as zero when it cannot be measured.
  91. session.rollback()
  92. logger.warning(
  93. "SQLite dbstat is unavailable; table sizes will be reported as 0: {}",
  94. exc,
  95. )
  96. sizes = {}
  97. # Reflect all tables once and run COUNT(*) per table
  98. metadata = MetaData()
  99. metadata.reflect(bind=engine)
  100. stats = {}
  101. for table_name, table_obj in metadata.tables.items():
  102. try:
  103. count = session.execute(
  104. select(func.count()).select_from(table_obj)
  105. ).scalar_one()
  106. except Exception:
  107. count = 0
  108. stats[table_name] = {"rows": count, "size": sizes.get(table_name, 0)}
  109. return stats
  110. return {}