import functools
import sqlite3


def with_connection(meth):
    """Connect to the database at the file path of a TextCache's dbname,
    try to perform the method's function, commit if successful,
    clean up if there's an error, and finally close the database."""

    @functools.wraps(meth)
    def wrapper(*args, **kwargs):
        tc = args[0]
        tc.con = sqlite3.connect(tc.dbname)
        try:
            out = meth(*args, **kwargs)
        except Exception as ex:
            tc.con.rollback()
            raise ex
        else:
            # print(f'commited transaction from method {meth} with args {args} and kwargs {kwargs}')
            tc.con.commit()
            return out
        finally:
            tc.con.close()
            tc.con = None

    return wrapper