File size: 7,840 Bytes
fb95c43
 
 
 
 
fdb6484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb95c43
fdb6484
 
fb95c43
 
fdb6484
 
 
cff8370
fdb6484
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from sqlmodel import SQLModel, create_engine, Session, select
from rag_app.database.schema import Sources
from rag_app.utils.logger import get_console_logger
import os
from dotenv import load_dotenv
import uuid
from datetime import datetime


class DataBaseHandler(): 
    """
    A class for managing the database.

    Attributes:
        sqlite_file_name (str): The SQLite file name for the database.
        logger (Logger): The logger for logging database operations.
        engine (Engine): The SQLAlchemy engine for the database.

    Methods:
        create_all_tables: Create all tables in the database.
        read_one: Read a single entry from the database by its hash_id.
        add_one: Add a single entry to the database.
        update_one: Update a single entry in the database by its hash_id.
        delete_one: Delete a single entry from the database by its id.
        add_many: Add multiple entries to the database.
        delete_many: Delete multiple entries from the database by their ids.
        read_all: Read all entries from the database, optionally filtered by a query.
        delete_all: Delete all entries from the database.
    """
    
    def __init__(
        self,
        sqlite_file_name = os.getenv('SOURCES_CACHE'),
        logger = get_console_logger("db_handler"),
        # *args,
        # **kwargs,
        ):
        self.sqlite_file_name = sqlite_file_name
        self.logger = logger
        
        sqlite_url = f"sqlite:///{self.sqlite_file_name}"
        self.engine = create_engine(sqlite_url, echo=False)
        
        
        self.session_id = str(uuid.uuid4())
        self.session_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
    def create_all_tables(self) -> None:
        SQLModel.metadata.create_all(self.engine)
    
    def create_new_session(self) -> None:
        """creates a new session_id and date time
        
        """
        self.session_id = str(uuid.uuid4())
        self.session_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')


    def read_one(self,hash_id: dict):
        """
        Read a single entry from the database by its hash_id.

        Args:
            hash_id (dict): Dictionary containing the hash_id to search for.

        Returns:
            Sources: The matching entry from the database, or None if no match is found.
        """
        with Session(self.engine) as session:
            statement = select(Sources).where(Sources.hash_id == hash_id)
            sources = session.exec(statement).first()
            return sources


    def add_one(self,data: dict):
        """
        Add a single entry to the database.

        Args:
            data (dict): Dictionary containing the data for the new entry.

        Returns:
            Sources: The added entry, or None if the entry already exists.
        """
        with Session(self.engine) as session:
            if session.exec(
                select(Sources).where(Sources.hash_id == data.get("hash_id"))
            ).first():
                self.logger.warning(f"Item with hash_id {data.get('hash_id')} already exists")
                return None  # or raise an exception, or handle as needed
            sources = Sources(**data)
            session.add(sources)
            session.commit()
            session.refresh(sources)
            self.logger.info(f"Item with hash_id {data.get('hash_id')} added to the database")
            return sources


    def update_one(self,hash_id: dict, data: dict):
        """
        Update a single entry in the database by its hash_id.

        Args:
            hash_id (dict): Dictionary containing the hash_id to search for.
            data (dict): Dictionary containing the updated data for the entry.

        Returns:
            Sources: The updated entry, or None if no match is found.
        """
        with Session(self.engine) as session:
            # Check if the item with the given hash_id exists
            sources = session.exec(
                select(Sources).where(Sources.hash_id == hash_id)
            ).first()
            if not sources:
                self.logger.warning(f"No item with hash_id {hash_id} found for update")
                return None  # or raise an exception, or handle as needed
            for key, value in data.items():
                setattr(sources, key, value)
            session.commit()
            self.logger.info(f"Item with hash_id {hash_id} updated in the database")
            return sources


    def delete_one(self,id: int):
        """
        Delete a single entry from the database by its id.

        Args:
            id (int): The id of the entry to delete.

        Returns:
            None
        """
        with Session(self.engine) as session:
            # Check if the item with the given hash_id exists
            sources = session.exec(
                select(Sources).where(Sources.hash_id == id)
            ).first()
            if not sources:
                self.logger.warning(f"No item with hash_id {id} found for deletion")
                return None  # or raise an exception, or handle as needed
            session.delete(sources)
            session.commit()
            self.logger.info(f"Item with hash_id {id} deleted from the database")


    def add_many(self,data: list):
        """
        Add multiple entries to the database.

        Args:
            data (list): List of dictionaries, each containing the data for a new entry.

        Returns:
            None
        """
        with Session(self.engine) as session:
            for info in data:
                # Reuse add_one function for each item
                result = self.add_one(info)
                if result is None:
                    self.logger.warning(
                        f"Item with hash_id {info.get('hash_id')} could not be added"
                    )
                else:
                    self.logger.info(
                        f"Item with hash_id {info.get('hash_id')} added to the database"
                    )
            session.commit()  # Commit at the end of the loop


    def delete_many(self,ids: list):
        """
        Delete multiple entries from the database by their ids.

        Args:
            ids (list): List of ids of the entries to delete.

        Returns:
            None
        """
        with Session(self.engine) as session:
            for id in ids:
                # Reuse delete_one function for each item
                result = self.delete_one(id)
                if result is None:
                    self.logger.warning(f"No item with hash_id {id} found for deletion")
                else:
                    self.logger.info(f"Item with hash_id {id} deleted from the database")
            session.commit()  # Commit at the end of the loop


    def read_all(self,query: dict = None):
        """
        Read all entries from the database, optionally filtered by a query.

        Args:
            query (dict, optional): Dictionary containing the query parameters. Defaults to None.

        Returns:
            list: List of matching entries from the database.
        """
        with Session(self.engine) as session:
            statement = select(Sources)
            if query:
                statement = statement.where(
                    *[getattr(Sources, key) == value for key, value in query.items()]
                )
            sources = session.exec(statement).all()
            return sources


    def delete_all(self,):
        """
        Delete all entries from the database.

        Returns:
            None
        """
        with Session(self.engine) as session:
            session.exec(Sources).delete()
            session.commit()
            self.logger.info("All items deleted from the database")