ThalamOS
a powerful Flask web application designed to enhance your storage management.
Loading...
Searching...
No Matches
Storage_connector.py
Go to the documentation of this file.
1"""
2StorageConnector Module
3
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.
7"""
8import os
9from typing import List
10from sqlmodel import Session, create_engine, select, or_, SQLModel
11from models import StorageItem, StorageItemType
12from logger_config import logger
13
14
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):
19 os.makedirs(db_dir)
20 logger.info(f"Verzeichnis erstellt: {db_dir}")
21logger.info(f"Database path: {db_path}")
22
23# SQLAlchemy Engine erstellen
24engine = create_engine(f"sqlite:///{db_path}", connect_args={"check_same_thread": False})
25
26def setup():
27 """Sets up the database by creating the necessary tables if they do not already exist."""
28 SQLModel.metadata.create_all(engine)
29
30def fetch_item(item_id: int) -> StorageItem | None:
31 """
32 Fetch an item from the storage database by its id.
33 Args:
34 item_id: The id of the item to fetch.
35 Returns:
36 The item object if found, otherwise None.
37 """
38 with Session(engine) as session:
39 return session.get(StorageItem, item_id)
40
41
42def delete_item(item_id: int) -> None:
43 """
44 Deletes an item from the storage database based on the provided item id.
45 Args:
46 item_id: The id of the item to be deleted from the storage.
47 Returns:
48 None
49 """
50 with Session(engine) as session:
51 item = session.get(StorageItem, item_id)
52 if item:
53 session.delete(item)
54 session.commit()
55 logger.info(f"Item with ID {item_id} deleted.")
56 else:
57 logger.warning(f"Deletion failed: ID {item_id} not found.")
58
59
60def create_item(pos: int, obj_type: StorageItemType, name: str, json_data: str) -> None:
61 """
62 Creates a new item in the storage database with the provided position, type, name, and JSON data.
63
64 Args:
65 pos: LED position of the item.
66 obj_type: type of the Item
67 name: name of item
68 json_data: additional json ifno
69
70 Returns:
71
72 """
73 info_value = None if json_data in ["{}", ""] else json_data
74
75 new_item = StorageItem(
76 position=pos,
77 type=obj_type,
78 name=name,
79 info=info_value
80 )
81
82 with Session(engine) as session:
83 session.add(new_item)
84 session.commit()
85 logger.info(f"Item created: {name}")
86
87def search(search_term: str) -> List[StorageItem]:
88 """
89 Searches the storage database for entries that match the given search term.
90 Args:
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
94 'info' columns.
95 Returns:
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.
98 Raises:
99 sqlite3.ProgrammingError: If there is an error executing the query.
100 """
101 with Session(engine) as session:
102 statement = select(StorageItem)
103 search_words = search_term.split()
104
105 for word in search_words:
106 pattern = f"%{word}%"
107 statement = statement.where(
108 or_(
109 StorageItem.type.like(pattern),
110 StorageItem.name.like(pattern),
111 StorageItem.info.like(pattern)
112 )
113 )
114
115 results = session.exec(statement).all()
116 return list(results)
117
118
119def update_item(item_id: int, pos: int, obj_type: StorageItemType, name: str, json_data: str) -> None:
120 """
121 Updates an item in the storage database.
122 Args:
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.
128 """
129 with Session(engine) as session:
130 db_item = session.get(StorageItem, item_id)
131 if not db_item:
132 logger.error(f"Update fehlgeschlagen: Item {item_id} nicht gefunden.")
133 return
134
135 db_item.position = pos
136 db_item.type = obj_type
137 db_item.name = name
138 db_item.info = json_data if json_data != "{}" else None
139
140 session.add(db_item)
141 session.commit()
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)