From 244102c291e419eb5e1fbe704b694c04ae490564 Mon Sep 17 00:00:00 2001 From: norohind <60548839+norohind@users.noreply.github.com> Date: Sun, 10 Apr 2022 23:43:31 +0300 Subject: [PATCH] Hook.py: add get_db() as method of Hook class --- Hook.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Hook.py b/Hook.py index 0ac0a79..9a2e609 100644 --- a/Hook.py +++ b/Hook.py @@ -1,4 +1,6 @@ +import sqlite3 from abc import ABC, abstractmethod +import os class Hook(ABC): # See at Hook class as to observer in observer pattern @@ -9,3 +11,19 @@ class Hook(ABC): # See at Hook class as to observer in observer pattern @abstractmethod def update(self, operation_id: int) -> None: raise NotImplemented + + @staticmethod + def get_db() -> sqlite3.Connection: + """ + One connection per request is only one method to avoid sqlite3.DatabaseError: database disk image is malformed. + Connections in sqlite are extremely cheap (0.22151980000001004 secs for 1000 just connections and + 0.24141229999999325 secs for 1000 connections for this getter, thanks timeit) + and don't require to be closed, especially in RO mode. So, why not? + + :return: + """ + + db = sqlite3.connect(f'file:{os.environ["DB_PATH"]}?mode=ro', check_same_thread=False, uri=True) + db.row_factory = lambda c, r: dict(zip([col[0] for col in c.description], r)) + + return db