from typing import Dict
from typing import List


def check_entry_exists(session, entry: Dict, schema_name: str, table: str) -> List[int]:
    """Queries target database for a matching entry.

    Generates query dynamically according to the given metadata entry.
    A downside of this approach is that the index is not utilized, so query
    performance may be comparably bad.

    On the positive side, it will follow the defined schema, as given in the
    metadata, so the query automatically adjusts as the schema spec changes.

    Parameters
    ----------
    session : SQLAlchemy session object
    entry : dict, metadata entry
    schema_name : str, name of schema
    table : str, name of table in schema to query

    Returns
    ----------
    List, of matching IDs
    """
    schema_def = f"{schema_name}.{table}"

    code = f"from .schema import {schema_name}\n\n"

    code += f"check = session.query({schema_def}.id).filter(\n"
    for k, v in entry.items():
        if k == "the_geom":
            # ignore geometry fields
            continue

        if isinstance(v, str):
            if (v.lower() not in ["true", "false"]):
                v = f"'{v}'"
            else:
                code += f"{schema_def}.{k}.is_({bool(v)}),\n"
        else:
            code += f"{schema_def}.{k} == {v},\n"


    code += ')'

    code_obj = compile(code, 'check_entry', 'exec')
    l = locals()
    exec(code_obj, globals(), l)

    check = l['check']

    return check.all()