fix(): Ajuste no retorno info database

This commit is contained in:
Kenio 2025-12-08 15:24:46 -03:00
parent a8f1543f41
commit 2f6fb09fff

View file

@ -71,7 +71,8 @@ def compare_fields(standard_fields: List[Dict], client_fields: List[Dict], table
def compare_structures(standard_structure: Dict[str, Any], client_structure: Dict[str, Any]) -> Dict[str, Any]:
pass
# --- NOVO: FUNÇÃO: ELEMENTOS SOMENTE NO PADRÃO (Padrão - Cliente) ---
# --- FUNÇÃO: ELEMENTOS SOMENTE NO PADRÃO (Padrão - Cliente) ---
# Esta função é essencial e deve ser mantida.
def find_standard_only_elements(standard_structure: Dict[str, Any], client_structure: Dict[str, Any]) -> Dict[str, Any]:
"""
@ -148,8 +149,8 @@ def find_standard_only_elements(standard_structure: Dict[str, Any], client_struc
return standard_only
# --- FUNÇÃO: ELEMENTOS SOMENTE NO CLIENTE (Agora usa chaves UPPERCASE) ---
# --- FUNÇÃO: ELEMENTOS SOMENTE NO CLIENTE (Removida a necessidade de chamada no execute) ---
# A função é mantida, mas não é chamada, pois não faz parte do retorno desejado.
def find_client_only_elements(standard_structure: Dict[str, Any], client_structure: Dict[str, Any]) -> Dict[str, Any]:
"""
Identifica elementos presentes na estrutura do cliente mas ausentes na estrutura padrão.
@ -157,31 +158,26 @@ def find_client_only_elements(standard_structure: Dict[str, Any], client_structu
"""
client_only = {}
# --- 1. TABLES (Lidando com a estrutura achatada do cliente) ---
# ... (lógica interna da função original) ...
# O conteúdo desta função não precisa ser alterado se não for usado.
# 1a. Normalize e Filtra Tabelas Padrão
# --- 1. TABLES (Lidando com a estrutura achatada do cliente) ---
standard_tables_names = {t.get('TABLE_NAME') for t in standard_structure.get('TABLES', [])
if t.get('TABLE_NAME') and not is_ignored(t.get('TABLE_NAME'))}
# 1b. Agrupa e Filtra Campos do Cliente por Nome de Tabela
client_fields_by_table: Dict[str, List[Dict]] = {}
# A chave do nível superior agora é 'TABLES' (em UPPERCASE)
for field_item in client_structure.get('TABLES', []):
table_name = field_item.get('TABLE_NAME')
# Filtra a tabela e o elemento, se for CONVERSAO
if table_name and not is_ignored(table_name):
if table_name not in client_fields_by_table:
client_fields_by_table[table_name] = []
client_fields_by_table[table_name].append(field_item)
# 1c. Encontra Tabelas Exclusivas do Cliente
client_tables_names = set(client_fields_by_table.keys())
unique_table_names = client_tables_names - standard_tables_names
client_only_tables = []
for table_name in unique_table_names:
# Retorna a lista de campos agrupados sob o nome da tabela (limpa)
client_only_tables.append({
"TABLE_NAME": table_name,
"FIELDS": [_remove_source_code(f) for f in client_fields_by_table[table_name]]
@ -191,35 +187,27 @@ def find_client_only_elements(standard_structure: Dict[str, Any], client_structu
client_only["TABELAS_UNICAS"] = client_only_tables
# --- 2. OUTROS ELEMENTOS (PKs, FKs, etc.) ---
# Chaves de nível superior agora em UPPERCASE
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, [])
# Cria Sets baseados na representação JSON normalizada (limpa), filtrando IGNORED
# Standard Set (Filtrado para IGNORED)
standard_elements_filtered = [item for item in standard_elements
if not is_ignored(get_element_identifier(item))]
# O _remove_source_code é chamado após a normalização.
standard_set = {json.dumps(_remove_source_code(item), sort_keys=True)
for item in standard_elements_filtered}
# Client Set (Filtrado para IGNORED)
client_set_normalized = {}
for item in client_elements:
identifier = get_element_identifier(item)
if identifier and not is_ignored(identifier): # Filtra CONVERSAO
if identifier and not is_ignored(identifier):
cleaned_item = _remove_source_code(item)
json_str = json.dumps(cleaned_item, sort_keys=True)
client_set_normalized[json_str] = cleaned_item
client_set = set(client_set_normalized.keys())
# Calcula a diferença Cliente - Padrão
unique_client_elements_str = client_set - standard_set
if unique_client_elements_str:
@ -230,10 +218,11 @@ def find_client_only_elements(standard_structure: Dict[str, Any], client_structu
return client_only
# --- CLASSE PRINCIPAL DE SERVIÇO ---
# --- CLASSE PRINCIPAL DE SERVIÇO (Modificada) ---
class ShowDatabaseService:
# Esta função helper não é mais estritamente necessária, mas é mantida por segurança/modularidade
def _clean_full_structure_for_output(self, structure: Dict[str, Any]) -> Dict[str, Any]:
"""Cria uma cópia limpa da estrutura, removendo 'SOURCE_CODE' em todos os elementos relevantes.
Assume que a estrutura está em UPPERCASE."""
@ -243,10 +232,8 @@ class ShowDatabaseService:
for key in keys_to_clean:
if key in cleaned and isinstance(cleaned[key], list):
# Aplica a limpeza a cada item da lista
cleaned[key] = [_remove_source_code(item) for item in cleaned[key]]
# Garante que, se houver campos (FIELDS) aninhados, eles também sejam limpos
if 'TABLES' in cleaned and isinstance(cleaned['TABLES'], list):
for table in cleaned['TABLES']:
if 'FIELDS' in table and isinstance(table['FIELDS'], list):
@ -265,7 +252,7 @@ class ShowDatabaseService:
# Extrai e carrega os dados JSON do campo 'file'
dados_json = json.loads(dados_json["file"])
# Extrai as estruturas de dados relevantes
# --- 1. Extração e Carregamento (Standard) ---
standard_structure_json_string = dados_json.get("standard_structure_json")
standard_structure_data: Dict[str, Any] = {}
if standard_structure_json_string:
@ -274,45 +261,33 @@ class ShowDatabaseService:
except json.JSONDecodeError:
pass
# Extrai a estrutura do cliente do JSON
# --- 2. Extração e Carregamento (Client e Metadata) ---
database_data = dados_json.get("database", {})
client_structure: Dict[str, Any] = database_data.get("structure", {})
# NOVO PASSO CRUCIAL: Normaliza as chaves para UPPERCASE em ambas as estruturas
partition_info = database_data.get("partition", {})
# --- 3. Normalização CRUCIAL ---
standard_structure_data = _normalize_keys_to_upper(standard_structure_data)
client_structure = _normalize_keys_to_upper(client_structure)
# Limpa ambas as estruturas de 'source_code' para o output de debug
debug_cliente = self._clean_full_structure_for_output(client_structure)
debug_padrao = self._clean_full_structure_for_output(standard_structure_data)
# Encontra elementos exclusivos do cliente (Cliente - Padrão)
elementos_unicos_cliente = find_client_only_elements(
standard_structure_data,
client_structure
)
# NOVO: Encontra elementos exclusivos do padrão (Padrão - Cliente)
# --- 4. Comparação FOCADA (Padrão - Cliente) ---
# SOMENTE a função que encontra elementos que faltam no cliente é chamada.
elementos_unicos_padrao = find_standard_only_elements(
standard_structure_data,
client_structure
)
# Separa o campo 'partition' das demais chaves
partition_info = database_data.get("partition", {})
# Monta o JSON final
# --- 5. Monta o JSON final SIMPLIFICADO ---
data = {
# Mantém a metadata básica
"cns": dados_json.get("cns"),
"cartorio": dados_json.get("cartorio"),
"data": dados_json.get("data"),
"hora": dados_json.get("hora"),
"database": {
"partition": partition_info,
"default_schema": debug_padrao,
"client_schema": debug_cliente,
"client_only_items": elementos_unicos_cliente,
"standard_only_items": elementos_unicos_padrao # NOVO CAMPO ADICIONADO
# Remove default_schema, client_schema e client_only_items
"standard_only_items": elementos_unicos_padrao
}
}