4This module provides functions to interact with a SQLite database for managing storage items.
5It includes functionalities to set up the database, create, fetch, delete, and search items,
6as well as export the data to a CSV file.
10from sqlmodel
import Session, create_engine, select, or_, SQLModel
11from models
import StorageItem, StorageItemType
12from logger_config
import logger
15base_dir = os.path.dirname(__file__)
16db_dir = os.path.join(base_dir,
"data")
17db_path = os.path.join(db_dir,
"storage.db")
18if not os.path.exists(db_dir):
20 logger.info(f
"Verzeichnis erstellt: {db_dir}")
21logger.info(f
"Database path: {db_path}")
24engine = create_engine(f
"sqlite:///{db_path}", connect_args={
"check_same_thread":
False})
27 """Sets up the database by creating the necessary tables if they do not already exist."""
28 SQLModel.metadata.create_all(engine)
32 Fetch an item from the storage database by its id.
34 item_id: The id of the item to fetch.
36 The item object if found, otherwise None.
38 with Session(engine)
as session:
39 return session.get(StorageItem, item_id)
44 Deletes an item from the storage database based on the provided item id.
46 item_id: The id of the item to be deleted from the storage.
50 with Session(engine)
as session:
51 item = session.get(StorageItem, item_id)
55 logger.info(f
"Item with ID {item_id} deleted.")
57 logger.warning(f
"Deletion failed: ID {item_id} not found.")
60def create_item(pos: int, obj_type: StorageItemType, name: str, json_data: str) ->
None:
62 Creates a new item in the storage database with the provided position, type, name, and JSON data.
65 pos: LED position of the item.
66 obj_type: type of the Item
68 json_data: additional json ifno
73 info_value =
None if json_data
in [
"{}",
""]
else json_data
82 with Session(engine)
as session:
85 logger.info(f
"Item created: {name}")
87def search(search_term: str) -> List[StorageItem]:
89 Searches the storage database for entries that match the given search term.
91 search_term: The term to search for in the database. The term will be split
92 into individual words,
93 and each word will be used to search the 'type', 'name', and
96 A list of tuples containing the rows from the database that match the search criteria.
97 Returns None if there is an SQLite programming error.
99 sqlite3.ProgrammingError: If there is an error executing the query.
101 with Session(engine)
as session:
102 statement = select(StorageItem)
103 search_words = search_term.split()
105 for word
in search_words:
106 pattern = f
"%{word}%"
107 statement = statement.where(
109 StorageItem.type.like(pattern),
110 StorageItem.name.like(pattern),
111 StorageItem.info.like(pattern)
115 results = session.exec(statement).all()
119def update_item(item_id: int, pos: int, obj_type: StorageItemType, name: str, json_data: str) ->
None:
121 Updates an item in the storage database.
123 item_id: The id of the item to update.
124 pos: The new position of the item.
125 obj_type: The new type of the item.
126 name: The new name of the item.
127 json_data: The new JSON data associated with the item.
129 with Session(engine)
as session:
130 db_item = session.get(StorageItem, item_id)
132 logger.error(f
"Update fehlgeschlagen: Item {item_id} nicht gefunden.")
135 db_item.position = pos
136 db_item.type = obj_type
138 db_item.info = json_data
if json_data !=
"{}" else None
142 session.refresh(db_item)
143 logger.info(f
"Item {item_id} erfolgreich aktualisiert.")
List[StorageItem] search(str search_term)
StorageItem|None fetch_item(int item_id)
None update_item(int item_id, int pos, StorageItemType obj_type, str name, str json_data)
None create_item(int pos, StorageItemType obj_type, str name, str json_data)
None delete_item(int item_id)