-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_handler.py
More file actions
147 lines (121 loc) · 5.34 KB
/
database_handler.py
File metadata and controls
147 lines (121 loc) · 5.34 KB
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
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, Enum, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, Session
from schemas import Email
import enum
# Configurazione del database
engine = create_engine("sqlite:///database.sqlite", echo=False, future=True)
Base = declarative_base()
class LivelloAtletico(str, enum.Enum):
AVANZATO = "AVANZATO"
INTERMEDIO = "INTERMEDIO"
PRINCIPIANTE = "PRINCIPIANTE"
class TipoDocumento(str, enum.Enum):
DIETA = "dieta"
MENTAL_COACHING = "mental coaching"
STATISTICHE = "statistiche"
SCHEDA = "scheda"
class Atleta(Base):
__tablename__ = "atleti"
id = Column(Integer, primary_key=True, autoincrement=True)
codice_fiscale = Column(String, unique=True, nullable=False)
nome = Column(String, nullable=False)
cognome = Column(String, nullable=False)
email = Column(String, unique=True, nullable=False)
telefono = Column(String, nullable=False)
livello = Column(Enum(LivelloAtletico), nullable=False)
documenti = relationship("Documento", back_populates="atleta", cascade="all, delete-orphan")
class Documento(Base):
__tablename__ = "documenti"
id = Column(Integer, primary_key=True, autoincrement=True)
atleta_id = Column(Integer, ForeignKey("atleti.id"), nullable=False)
tipo = Column(Enum(TipoDocumento), nullable=False)
titolo = Column(String, nullable=False)
contenuto = Column(Text, nullable=False)
creato_il = Column(DateTime, default=datetime.utcnow, nullable=False)
atleta = relationship("Atleta", back_populates="documenti")
Base.metadata.create_all(engine)
def save_email_as_document(email: Email, tipo: TipoDocumento, atleta_id: int):
"""Salva un'email come documento nel database."""
with Session(engine) as session:
doc = Documento(atleta_id=atleta_id, tipo=tipo, titolo=email.object, contenuto=email.content)
session.add(doc)
session.commit()
def get_last_document_as_email(atleta_id: int, tipo: TipoDocumento) -> Email:
"""Ottiene l'ultimo documento di un determinato tipo per un atleta e lo restituisce come Email."""
with Session(engine) as session:
doc = (session.query(Documento)
.filter_by(atleta_id=atleta_id, tipo=tipo)
.order_by(Documento.creato_il.desc())
.first())
return Email(object=doc.titolo, content=doc.contenuto) if doc else None
def get_email_by_atleta_id(atleta_id: int) -> str:
"""Ottiene l'email di un atleta dato il suo ID."""
with Session(engine) as session:
atleta = session.get(Atleta, atleta_id)
return atleta.email if atleta else None
def get_all_atleti():
"""Ottiene tutti gli atleti dal database."""
with Session(engine) as session:
return session.query(Atleta).all()
def get_atleta_by_id(atleta_id: int):
"""Ottiene un atleta per ID."""
with Session(engine) as session:
return session.get(Atleta, atleta_id)
def get_documenti_by_atleta_id(atleta_id: int):
"""Ottiene tutti i documenti di un atleta."""
with Session(engine) as session:
return session.query(Documento).filter_by(atleta_id=atleta_id).order_by(Documento.creato_il.desc()).all()
def add_atleta(codice_fiscale: str, nome: str, cognome: str, email: str, telefono: str, livello: LivelloAtletico):
"""Aggiunge un nuovo atleta al database."""
with Session(engine) as session:
atleta = Atleta(
codice_fiscale=codice_fiscale,
nome=nome,
cognome=cognome,
email=email,
telefono=telefono,
livello=livello
)
session.add(atleta)
session.commit()
return atleta.id
def get_documento_by_id(documento_id: int):
"""Ottiene un documento per ID."""
with Session(engine) as session:
return session.get(Documento, documento_id)
def update_atleta(atleta_id: int, **kwargs):
"""Aggiorna i dati di un atleta."""
with Session(engine) as session:
atleta = session.get(Atleta, atleta_id)
if not atleta:
raise ValueError(f"Atleta con ID {atleta_id} non trovato")
# Aggiorna solo i campi forniti
for field, value in kwargs.items():
if hasattr(atleta, field):
if field == 'livello' and isinstance(value, str):
value = LivelloAtletico(value)
setattr(atleta, field, value)
session.commit()
return atleta
def delete_atleta(atleta_id: int):
"""Elimina un atleta e tutti i suoi documenti."""
with Session(engine) as session:
atleta = session.get(Atleta, atleta_id)
if not atleta:
raise ValueError(f"Atleta con ID {atleta_id} non trovato")
session.delete(atleta)
session.commit()
def update_documento_status(documento_id: int, inviato: bool = True):
"""Aggiorna lo status di invio di un documento."""
# Per ora non implementiamo il campo inviato nel database
# ma possiamo estendere in futuro
pass
def delete_documento(documento_id: int):
"""Elimina un documento."""
with Session(engine) as session:
documento = session.get(Documento, documento_id)
if not documento:
raise ValueError(f"Documento con ID {documento_id} non trovato")
session.delete(documento)
session.commit()