-
Notifications
You must be signed in to change notification settings - Fork 2
/
db.py
49 lines (36 loc) · 1.22 KB
/
db.py
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
from sqlalchemy import desc
from sqlmodel import Session, SQLModel, create_engine
from models import Translation
DATABASE_URL = "sqlite:///translations.db"
engine = create_engine(DATABASE_URL)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def store_translation(text: str, destination: str, translated_text: str):
with Session(engine) as session:
translation = Translation(
text=text,
destination_language=destination,
translated_text=translated_text,
)
session.add(translation)
session.commit()
def retrieve_translations(dest_language: str):
with Session(engine) as session:
translations = (
session.query(Translation)
.filter_by(destination_language=dest_language)
.order_by(desc(Translation.query_datetime))
.all()
)
return translations
def clear_translations(dest_language: str):
with Session(engine) as session:
result = (
session.query(Translation)
.filter_by(destination_language=dest_language)
.delete()
)
session.commit()
return result
if __name__ == "__main__":
create_db_and_tables()