# Path: virtool/db/utils.py
# @asynccontextmanager
# async def buffered_bulk_writer(collection, batch_size=100):
#     """
#     A context manager for bulk writing to MongoDB.
# 
#     Returns a :class:``BufferedBulkWriter`` object. Automatically flushes the buffer
#     when the context manager exits.
# 
#     :param collection: the MongoDB collection to write against
#     :param batch_size: the number of requests to be sent in each bulk operation
# 
#     """
#     writer = BufferedBulkWriter(collection, batch_size)
# 
#     try:
#         yield writer
#     finally:
#         await writer.flush()


from pymongo import UpdateOne
from virtool.db.utils import buffered_bulk_writer
import virtool.db.migrate
import virtool.db.migrate_shared
import virtool.db.utils
import virtool.types



async def migrate_analyses(app: virtool.types.App):
    """
    Delete unready analyses.

    :param app: the application object

    """
    await virtool.db.utils.delete_unready(app["db"].analyses)
    await virtool.db.migrate_shared.add_subtractions_field(app["db"].analyses)
    await nest_results(app["db"])


async def nest_results(db):
    """
    Move the ``subtracted_count`` and ``read_count`` fields from the document to the ``results`` subdocument.

    This supports the new jobs API model where only a ``results`` field can be set on the analysis document by a
    workflow job.

    :param db: the application database object

    """

# Path: virtool/db/utils.py
# @asynccontextmanager
# async def buffered_bulk_writer(collection, batch_size=100):
#     """
#     A context manager for bulk writing to MongoDB.
# 
#     Returns a :class:``BufferedBulkWriter`` object. Automatically flushes the buffer
#     when the context manager exits.
# 
#     :param collection: the MongoDB collection to write against
#     :param batch_size: the number of requests to be sent in each bulk operation
# 
#     """
#     writer = BufferedBulkWriter(collection, batch_size)
# 
#     try:
#         yield writer
#     finally:
#         await writer.flush()


# Path: virtool/analyses/migrate.py
from pymongo import UpdateOne
from virtool.db.utils import buffered_bulk_writer
import virtool.db.migrate
import virtool.db.migrate_shared
import virtool.db.utils
import virtool.types




async def migrate_analyses(app: virtool.types.App):
    """
    Delete unready analyses.

    :param app: the application object

    """
    await virtool.db.utils.delete_unready(app["db"].analyses)
    await virtool.db.migrate_shared.add_subtractions_field(app["db"].analyses)
    await nest_results(app["db"])


async def nest_results(db):
    """
    Move the ``subtracted_count`` and ``read_count`` fields from the document to the ``results`` subdocument.

    This supports the new jobs API model where only a ``results`` field can be set on the analysis document by a
    workflow job.

    :param db: the application database object

    """

    async with buffered_bulk_writer(db.analyses) as writer: