Debug
This commit is contained in:
parent
0017c231eb
commit
939a301fd1
1 changed files with 44 additions and 24 deletions
|
|
@ -6,12 +6,17 @@ from typing import Dict, Any, List
|
|||
from packages.v1.administrativo.schemas.log_schema import LogClientIdSchema
|
||||
from packages.v1.administrativo.actions.log.log_show_database_action import ShowDatabaseAction
|
||||
|
||||
# --- FUNÇÃO AUXILIAR PARA COMPARAÇÃO DE CAMPOS (MANTIDA SEM CONTEÚDO) ---
|
||||
# --- CONSTANTE DE FILTRO ---
|
||||
# Define os identificadores a serem ignorados em TODA a auditoria
|
||||
IGNORE_ELEMENTS_SET = {"CONVERSAO_RI"}
|
||||
|
||||
|
||||
# --- FUNÇÃO AUXILIAR PARA COMPARAÇÃO DE CAMPOS ---
|
||||
|
||||
def compare_fields(standard_fields: List[Dict], client_fields: List[Dict], table_name: str) -> List[Dict]:
|
||||
"""
|
||||
Compara os campos de uma tabela entre as estruturas padrão e cliente,
|
||||
retornando apenas os nomes dos campos/atributos divergentes.
|
||||
Compara os campos de uma tabela entre as estruturas padrão e cliente.
|
||||
(Esta função não precisa de filtro, pois é chamada apenas para tabelas JÁ FILTRADAS)
|
||||
"""
|
||||
discrepancies = []
|
||||
|
||||
|
|
@ -55,7 +60,7 @@ def compare_fields(standard_fields: List[Dict], client_fields: List[Dict], table
|
|||
return discrepancies
|
||||
|
||||
|
||||
# --- FUNÇÃO PRINCIPAL DE COMPARAÇÃO DE ESTRUTURAS (MANTIDA SEM CONTEÚDO) ---
|
||||
# --- FUNÇÃO PRINCIPAL DE COMPARAÇÃO DE ESTRUTURAS (AJUSTADA COM FILTRO) ---
|
||||
|
||||
def compare_structures(standard_structure: Dict[str, Any], client_structure: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
|
|
@ -74,17 +79,26 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
|
|||
audit_log["discrepancias_encontradas"] = True
|
||||
return audit_log
|
||||
|
||||
# Mapeamento seguro das tabelas (Correção do KeyError)
|
||||
standard_tables_map = {t['TABLE_NAME']: t for t in standard_structure.get('tables', [])}
|
||||
# --- 1. AUDITORIA DE TABELAS E SEUS CAMPOS (APLICA FILTRO AQUI) ---
|
||||
|
||||
# 1.1 Filtragem e Mapeamento Padrão
|
||||
standard_tables_filtered = [
|
||||
t for t in standard_structure.get('tables', [])
|
||||
if t.get('TABLE_NAME') not in IGNORE_ELEMENTS_SET
|
||||
]
|
||||
standard_tables_map = {t['TABLE_NAME']: t for t in standard_tables_filtered}
|
||||
|
||||
# 1.2 Mapeamento Cliente (com filtro e tratamento de KeyError)
|
||||
client_tables_map = {}
|
||||
malformed_tables_data = []
|
||||
|
||||
for t in client_structure.get('tables', []):
|
||||
table_name = t.get('TABLE_NAME')
|
||||
|
||||
if table_name:
|
||||
# Filtra TABLE_NAME = 'CONVERSAO_RI' E trata a falta da chave
|
||||
if table_name and table_name not in IGNORE_ELEMENTS_SET:
|
||||
client_tables_map[table_name] = t
|
||||
else:
|
||||
elif not table_name:
|
||||
malformed_tables_data.append(t)
|
||||
|
||||
if malformed_tables_data:
|
||||
|
|
@ -94,7 +108,7 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
|
|||
"total_objetos_ignorados": len(malformed_tables_data)
|
||||
}
|
||||
|
||||
# 1. AUDITORIA DE TABELAS
|
||||
# 1.3 Compara as tabelas já filtradas
|
||||
missing_tables = standard_tables_map.keys() - client_tables_map.keys()
|
||||
if missing_tables:
|
||||
audit_log["discrepancias_encontradas"] = True
|
||||
|
|
@ -115,16 +129,27 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
|
|||
audit_log["discrepancias_encontradas"] = True
|
||||
audit_log["detalhes"]["divergencia_de_campos"].extend(field_discrepancies)
|
||||
|
||||
# 2. AUDITORIA DE OUTROS ELEMENTOS (PKs, FKs, etc.)
|
||||
# --- 2. AUDITORIA DE OUTROS ELEMENTOS (PKs, FKs, etc.) (APLICA FILTRO AQUI) ---
|
||||
|
||||
elements_to_check = ['primary_keys', 'foreign_keys', 'indexes', 'views', 'procedures', 'triggers']
|
||||
|
||||
for element_key in elements_to_check:
|
||||
standard_elements = standard_structure.get(element_key, [])
|
||||
client_elements = client_structure.get(element_key, [])
|
||||
|
||||
# FILTRAGEM DE ELEMENTOS (Ex: Se CONVERSAO_RI for um CONSTRAINT_NAME ou INDEX_NAME)
|
||||
|
||||
def filter_element(item):
|
||||
# Tenta encontrar um identificador primário para o filtro
|
||||
identifier = item.get('TABLE_NAME') or item.get('CONSTRAINT_NAME') or item.get('INDEX_NAME')
|
||||
return identifier not in IGNORE_ELEMENTS_SET
|
||||
|
||||
standard_elements_filtered = list(filter(filter_element, standard_elements))
|
||||
client_elements_filtered = list(filter(filter_element, client_elements))
|
||||
|
||||
try:
|
||||
standard_set = {json.dumps(item, sort_keys=True) for item in standard_elements}
|
||||
client_set = {json.dumps(item, sort_keys=True) for item in client_elements}
|
||||
standard_set = {json.dumps(item, sort_keys=True) for item in standard_elements_filtered}
|
||||
client_set = {json.dumps(item, sort_keys=True) for item in client_elements_filtered}
|
||||
except TypeError:
|
||||
audit_log["discrepancias_encontradas"] = True
|
||||
audit_log["detalhes"]["erro_serializacao"] = f"Erro ao comparar {element_key}. Os dados podem estar malformados."
|
||||
|
|
@ -148,7 +173,7 @@ def compare_structures(standard_structure: Dict[str, Any], client_structure: Dic
|
|||
return audit_log
|
||||
|
||||
|
||||
# --- CLASSE PRINCIPAL DE SERVIÇO (AJUSTADA PARA DEBUG) ---
|
||||
# --- CLASSE PRINCIPAL DE SERVIÇO (MANTIDA PARA DEBUG) ---
|
||||
|
||||
class ShowDatabaseService:
|
||||
|
||||
|
|
@ -156,39 +181,34 @@ class ShowDatabaseService:
|
|||
|
||||
log_show_database_action = ShowDatabaseAction()
|
||||
|
||||
# Executa a ação, que agora retorna os dados do log E o standard_structure_json
|
||||
dados_completos = log_show_database_action.execute(client_id_schema)
|
||||
|
||||
# verifica se 'dados_completos' não é None e contém 'file'
|
||||
if dados_completos and dados_completos.get("file"):
|
||||
|
||||
# 1. Parsing do Log do Cliente
|
||||
dados_json = json.loads(dados_completos["file"])
|
||||
|
||||
# 2. Extração da Estrutura Padrão (JSON em formato string)
|
||||
# 2. Extração e Parsing da Estrutura Padrão
|
||||
standard_structure_json_string = dados_completos.get("standard_structure_json")
|
||||
|
||||
# 3. Parsing do JSON da Estrutura Padrão
|
||||
standard_structure_data: Dict[str, Any] = {}
|
||||
if standard_structure_json_string:
|
||||
try:
|
||||
standard_structure_data = json.loads(standard_structure_json_string)
|
||||
except json.JSONDecodeError:
|
||||
# Se falhar, a comparação será feita com um dict vazio
|
||||
pass
|
||||
|
||||
database_data = dados_json.get("database", {})
|
||||
|
||||
# 4. Extração da Estrutura do Cliente
|
||||
# 3. Extração da Estrutura do Cliente
|
||||
client_structure: Dict[str, Any] = database_data.get("structure", {})
|
||||
|
||||
# 5. Efetua a auditoria comparando as duas estruturas
|
||||
# 4. Efetua a auditoria
|
||||
auditoria_do_banco = compare_structures(
|
||||
standard_structure_data, # Estrutura padrão
|
||||
client_structure # Estrutura do cliente
|
||||
)
|
||||
|
||||
# 6. Monta o JSON final de RETORNO (incluindo as estruturas para debug)
|
||||
# 5. Monta o JSON final (INCLUINDO ESTRUTURAS PARA DEBUG)
|
||||
data = {
|
||||
"cns": dados_json.get("cns"),
|
||||
"cartorio": dados_json.get("cartorio"),
|
||||
|
|
@ -200,10 +220,10 @@ class ShowDatabaseService:
|
|||
"db_accessible": database_data.get("db_accessible", {}),
|
||||
"last_modified": database_data.get("last_modified", {}),
|
||||
|
||||
# --- CAMPOS DE DEBUG ---
|
||||
# --- CAMPOS DE DEBUG SOLICITADOS ---
|
||||
"estrutura_cliente_debug": client_structure,
|
||||
"estrutura_padrao_debug": standard_structure_data,
|
||||
# -----------------------
|
||||
# ----------------------------------
|
||||
|
||||
"auditoria_do_banco": auditoria_do_banco
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue