def dvi_match_query(body_id):
    """
        Get a query for candidate matches between the missing
        persons registry and a dead body

        @param body_id: the dvi_body record ID
    """

    ptable = s3db.pr_person
    ntable = s3db.pr_note
    btable = s3db.dvi_body

    query = ((ptable.deleted == False) &
            (ptable.missing == True) &
            (ntable.pe_id == ptable.pe_id) &
            (ntable.status == 1))

    body = btable[body_id]
    if not body:
        return query

    # last seen should be before date of recovery
    if body.date_of_recovery:
        q = ((ntable.timestmp <= body.date_of_recovery) |
            (ntable.timestmp == None))
        query = query & q

    # age group should match
    if body.age_group and body.age_group != 1:
        q = ((ptable.age_group == None) |
            (ptable.age_group == 1) |
            (ptable.age_group == body.age_group))
        query = query & q

    # gender should match
    if body.gender and body.gender != 1:
        q = ((ptable.gender == None) |
            (ptable.gender == 1) |
            (ptable.gender == body.gender))

    return query

# -----------------------------------------------------------------------------
dataset/ETHPy150Open sahana/eden/controllers/dvi.py/dvi_match_query/original