Spaces:
Running
Running
File size: 4,444 Bytes
1b97239 |
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 |
# Standard library imports
import sqlite3
from typing import Annotated, List, Tuple, Optional
class Database:
"""
A class to interact with an SQLite database.
This class provides methods to fetch data, insert data, and handle specific
tasks like fetching or inserting topic IDs in a database.
Parameters
----------
db_path : str
The path to the SQLite database file.
Attributes
----------
db_path : str
The path to the SQLite database file.
"""
def __init__(self, db_path: Annotated[str, "Path to the SQLite database"]):
"""
Initializes the Database class with the provided database path.
Parameters
----------
db_path : str
The path to the SQLite database file.
"""
self.db_path = db_path
def fetch(
self,
sql_file_path: Annotated[str, "Path to the SQL file"]
) -> Annotated[List[Tuple], "Results fetched from the query"]:
"""
Executes a SELECT query from an SQL file and fetches the results.
Parameters
----------
sql_file_path : str
Path to the SQL file containing the SELECT query.
Returns
-------
List[Tuple]
A list of tuples representing rows returned by the query.
Examples
--------
>>> db = Database("example.db")
>>> result = db.fetch("select_query.sql")
>>> print(results)
[(1, 'data1'), (2, 'data2')]
"""
with open(sql_file_path, encoding='utf-8') as f:
query = f.read()
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(query)
results = cursor.fetchall()
conn.close()
return results
def insert(
self,
sql_file_path: Annotated[str, "Path to the SQL file"],
params: Optional[Annotated[Tuple, "Query parameters"]] = None
) -> Annotated[int, "ID of the last inserted row"]:
"""
Executes an INSERT query from an SQL file and returns the last row ID.
Parameters
----------
sql_file_path : str
Path to the SQL file containing the INSERT query.
params : tuple, optional
Parameters for the query. Defaults to None.
Returns
-------
int
The ID of the last inserted row.
Examples
--------
>>> db = Database("example.db")
>>> last_id_ = db.insert("insert_query.sql", ("value1", "value2"))
>>> print(last_id)
3
"""
with open(sql_file_path, encoding='utf-8') as f:
query = f.read()
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
if params is not None:
cursor.execute(query, params)
else:
cursor.execute(query)
conn.commit()
last_id = cursor.lastrowid
conn.close()
return last_id
def get_or_insert_topic_id(
self,
detected_topic: Annotated[str, "Topic to detect or insert"],
topics: Annotated[List[Tuple], "Existing topics with IDs"],
db_topic_insert_path: Annotated[str, "Path to the SQL file for inserting topics"]
) -> Annotated[int, "Topic ID"]:
"""
Fetches an existing topic ID or inserts a new one and returns its ID.
Parameters
----------
detected_topic : str
The topic to be detected or inserted.
topics : List[Tuple[int, str]]
A list of existing topics as (id, name) tuples.
db_topic_insert_path : str
Path to the SQL file for inserting a new topic.
Returns
-------
int
The ID of the detected or newly inserted topic.
Examples
--------
>>> db = Database("example.db")
>>> topics_ = [(1, 'Python'), (2, 'SQL')]
>>> topic_id_ = db.get_or_insert_topic_id("AI", topics, "insert_topic.sql")
>>> print(topic_id)
3
"""
detected_topic_lower = detected_topic.lower()
topic_map = {t[1].lower(): t[0] for t in topics}
if detected_topic_lower in topic_map:
return topic_map[detected_topic_lower]
else:
topic_id = self.insert(db_topic_insert_path, (detected_topic,))
return topic_id
|