# Path: animanager/sqlite/utils.py
# def upsert(db, table, key_cols, update_dict):
#     """Fabled upsert for SQLiteDB.
# 
#     Perform an upsert based on primary key.
# 
#     :param SQLiteDB db: database
#     :param str table: table to upsert into
#     :param str key_cols: name of key columns
#     :param dict update_dict: key-value pairs to upsert
# 
#     """
#     with db:
#         cur = db.cursor()
#         cur.execute(
#             'UPDATE {} SET {} WHERE {}'.format(
#                 table,
#                 ','.join(_sqlpformat(col) for col in update_dict.keys()),
#                 ' AND '.join(_sqlpformat(col) for col in key_cols),
#             ),
#             update_dict,
#         )
#         if db.changes() == 0:
#             keys, values = zip(*update_dict.items())
#             cur.execute(
#                 'INSERT INTO {} ({}) VALUES ({})'.format(
#                     table,
#                     ','.join(keys),
#                     ','.join('?' for _ in values)),
#                 values)
# 
# Path: animanager/db/query/eptype.py
# def get_eptype(db, name):
#     """Get episode type by name or id."""
#     return EpisodeTypes.from_db(db)[name]


from typing import Any, Iterator
from animanager.sqlite.utils import upsert
from .eptype import get_eptype
}


def cache_status(db, aid, force=False):
    """Calculate and cache status for given anime.

    Don't do anything if status already exists and force is False.

    """
    with db:
        cur = db.cursor()
        if not force:
            # We don't do anything if we already have this aid in our
            # cache.
            cur.execute('SELECT 1 FROM cache_anime WHERE aid=?', (aid,))
            if cur.fetchone() is not None:
                return

        # Retrieve information for determining complete.
        cur.execute(
            'SELECT episodecount, enddate FROM anime WHERE aid=?', (aid,))
        row = cur.fetchone()
        if row is None:
            raise ValueError('aid provided does not exist')
        episodecount, enddate = row

        # Select all regular episodes in ascending order.
        cur.execute("""
            SELECT number, user_watched FROM episode
            WHERE aid=? AND type=?

# Path: animanager/sqlite/utils.py
# def upsert(db, table, key_cols, update_dict):
#     """Fabled upsert for SQLiteDB.
# 
#     Perform an upsert based on primary key.
# 
#     :param SQLiteDB db: database
#     :param str table: table to upsert into
#     :param str key_cols: name of key columns
#     :param dict update_dict: key-value pairs to upsert
# 
#     """
#     with db:
#         cur = db.cursor()
#         cur.execute(
#             'UPDATE {} SET {} WHERE {}'.format(
#                 table,
#                 ','.join(_sqlpformat(col) for col in update_dict.keys()),
#                 ' AND '.join(_sqlpformat(col) for col in key_cols),
#             ),
#             update_dict,
#         )
#         if db.changes() == 0:
#             keys, values = zip(*update_dict.items())
#             cur.execute(
#                 'INSERT INTO {} ({}) VALUES ({})'.format(
#                     table,
#                     ','.join(keys),
#                     ','.join('?' for _ in values)),
#                 values)
# 
# Path: animanager/db/query/eptype.py
# def get_eptype(db, name):
#     """Get episode type by name or id."""
#     return EpisodeTypes.from_db(db)[name]


# Path: animanager/db/query/status.py
from typing import Any, Iterator
from animanager.sqlite.utils import upsert
from .eptype import get_eptype

}


def cache_status(db, aid, force=False):
    """Calculate and cache status for given anime.

    Don't do anything if status already exists and force is False.

    """
    with db:
        cur = db.cursor()
        if not force:
            # We don't do anything if we already have this aid in our
            # cache.
            cur.execute('SELECT 1 FROM cache_anime WHERE aid=?', (aid,))
            if cur.fetchone() is not None:
                return

        # Retrieve information for determining complete.
        cur.execute(
            'SELECT episodecount, enddate FROM anime WHERE aid=?', (aid,))
        row = cur.fetchone()
        if row is None:
            raise ValueError('aid provided does not exist')
        episodecount, enddate = row

        # Select all regular episodes in ascending order.
        cur.execute("""
            SELECT number, user_watched FROM episode
            WHERE aid=? AND type=?

            ORDER BY number ASC