import sqlite3
from contextlib import contextmanager
from typing import Iterator, Optional

from folkugat_web.config.db import DB_FILE

Connection = sqlite3.Connection


@contextmanager
def get_connection(con: Optional[Connection] = None) -> Iterator[Connection]:
    if con:
        yield con
    else:
        con = sqlite3.connect(DB_FILE)
        try:
            yield con
            con.commit()
        except Exception:
            con.rollback()
            raise
        finally:
            con.close()
