admin_helpers.py 3.9 KB

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