# Buggy code
def lookup_series(name=None, tvdb_id=None, only_cached=False, session=None):
    """
    Look up information on a series. Will be returned from cache if available, and looked up online and cached if not.

    Either `name` or `tvdb_id` parameter are needed to specify the series.
    :param unicode name: Name of series.
    :param int tvdb_id: TVDb ID of series.
    :param bool only_cached: If True, will not cause an online lookup. LookupError will be raised if not available
        in the cache.
    :param session: An sqlalchemy session to be used to lookup and store to cache. Commit(s) may occur when passing in
        a session. If one is not supplied it will be created.

    :return: Instance of :class:`TVDBSeries` populated with series information. If session was not supplied, this will
        be a detached from the database, so relationships cannot be loaded.
    :raises: :class:`LookupError` if series cannot be looked up.
    """
    if not (name or tvdb_id):
        raise LookupError("No criteria specified for tvdb lookup")

    log.debug("Looking up tvdb information for %s %s", name, tvdb_id)

    series = None

    def id_str():
        return "<name=%s,tvdb_id=%s>" % (name, tvdb_id)

    if tvdb_id:
        series = session.query(TVDBSeries).filter(TVDBSeries.id == tvdb_id).first()
    if not series and name:
        found = (
            session.query(TVDBSearchResult)
            .filter(func.lower(TVDBSearchResult.search) == name.lower())
            .first()
        )
        if found and found.series:
            series = found.series
    if series:
        # Series found in cache, update if cache has expired.
        if not only_cached:
            mark_expired(session=session)
        if not only_cached and series.expired:
            log.verbose("Data for %s has expired, refreshing from tvdb", series.name)
            try:
                series.update()
            except LookupError as e:
                log.warning(
                    "Error while updating from tvdb (%s), using cached data.", e.args[0]
                )
        else:
            log.debug("Series %s information restored from cache." % id_str())
    else:
        if only_cached:
            raise LookupError("Series %s not found from cache" % id_str())
        # There was no series found in the cache, do a lookup from tvdb
        log.debug("Series %s not found in cache, looking up from tvdb.", id_str())
        if tvdb_id:
            series = TVDBSeries(id=tvdb_id)
            series.update()
            if series.name:
                session.merge(series)
        elif name:
            tvdb_id = find_series_id(name)
            if tvdb_id:
                series = (
                    session.query(TVDBSeries).filter(TVDBSeries.id == tvdb_id).first()
                )
                if not series:
                    series = TVDBSeries()
                    series.id = tvdb_id
                    series.update()
                    session.merge(series)

                # Add search result to cache
                search_result = (
                    session.query(TVDBSearchResult)
                    .filter(func.lower(TVDBSearchResult.search) == name.lower())
                    .first()
                )
                if not search_result:
                    search_result = TVDBSearchResult(search=name.lower())
                    search_result.series_id = tvdb_id
                    session.add(search_result)

    if not series:
        raise LookupError("No results found from tvdb for %s" % id_str())
    if not series.name:
        raise LookupError("Tvdb result for series does not have a title.")

    return series


# Traceback (FlushError)
2016-04-01 21:04 INFO     download      tv_shows        Downloading: Sleepy.Hollow.S03E17.720p.HDTV.x264-AVS
2016-04-01 21:04 ERROR    api_tvdb      tv_shows        Could not get update information from tvdb: 404 Client Error: Not Found for url: https://api-beta.thetvdb.com/updated/query?fromTime=1459529228
2016-04-01 21:04 ERROR    lazy_lookup   tv_shows        Unhandled error in lazy lookup plugin
2016-04-01 21:04 CRITICAL manager       tv_shows        An unexpected crash has occurred. Writing crash report to /home/pi/.flexget/crash_report.2016.04.01.210426572780.log. Please verify you are running the latest version of flexget by using "flexget -V" from CLI or by using version_checker plugin at http://flexget.com/wiki/Plugins/version_checker. You are currently using version 1.2.499
2016-04-01 21:04 ERROR    lazy_lookup   tv_shows        Unhandled error in lazy lookup plugin
2016-04-01 21:04 CRITICAL manager       tv_shows        An unexpected crash has occurred. Writing crash report to /home/pi/.flexget/crash_report.2016.04.01.210427914486.log. Please verify you are running the latest version of flexget by using "flexget -V" from CLI or by using version_checker plugin at http://flexget.com/wiki/Plugins/version_checker. You are currently using version 1.2.499
2016-04-01 21:04 INFO     transmission  tv_shows        "Sleepy.Hollow.S03E17.720p.HDTV.x264-AVS" torrent added to transmission
2016-04-01 21:04 ERROR    lazy_lookup   tv_shows        Unhandled error in lazy lookup plugin
2016-04-01 21:04 CRITICAL manager       tv_shows        An unexpected crash has occurred. Writing crash report to /home/pi/.flexget/crash_report.2016.04.01.210434515925.log. Please verify you are running the latest version of flexget by using "flexget -V" from CLI or by using version_checker plugin at http://flexget.com/wiki/Plugins/version_checker. You are currently using version 1.2.499
2016-04-01 21:04 ERROR    lazy_lookup   tv_shows        Unhandled error in lazy lookup plugin
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flexget/utils/lazy_dict.py", line 36, in __getitem__
func(self.store)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/metainfo/thetvdb_lookup.py", line 115, in lazy_series_poster_lookup
return self.series_lookup(entry, self.series_poster_map)
File "/usr/local/lib/python2.7/dist-packages/flexget/utils/database.py", line 30, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flexget/utils/sqlalchemy_utils.py", line 137, in __exit__
self.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 801, in commit
self.transaction.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 392, in commit
self._prepare_impl()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 372, in _prepare_impl
self.session.flush()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2019, in flush
self._flush(objects)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2137, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2101, in _flush
flush_context.execute()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 373, in execute
rec.execute(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 532, in execute
uow
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 149, in save_obj
base_mapper, states, uowtransaction
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 301, in _organize_states_for_save
state_str(existing)))
FlushError: New instance <TVDBGenre at 0x68f50970> with identity key (<class 'flexget.plugins.api_tvdb.TVDBGenre'>, (4,)) conflicts with persistent instance <TVDBGenre at 0x68f433d0>

# Fixed code
def lookup_series(name=None, tvdb_id=None, only_cached=False, session=None):
    """
    Look up information on a series. Will be returned from cache if available, and looked up online and cached if not.

    Either `name` or `tvdb_id` parameter are needed to specify the series.
    :param unicode name: Name of series.
    :param int tvdb_id: TVDb ID of series.
    :param bool only_cached: If True, will not cause an online lookup. LookupError will be raised if not available
        in the cache.
    :param session: An sqlalchemy session to be used to lookup and store to cache. Commit(s) may occur when passing in
        a session. If one is not supplied it will be created.

    :return: Instance of :class:`TVDBSeries` populated with series information. If session was not supplied, this will
        be a detached from the database, so relationships cannot be loaded.
    :raises: :class:`LookupError` if series cannot be looked up.
    """
    if not (name or tvdb_id):
        raise LookupError("No criteria specified for tvdb lookup")

    log.debug("Looking up tvdb information for %s %s", name, tvdb_id)

    series = None

    def id_str():
        return "<name=%s,tvdb_id=%s>" % (name, tvdb_id)

    if tvdb_id:
        series = session.query(TVDBSeries).filter(TVDBSeries.id == tvdb_id).first()
    if not series and name:
        found = (
            session.query(TVDBSearchResult)
            .filter(func.lower(TVDBSearchResult.search) == name.lower())
            .first()
        )
        if found and found.series:
            series = found.series
    if series:
        # Series found in cache, update if cache has expired.
        if not only_cached:
            mark_expired(session=session)
        if not only_cached and series.expired:
            log.verbose("Data for %s has expired, refreshing from tvdb", series.name)
            try:
                updated_series = TVDBSeries(id=series.id)
                series = session.merge(updated_series)
                _update_search_strings(series, search=name)
            except LookupError as e:
                log.warning(
                    "Error while updating from tvdb (%s), using cached data.", e.args[0]
                )
        else:
            log.debug("Series %s information restored from cache." % id_str())
    else:
        if only_cached:
            raise LookupError("Series %s not found from cache" % id_str())
        # There was no series found in the cache, do a lookup from tvdb
        log.debug("Series %s not found in cache, looking up from tvdb.", id_str())
        if tvdb_id:
            series = session.merge(TVDBSeries(id=tvdb_id))
            _update_search_strings(series, search=name)
        elif name:
            tvdb_id = find_series_id(name)
            if tvdb_id:
                series = (
                    session.query(TVDBSeries).filter(TVDBSeries.id == tvdb_id).first()
                )
                if not series:
                    series = session.merge(TVDBSeries(tvdb_id))
                    _update_search_strings(series, search=name)

    if not series:
        raise LookupError("No results found from tvdb for %s" % id_str())
    if not series.name:
        raise LookupError("Tvdb result for series does not have a title.")

    return series