Files
burmddit/backend/init_db.py

143 lines
4.4 KiB
Python

#!/usr/bin/env python3
# Database initialization script
import sys
import os
from loguru import logger
import database
import config
def init_database():
"""Initialize database with schema"""
logger.info("Initializing Burmddit database...")
# Check if DATABASE_URL is set
if not config.DATABASE_URL:
logger.error("DATABASE_URL not set!")
logger.error("Please set it in .env file or environment")
return False
logger.info(f"Connecting to database: {config.DATABASE_URL[:30]}...")
try:
# Read and execute schema
schema_path = os.path.join(os.path.dirname(__file__), '..', 'database', 'schema.sql')
with open(schema_path, 'r') as f:
schema_sql = f.read()
with database.get_db_connection() as conn:
with conn.cursor() as cur:
cur.execute(schema_sql)
logger.info("✅ Database schema created successfully!")
# Verify tables exist
with database.get_db_connection() as conn:
with conn.cursor() as cur:
cur.execute("""
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
""")
tables = cur.fetchall()
logger.info(f"Created {len(tables)} tables:")
for table in tables:
logger.info(f" - {table[0]}")
# Check categories
categories = database.get_all_categories()
logger.info(f"\n{len(categories)} categories created:")
for cat in categories:
logger.info(f" - {cat['name']} ({cat['name_burmese']})")
logger.info("\n🎉 Database initialization complete!")
return True
except FileNotFoundError:
logger.error(f"Schema file not found at: {schema_path}")
return False
except Exception as e:
logger.error(f"Error initializing database: {e}")
import traceback
logger.error(traceback.format_exc())
return False
def reset_database():
"""Reset database (DANGEROUS - deletes all data!)"""
logger.warning("⚠️ RESETTING DATABASE - ALL DATA WILL BE LOST!")
confirm = input("Type 'YES DELETE EVERYTHING' to confirm: ")
if confirm != 'YES DELETE EVERYTHING':
logger.info("Reset cancelled.")
return False
try:
with database.get_db_connection() as conn:
with conn.cursor() as cur:
# Drop all tables
cur.execute("""
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;
""")
logger.info("✅ Database reset complete")
# Reinitialize
return init_database()
except Exception as e:
logger.error(f"Error resetting database: {e}")
return False
def show_stats():
"""Show database statistics"""
try:
stats = database.get_site_stats()
logger.info("\n📊 DATABASE STATISTICS")
logger.info("=" * 40)
logger.info(f"Total articles: {stats['total_articles']}")
logger.info(f"Total views: {stats['total_views']}")
logger.info(f"Active subscribers: {stats['subscribers']}")
logger.info(f"Articles today: {stats['articles_today']}")
logger.info("=" * 40)
# Get recent articles
recent = database.get_recent_articles(5)
logger.info(f"\n📰 RECENT ARTICLES ({len(recent)}):")
for article in recent:
logger.info(f" - {article['title_burmese'][:50]}...")
return True
except Exception as e:
logger.error(f"Error fetching stats: {e}")
return False
def main():
"""Main CLI"""
import argparse
parser = argparse.ArgumentParser(description='Burmddit Database Management')
parser.add_argument('command', choices=['init', 'reset', 'stats'],
help='Command to execute')
args = parser.parse_args()
if args.command == 'init':
success = init_database()
elif args.command == 'reset':
success = reset_database()
elif args.command == 'stats':
success = show_stats()
sys.exit(0 if success else 1)
if __name__ == '__main__':
main()