init_db.py 1.1 KB

123456789101112131415161718192021222324252627282930
  1. """Initialize database and create tables."""
  2. import os
  3. from app import create_app, db
  4. from app.services.admin_service import AdminService
  5. def init_database():
  6. """Initialize database with tables and default admin."""
  7. config_name = os.environ.get('FLASK_CONFIG', 'production')
  8. app = create_app(config_name)
  9. with app.app_context():
  10. # Create all tables
  11. db.create_all()
  12. print("Database tables created successfully.")
  13. # Create default admin if not exists
  14. created, message = AdminService.create_default_admin()
  15. print(message)
  16. # Create indexes for name columns (if not exists)
  17. try:
  18. db.session.execute(db.text('CREATE INDEX IF NOT EXISTS ix_persons_name ON persons(name)'))
  19. db.session.execute(db.text('CREATE INDEX IF NOT EXISTS ix_items_name ON items(name)'))
  20. db.session.commit()
  21. print("Indexes created successfully.")
  22. except Exception as e:
  23. print(f"Index creation skipped: {e}")
  24. if __name__ == '__main__':
  25. init_database()