import re


def copy_from(con, copy_from_sql):
    """
    To be used with a 'COPY FROM' statement.
    Calls pymapd `execute`, but parses the response to check if it failed or not.
    If it fails to do too many rejected records, raise an exception.
    If it succeeds, return a dict with loaded, rejected, and time in ms.
    """
    rs = con.execute(copy_from_sql).fetchall()
    msg = rs[0][0]
    if msg.startswith("Loaded:"):
        m = re.match(
            "Loaded: ([0-9]+) recs, Rejected: ([0-9]+) recs in ([0-9.]+) secs", msg
        )
        if m:
            return {"loaded": m[1], "rejected": m[2], "time": m[3]}
        else:
            # never seen this, but just in case
            return {"message": msg}
    elif msg.startswith("Creating ") or msg.startswith("Appending "):
        # with geo=true is not very descriptive
        return {"message": msg}
    else:
        raise Exception(str(rs))