def domains(db, domain=None, top=False):
    doms = []
    with db.connect() as session:
        if domain:
            dom = find_domain(session, domain)
            if not dom:
                if not top:
                    raise NotFoundError(entity=domain)
                else:
                    add_dot = lambda d: '.' + d if not d.startswith('.') else d
                    d = add_dot(domain)
                    tops = session.query(Domain).\
                        filter(Domain.is_top_domain).order_by(Domain.domain).all()
                    doms = [t for t in tops
                            if d.endswith(add_dot(t.domain))]
                    if not doms:
                        raise NotFoundError(entity=domain)
            else:
                doms = [dom]
        else:
            query = session.query(Domain)
            if top:
                query = query.filter(Domain.is_top_domain)
            doms = query.order_by(Domain.domain).all()
        session.expunge_all()
    return doms