def check_if_upgrade_needed() -> bool:
    """Check if the upgrade has already been applied."""
    connection = op.get_bind()
    inspector = inspect(connection)

    # Check if documents table exists in the correct schema
    if not inspector.has_table("documents", schema=project_name):
        logger.info(
            f"Migration not needed: '{project_name}.documents' table doesn't exist"
        )
        return False

    # Check if total_tokens column already exists
    columns = {
        col["name"]
        for col in inspector.get_columns("documents", schema=project_name)
    }

    if "total_tokens" in columns:
        logger.info(
            "Migration not needed: documents table already has total_tokens column"
        )
        return False

    logger.info("Migration needed: documents table needs total_tokens column")
    return True
Check if the upgrade has already been applied.
py/migrations/versions/3efc7b3b1b3d_add_total_tokens_count.py