import sqlite3
from datetime import datetime
class UrgenciasDB:
def __init__(self, db_name=':memory:'):
self.conn = sqlite3.connect(db_name)
self.cursor = self.conn.cursor()
self.create_tables()
self.inserir_dados_exemplo()
def create_tables(self):
"""Cria as tabelas necessárias no banco de dados"""
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS UTENTE (
nr_utente INTEGER PRIMARY KEY,
sexo TEXT,
localidade TEXT,
idade INTEGER
)
''')
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS HOSPITAL (
nome TEXT PRIMARY KEY,
localizacao TEXT
)
''')
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS EPISODIO_URGENCIA (
cod_episodio INTEGER PRIMARY KEY,
data_hora_entrada TEXT,
data_hora_saida TEXT,
nr_utente INTEGER,
nome_hospital TEXT,
FOREIGN KEY (nr_utente) REFERENCES UTENTE(nr_utente),
FOREIGN KEY (nome_hospital) REFERENCES HOSPITAL(nome)
)
''')
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS FUNCIONARIO (
nr_funcionario INTEGER PRIMARY KEY,
sexo TEXT,
tipo TEXT CHECK (tipo IN ('Médico', 'Enfermeiro')),
eh_estagiario INTEGER
)
''')
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS ATO_MEDICO (
id_ato INTEGER PRIMARY KEY,
data_hora_inicio TEXT,
data_hora_fim TEXT,
tipo TEXT CHECK (tipo IN ('Triagem', 'Consulta', 'Exame')),
cod_episodio INTEGER,
FOREIGN KEY (cod_episodio) REFERENCES EPISODIO_URGENCIA(cod_episodio)
)
''')
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS PRESCRICAO (
id_prescricao INTEGER PRIMARY KEY,
id_ato INTEGER,
nr_medico INTEGER,
data_hora_prescricao TEXT,
FOREIGN KEY (id_ato) REFERENCES ATO_MEDICO(id_ato),
FOREIGN KEY (nr_medico) REFERENCES FUNCIONARIO(nr_funcionario)
)
''')
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS PARTICIPACAO_ATO (
id_participacao INTEGER PRIMARY KEY,
id_ato INTEGER,
nr_funcionario INTEGER,
tipo_participacao TEXT,
FOREIGN KEY (id_ato) REFERENCES ATO_MEDICO(id_ato),
FOREIGN KEY (nr_funcionario) REFERENCES FUNCIONARIO(nr_funcionario)
)
''')
self.conn.commit()
def inserir_dados_exemplo(self):
"""Insere dados de exemplo para demonstração"""
# Inserir utentes
self.cursor.execute("INSERT OR IGNORE INTO UTENTE VALUES (1, 'M', 'Lisboa', 30)")
self.cursor.execute("INSERT OR IGNORE INTO UTENTE VALUES (2, 'F', 'Porto', 45)")
# Inserir hospitais
self.cursor.execute("INSERT OR IGNORE INTO HOSPITAL VALUES ('Hospital Central', 'Lisboa')")
self.cursor.execute("INSERT OR IGNORE INTO HOSPITAL VALUES ('Hospital São João', 'Porto')")
# Inserir funcionários
self.cursor.execute("INSERT OR IGNORE INTO FUNCIONARIO VALUES (101, 'M', 'Médico', 0)")
self.cursor.execute("INSERT OR IGNORE INTO FUNCIONARIO VALUES (102, 'F', 'Enfermeiro', NULL)")
# Inserir episódios de urgência
self.cursor.execute('''
INSERT OR IGNORE INTO EPISODIO_URGENCIA
VALUES (1001, '2023-01-01 08:00:00', NULL, 1, 'Hospital Central')
''')
self.cursor.execute('''
INSERT OR IGNORE INTO EPISODIO_URGENCIA
VALUES (1002, '2023-01-02 09:30:00', NULL, 2, 'Hospital São João')
''')
# Inserir atos médicos
self.cursor.execute('''
INSERT OR IGNORE INTO ATO_MEDICO
VALUES (1, '2023-01-01 08:15:00', '2023-01-01 08:30:00', 'Triagem', 1001)
''')
self.cursor.execute('''
INSERT OR IGNORE INTO ATO_MEDICO
VALUES (2, '2023-01-01 09:00:00', NULL, 'Consulta', 1001)
''')
self.conn.commit()
def demonstrar_inserir_episodio(self):
"""Demonstra a inserção de um novo episódio"""
print("\nDemonstração: Inserindo novo episódio de urgência...")
try:
cod_episodio = 1003
nr_utente = 2
nome_hospital = "Hospital Central"
data_hora_entrada = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.cursor.execute('''
INSERT INTO EPISODIO_URGENCIA
VALUES (?, ?, NULL, ?, ?)
''', (cod_episodio, data_hora_entrada, nr_utente, nome_hospital))
self.conn.commit()
print(f"Episódio {cod_episodio} inserido com sucesso para o utente {nr_utente} no {nome_hospital}!")
except sqlite3.IntegrityError:
print("Episódio já existe (usando dados de demonstração)")
def demonstrar_registar_saida(self):
"""Demonstra o registro de saída de um episódio"""
print("\nDemonstração: Registrando saída de um episódio...")
# Encontrar um episódio aberto
self.cursor.execute('''
SELECT cod_episodio FROM EPISODIO_URGENCIA
WHERE data_hora_saida IS NULL LIMIT 1
''')
episodio = self.cursor.fetchone()
if episodio:
cod_episodio = episodio[0]
data_hora_saida = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.cursor.execute('''
UPDATE EPISODIO_URGENCIA
SET data_hora_saida = ?
WHERE cod_episodio = ?
''', (data_hora_saida, cod_episodio))
self.conn.commit()
print(f"Saída registrada para o episódio {cod_episodio} às {data_hora_saida}")
else:
print("Não há episódios abertos para registrar saída")
def listar_tudo(self):
"""Lista o conteúdo de todas as tabelas"""
print("\n--- CONTEÚDO COMPLETO DA BASE DE DADOS ---")
print("\nUTENTES:")
self.cursor.execute("SELECT * FROM UTENTE")
for row in self.cursor.fetchall():
print(row)
print("\nHOSPITAIS:")
self.cursor.execute("SELECT * FROM HOSPITAL")
for row in self.cursor.fetchall():
print(row)
print("\nEPISÓDIOS DE URGÊNCIA:")
self.cursor.execute("SELECT * FROM EPISODIO_URGENCIA")
for row in self.cursor.fetchall():
print(row)
print("\nFUNCIONÁRIOS:")
self.cursor.execute("SELECT * FROM FUNCIONARIO")
for row in self.cursor.fetchall():
print(row)
print("\nATOS MÉDICOS:")
self.cursor.execute("SELECT * FROM ATO_MEDICO")
for row in self.cursor.fetchall():
print(row)
print("\nPRESCRIÇÕES:")
self.cursor.execute("SELECT * FROM PRESCRICAO")
for row in self.cursor.fetchall():
print(row)
print("\nPARTICIPAÇÕES EM ATOS:")
self.cursor.execute("SELECT * FROM PARTICIPACAO_ATO")
for row in self.cursor.fetchall():
print(row)
def close(self):
"""Fecha a conexão com o banco de dados"""
self.conn.close()
# Demonstração automática das funcionalidades
print("=== DEMONSTRAÇÃO DO SISTEMA DE GESTÃO DE URGÊNCIAS ===")
db = UrgenciasDB()
# 1. Mostrar dados iniciais
print("\nDados iniciais:")
db.listar_tudo()
# 2. Demonstrar inserção de novo episódio
db.demonstrar_inserir_episodio()
# 3. Demonstrar registro de saída
db.demonstrar_registar_saida()
# 4. Mostrar dados após operações
print("\nDados após operações:")
db.listar_tudo()
db.close()
print("\nDemonstração concluída!")
To embed this program on your website, copy the following code and paste it into your website's HTML: