baucli 1.0.147__tar.gz → 1.0.149__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {baucli-1.0.147 → baucli-1.0.149}/PKG-INFO +1 -1
- {baucli-1.0.147 → baucli-1.0.149}/baucli/__init__.py +1 -1
- {baucli-1.0.147 → baucli-1.0.149}/baucli/cli.py +125 -16
- baucli-1.0.149/baucli/db_check_report.py +245 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/skills.py +35 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli.egg-info/PKG-INFO +1 -1
- {baucli-1.0.147 → baucli-1.0.149}/baucli.egg-info/SOURCES.txt +3 -0
- baucli-1.0.149/tests/test_db_check_report.py +72 -0
- baucli-1.0.149/tests/test_skills_size_budget.py +25 -0
- {baucli-1.0.147 → baucli-1.0.149}/MANIFEST.in +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/README.md +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/apex_rebuild.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/apexlang.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/apexlang_profile.json +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/apexlint.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/api.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/canon.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/config.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/db/__init__.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/db/mssql.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/db/mysql.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/db/oracle.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/db/postgresql.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/democrm.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/democrm_sql/mssql/crm_data_mssql.sql +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/democrm_sql/mssql/crm_demo_mssql.sql +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/democrm_sql/mysql/crm_data_mysql.sql +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/democrm_sql/mysql/crm_demo_mysql.sql +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/democrm_sql/oracle/crm_demo_oracle.sql +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/democrm_sql/postgresql/crm_data_postgresql.sql +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/democrm_sql/postgresql/crm_demo_postgresql.sql +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/diffenvs.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/docmig.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/docmig_baseline.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/docmig_build.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/docmig_install.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/docmig_shell.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/docmig_spec_schema.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/docmig_spec_tools.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/docmig_spec_workspace.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/git.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/legacy/__init__.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/legacy/delphi.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/legacy/delphi_canon.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/legacy/delphi_evidence.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/legacy/magic.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/mcp_server.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/project.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/rag_embed.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/sample_scan.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/scope_scan.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/screenshot.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/seed_check.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/stress.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/sync.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/templates/app_shell/.apex/apexlang.json +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/templates/app_shell/pages/login.apx.tpl +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/templates/app_shell/shared-components/lists/navigation-bar.apx +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/templates/app_shell/shared-components/themes/universal-theme/theme.apx +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/uikit.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli/unwrap.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli.egg-info/dependency_links.txt +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli.egg-info/entry_points.txt +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli.egg-info/requires.txt +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/baucli.egg-info/top_level.txt +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/pyproject.toml +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/setup.cfg +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/setup.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_apexlint_binario.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_apexlint_dialogo.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_apexlint_dominio.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_api_request_db.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_canon_anchored_markers.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_canon_multiengine.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_db_tenant_guard.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_delphi_canon.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_delphi_datasnap.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_delphi_evidence.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_delphi_fmx.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_delta_clock.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_deploy_alias.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_baseline.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_build.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_build_extend.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_build_new.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_expressividade.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_install.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_install_extend.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_install_shell.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_project.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_project_new.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_shell.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_spec_analista.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_spec_schema.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_spec_schema_11.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_spec_schema_app.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_spec_use_baseline.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_sqlcl_padrao.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docmig_support_objects.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_docrev_dismiss.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_doctab_split.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_documentation_list_db_label.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_mcp_doc_changeset.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_mcp_doc_tags.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_mcp_doctab_text.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_mcp_schema_context.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_packaging_deps.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_post_apply_uikit.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_profiles_add_prompt.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_project_guarda_chuva.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_scope_scan_call_wrapper.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_scope_scan_datasnap_reach.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_scope_scan_from_depth.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_scope_scan_owner.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_scope_scan_pkg_func_from.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_skills_apex_domain.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_skills_lessons.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_spec_sem_beg.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_sync_413.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_sync_charset.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_table_status.py +0 -0
- {baucli-1.0.147 → baucli-1.0.149}/tests/test_uikit_scope.py +0 -0
|
@@ -5788,8 +5788,18 @@ def db_profile(db_name, schema, source, tables_csv):
|
|
|
5788
5788
|
@click.option("-v", "--verbose", "verbose", is_flag=True, default=False,
|
|
5789
5789
|
help="Mostra o SQL de cada etapa junto do tempo — para levar a "
|
|
5790
5790
|
"query lenta ao EXPLAIN PLAN.")
|
|
5791
|
+
@click.option("--format", "fmt", type=click.Choice(["terminal", "json", "html"], case_sensitive=False),
|
|
5792
|
+
default="terminal", show_default=True,
|
|
5793
|
+
help="terminal = tabelas na tela (como sempre); json = contrato versionado "
|
|
5794
|
+
"com TODOS os objetos (ignora --top), para CI/scripts; html = um "
|
|
5795
|
+
"arquivo só, para enviar ao cliente ou imprimir em PDF pelo navegador.")
|
|
5796
|
+
@click.option("--output", "out_file", default=None,
|
|
5797
|
+
help="Arquivo de saída para --format json|html (default: stdout).")
|
|
5798
|
+
@click.option("--client", "client_name", default=None,
|
|
5799
|
+
help="Nome do cliente no cabeçalho do HTML (opcional).")
|
|
5791
5800
|
def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
5792
|
-
max_cols: int, strict: bool, verbose: bool
|
|
5801
|
+
max_cols: int, strict: bool, verbose: bool,
|
|
5802
|
+
fmt: str = "terminal", out_file: str = None, client_name: str = None):
|
|
5793
5803
|
"""Pré-voo de IA: aponta o que vai dar problema ANTES de documentar.
|
|
5794
5804
|
|
|
5795
5805
|
\b
|
|
@@ -5837,6 +5847,25 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
5837
5847
|
LINES_UNSAFE = 6000 # DOCPL.LINES_UNSAFE (AI edit safety)
|
|
5838
5848
|
MAX_COLS_FALLBACK = 60 # DOCTAB.MAX_COLUMNS_IN_TABLE_PROMPT
|
|
5839
5849
|
|
|
5850
|
+
# ── Saída estruturada (--format json|html) ────────────────────────────
|
|
5851
|
+
# O diagnóstico é montado num dict (`report`) ao lado de cada seção e, no
|
|
5852
|
+
# fim, serializado por baucli/db_check_report.py. Em modo estruturado a
|
|
5853
|
+
# narração do rich é silenciada (console.quiet) para que stdout carregue
|
|
5854
|
+
# só o payload; erros fatais passam por _fail, que religa o console.
|
|
5855
|
+
from baucli.db_check_report import empty_report, to_json, to_html
|
|
5856
|
+
from baucli import __version__ as _baucli_ver
|
|
5857
|
+
fmt = (fmt or "terminal").lower()
|
|
5858
|
+
_structured = fmt in ("json", "html")
|
|
5859
|
+
report = empty_report()
|
|
5860
|
+
report["baucli_version"] = _baucli_ver
|
|
5861
|
+
if _structured:
|
|
5862
|
+
console.quiet = True
|
|
5863
|
+
|
|
5864
|
+
def _fail(msg, code=1):
|
|
5865
|
+
console.quiet = False
|
|
5866
|
+
console.print(msg)
|
|
5867
|
+
raise SystemExit(code)
|
|
5868
|
+
|
|
5840
5869
|
from baucli.project import find_project
|
|
5841
5870
|
proj = find_project()
|
|
5842
5871
|
|
|
@@ -5852,25 +5881,22 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
5852
5881
|
cfg = load_config()
|
|
5853
5882
|
name, db_config = get_database(cfg, db_name)
|
|
5854
5883
|
if not name or not db_config:
|
|
5855
|
-
|
|
5884
|
+
_fail(
|
|
5856
5885
|
f"[red]bau.toml aponta [connection].db = '{db_name}', mas esse database "
|
|
5857
5886
|
f"não está registrado neste BAUCLI_HOME.[/red]" if from_project else
|
|
5858
5887
|
"[red]Nenhum database configurado. Use --db, ou "
|
|
5859
5888
|
"[cyan]baucli connect[/cyan] para registrar um.[/red]")
|
|
5860
|
-
raise SystemExit(1)
|
|
5861
5889
|
if (db_config.get("engine") or "").lower() != "oracle":
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
raise SystemExit(1)
|
|
5890
|
+
_fail(f"[red]db check suporta apenas Oracle "
|
|
5891
|
+
f"(este é {db_config.get('engine')}).[/red]")
|
|
5865
5892
|
if not schema:
|
|
5866
5893
|
cand = [s for s in (db_config.get("schemas") or [])]
|
|
5867
5894
|
if len(cand) == 1:
|
|
5868
5895
|
schema = cand[0].upper()
|
|
5869
5896
|
else:
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
raise SystemExit(1)
|
|
5897
|
+
_fail("[red]Sem schema. Use --schema, ou defina "
|
|
5898
|
+
"[project].default_schema no bau.toml.[/red]"
|
|
5899
|
+
+ (f" Schemas do database: {', '.join(cand)}" if cand else ""))
|
|
5874
5900
|
|
|
5875
5901
|
# ── Limiares vindos do BAU (o servidor é a fonte, não o CLI) ───────────
|
|
5876
5902
|
# Busca best-effort: sem api key ou com o BAU fora do ar, cai no fallback
|
|
@@ -5906,6 +5932,21 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
5906
5932
|
max_cols = MAX_COLS_FALLBACK
|
|
5907
5933
|
|
|
5908
5934
|
_origem_cols = "flag --max-columns" if _cols_flag else _thr_fonte
|
|
5935
|
+
report["schema"] = schema
|
|
5936
|
+
report["database"] = {
|
|
5937
|
+
"alias": name, "engine": db_config.get("engine"),
|
|
5938
|
+
"host": db_config.get("host"), "port": db_config.get("port"),
|
|
5939
|
+
"service": db_config.get("service", db_config.get("database")),
|
|
5940
|
+
"user": db_config.get("user"),
|
|
5941
|
+
}
|
|
5942
|
+
report["thresholds"] = {
|
|
5943
|
+
"source_max_chars": src_max, "max_columns": max_cols,
|
|
5944
|
+
"chars_per_token": CHARS_PER_TOKEN,
|
|
5945
|
+
"lines_warning": LINES_WARNING, "lines_critical": LINES_CRITICAL,
|
|
5946
|
+
"lines_caution": LINES_CAUTION, "lines_unsafe": LINES_UNSAFE,
|
|
5947
|
+
"size_warning_kb": SIZE_WARNING_KB, "size_critical_kb": SIZE_CRITICAL_KB,
|
|
5948
|
+
"source": _thr_fonte, "max_columns_source": _origem_cols,
|
|
5949
|
+
}
|
|
5909
5950
|
show_db_panel("DB Check — pré-voo de IA", db_name=name, db_config=db_config,
|
|
5910
5951
|
extra_lines=[
|
|
5911
5952
|
f" Schema: [yellow]{schema}[/yellow]",
|
|
@@ -5953,8 +5994,7 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
5953
5994
|
try:
|
|
5954
5995
|
extractor.connect()
|
|
5955
5996
|
except Exception as e:
|
|
5956
|
-
|
|
5957
|
-
raise SystemExit(1)
|
|
5997
|
+
_fail(f"[red]Connection error: {e}[/red]")
|
|
5958
5998
|
_steps.append(("conexao ao banco", _time.perf_counter() - _t0, 0))
|
|
5959
5999
|
console.print(f" [dim] conexao ao banco: [/dim][cyan]{_steps[-1][1]:.2f}s[/cyan]")
|
|
5960
6000
|
cur = extractor._conn.cursor()
|
|
@@ -5973,11 +6013,10 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
5973
6013
|
console.print(f" [dim] guarda de sanidade: [/dim][cyan]{_steps[-1][1]:.2f}s[/cyan]")
|
|
5974
6014
|
if conn_user != schema:
|
|
5975
6015
|
if _vis == 0:
|
|
5976
|
-
console.print(f"[red]Conectado como [bold]{conn_user}[/bold] mas checando "
|
|
5977
|
-
f"[bold]{schema}[/bold] — esse usuário não enxerga nada desse "
|
|
5978
|
-
f"schema. Provável --db/BAUCLI_HOME errado.[/red]")
|
|
5979
6016
|
extractor.disconnect()
|
|
5980
|
-
|
|
6017
|
+
_fail(f"[red]Conectado como [bold]{conn_user}[/bold] mas checando "
|
|
6018
|
+
f"[bold]{schema}[/bold] — esse usuário não enxerga nada desse "
|
|
6019
|
+
f"schema. Provável --db/BAUCLI_HOME errado.[/red]")
|
|
5981
6020
|
|
|
5982
6021
|
# Tipos que o BAU consegue fatiar: um PACKAGE BODY grande é documentado
|
|
5983
6022
|
# subprograma a subprograma (chunking DOCPL), então passar do limite da
|
|
@@ -6026,6 +6065,14 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6026
6065
|
findings[lvl] += 1
|
|
6027
6066
|
flagged.append((lvl, otype, oname, int(lines or 0), int(chars or 0), why))
|
|
6028
6067
|
|
|
6068
|
+
_ord_lvl = {"CRÍTICO": 0, "ATENÇÃO": 1, "AVISO": 2}
|
|
6069
|
+
report["plsql"] = {
|
|
6070
|
+
"total": len(plsql_rows),
|
|
6071
|
+
"flagged": [{"level": lvl, "type": otype, "name": oname, "lines": lines,
|
|
6072
|
+
"chars": chars, "tokens": int(chars / CHARS_PER_TOKEN), "reason": why}
|
|
6073
|
+
for (lvl, otype, oname, lines, chars, why)
|
|
6074
|
+
in sorted(flagged, key=lambda r: (_ord_lvl[r[0]], -r[4]))],
|
|
6075
|
+
}
|
|
6029
6076
|
console.print(f"[bold]PL/SQL[/bold] — {len(plsql_rows)} objeto(s) no schema, "
|
|
6030
6077
|
f"{len(flagged)} sinalizado(s)")
|
|
6031
6078
|
if flagged:
|
|
@@ -6071,6 +6118,11 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6071
6118
|
ORDER BY 2 DESC
|
|
6072
6119
|
""", {"o": schema, "mx": max_cols})
|
|
6073
6120
|
findings["ATENÇÃO"] += len(wide)
|
|
6121
|
+
report["wide_tables"] = {
|
|
6122
|
+
"max_columns": max_cols,
|
|
6123
|
+
"items": [{"table": tname, "columns": int(cols), "lobs": int(lobs or 0)}
|
|
6124
|
+
for (tname, cols, lobs) in wide],
|
|
6125
|
+
}
|
|
6074
6126
|
console.print(f"\n[bold]Tabelas largas[/bold] — {len(wide)} acima de {max_cols} colunas")
|
|
6075
6127
|
if wide:
|
|
6076
6128
|
t = RichTable(show_header=True, header_style="bold", border_style="dim")
|
|
@@ -6152,6 +6204,14 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6152
6204
|
com_id = [r for r in no_pk if r not in sem_id]
|
|
6153
6205
|
findings["ATENÇÃO"] += len(sem_id)
|
|
6154
6206
|
findings["AVISO"] += len(com_id)
|
|
6207
|
+
report["no_pk"] = {
|
|
6208
|
+
"total": len(no_pk), "no_identity": len(sem_id), "with_unique": len(com_id),
|
|
6209
|
+
"items": [{"table": tname, "columns": int(cols or 0),
|
|
6210
|
+
"rows_est": int(nrows) if nrows is not None else None,
|
|
6211
|
+
"uks": int(uks or 0), "unique_indexes": int(uix or 0),
|
|
6212
|
+
"has_identity": not (int(uks or 0) == 0 and int(uix or 0) == 0)}
|
|
6213
|
+
for (tname, cols, uks, uix, nrows) in (sem_id + com_id)],
|
|
6214
|
+
}
|
|
6155
6215
|
console.print(f"\n[bold]Tabelas sem PK[/bold] — {len(no_pk)} "
|
|
6156
6216
|
f"([red]{len(sem_id)} sem identidade alguma[/red], "
|
|
6157
6217
|
f"{len(com_id)} com UK/índice único"
|
|
@@ -6185,6 +6245,11 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6185
6245
|
ORDER BY 2 DESC
|
|
6186
6246
|
""", {"o": schema, "mx": src_max})
|
|
6187
6247
|
findings["CRÍTICO"] += len(big_views)
|
|
6248
|
+
report["big_views"] = {
|
|
6249
|
+
"limit_chars": src_max,
|
|
6250
|
+
"items": [{"view": vname, "chars": int(vlen), "tokens": int(int(vlen) / CHARS_PER_TOKEN)}
|
|
6251
|
+
for (vname, vlen) in big_views],
|
|
6252
|
+
}
|
|
6188
6253
|
console.print(f"\n[bold]Views grandes[/bold] — {len(big_views)} acima de "
|
|
6189
6254
|
f"{src_max:,} chars")
|
|
6190
6255
|
if big_views:
|
|
@@ -6216,6 +6281,13 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6216
6281
|
""", {"o": schema})
|
|
6217
6282
|
broken = [r for r in invalid if (r[3] or "").strip()]
|
|
6218
6283
|
stale = [r for r in invalid if not (r[3] or "").strip()]
|
|
6284
|
+
report["invalid"] = {
|
|
6285
|
+
"total": len(invalid),
|
|
6286
|
+
"broken": [{"type": otype, "name": oname, "last_ddl": last_ddl or None,
|
|
6287
|
+
"first_error": (err or "").strip()} for (otype, oname, last_ddl, err) in broken],
|
|
6288
|
+
"stale": [{"type": otype, "name": oname, "last_ddl": last_ddl or None}
|
|
6289
|
+
for (otype, oname, last_ddl, _err) in stale],
|
|
6290
|
+
}
|
|
6219
6291
|
|
|
6220
6292
|
if invalid:
|
|
6221
6293
|
console.print(f"\n[bold]Objetos INVALID[/bold] — {len(invalid)} no total "
|
|
@@ -6283,6 +6355,13 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6283
6355
|
""", {"o": schema})
|
|
6284
6356
|
sem_corpo = [r for r in nobody if int(r[3] or 0) > 0]
|
|
6285
6357
|
so_spec = [r for r in nobody if int(r[3] or 0) == 0]
|
|
6358
|
+
report["packages_no_body"] = {
|
|
6359
|
+
"total": len(nobody),
|
|
6360
|
+
"declaring": [{"package": pname, "subprograms": int(subs or 0),
|
|
6361
|
+
"spec_status": status, "last_ddl": last_ddl or None}
|
|
6362
|
+
for (pname, last_ddl, status, subs) in sem_corpo],
|
|
6363
|
+
"spec_only": [r[0] for r in so_spec],
|
|
6364
|
+
}
|
|
6286
6365
|
|
|
6287
6366
|
if nobody:
|
|
6288
6367
|
console.print(f"\n[bold]Packages sem BODY[/bold] — {len(nobody)} no total "
|
|
@@ -6346,6 +6425,7 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6346
6425
|
motivo = str(e).splitlines()[0][:70]
|
|
6347
6426
|
|
|
6348
6427
|
if not regras:
|
|
6428
|
+
report["object_rules"]["skipped"] = motivo or "nenhuma regra ativa"
|
|
6349
6429
|
console.print(f"\n[bold]Regras de objetos[/bold] [dim]— pulado: "
|
|
6350
6430
|
f"{motivo or 'nenhuma regra ativa'}[/dim]")
|
|
6351
6431
|
else:
|
|
@@ -6383,6 +6463,7 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6383
6463
|
) WHERE seq = 1 ORDER BY ak, nome"""
|
|
6384
6464
|
hits = _timed(f"regras de objeto ({len(regras)} regras x catalogo)",
|
|
6385
6465
|
_sql_reg, {"o": schema})
|
|
6466
|
+
report["object_rules"].update(source="BAU Server", rules=len(regras))
|
|
6386
6467
|
console.print(f"\n[bold]Regras de objetos[/bold] [dim]({len(regras)} regras "
|
|
6387
6468
|
f"· fonte: BAU Server)[/dim]")
|
|
6388
6469
|
if not hits:
|
|
@@ -6393,6 +6474,9 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6393
6474
|
for nome, tipo, ak, rname, _tot in hits:
|
|
6394
6475
|
por_kind.setdefault(ak, []).append(nome)
|
|
6395
6476
|
total = int(hits[0][4] or 0)
|
|
6477
|
+
report["object_rules"].update(
|
|
6478
|
+
total_objects=total, excluded=sum(len(v) for v in por_kind.values()),
|
|
6479
|
+
by_kind={ak: list(v) for ak, v in sorted(por_kind.items())})
|
|
6396
6480
|
for ak in sorted(por_kind):
|
|
6397
6481
|
nomes = por_kind[ak]
|
|
6398
6482
|
mostra = nomes if top == 0 else nomes[:top]
|
|
@@ -6489,6 +6573,14 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6489
6573
|
_cmt_hits.append((_k, _tb, _col, ",".join(_sig), _txt))
|
|
6490
6574
|
|
|
6491
6575
|
_is_utf8 = str(_charset).upper() in ("AL32UTF8", "UTF8")
|
|
6576
|
+
report["encoding"] = {
|
|
6577
|
+
"charset": _charset, "ncharset": _cs.get("NLS_NCHAR_CHARACTERSET"),
|
|
6578
|
+
"is_utf8": _is_utf8, "available": True,
|
|
6579
|
+
"source_objects": [{"name": _n, "type": _ty, "lines": int(_cnt or 0)}
|
|
6580
|
+
for (_n, _ty, _cnt) in _src_rows],
|
|
6581
|
+
"comments": [{"where": _k, "table": _tb, "column": _col, "signals": _sig, "text": _txt}
|
|
6582
|
+
for (_k, _tb, _col, _sig, _txt) in _cmt_hits],
|
|
6583
|
+
}
|
|
6492
6584
|
|
|
6493
6585
|
if _src_rows or _cmt_hits or not _is_utf8:
|
|
6494
6586
|
console.print("\n[bold]Codificação (acentuação da origem)[/bold]")
|
|
@@ -6542,9 +6634,13 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6542
6634
|
elif _is_utf8:
|
|
6543
6635
|
console.print(" [green]● Nenhum sinal de acentuação quebrada.[/green]")
|
|
6544
6636
|
except Exception as _e:
|
|
6637
|
+
report["encoding"]["available"] = False
|
|
6638
|
+
report["errors"].append(f"codificação: checagem indisponível ({str(_e).splitlines()[0][:80]})")
|
|
6545
6639
|
console.print(f" [dim]Codificação: checagem indisponível ({str(_e).splitlines()[0][:60]}).[/dim]")
|
|
6546
6640
|
|
|
6547
6641
|
extractor.disconnect()
|
|
6642
|
+
report["timings"] = [{"step": _lbl, "seconds": round(_dt, 3), "rows": _n}
|
|
6643
|
+
for (_lbl, _dt, _n) in _steps]
|
|
6548
6644
|
|
|
6549
6645
|
# ── Tempos por etapa: o gargalo fica explicito ─────────────────────────
|
|
6550
6646
|
# Ordenado pelo mais lento. A coluna "linhas" ajuda a distinguir "query
|
|
@@ -6588,6 +6684,19 @@ def db_check(db_name: str, schema: str, top: int, src_max: int,
|
|
|
6588
6684
|
console.print("[dim]Próximo passo: baucli sync (ou baucli sync --scope <CODE> "
|
|
6589
6685
|
"para recortar o schema).[/dim]")
|
|
6590
6686
|
|
|
6687
|
+
report["summary"] = {"critico": findings["CRÍTICO"], "atencao": findings["ATENÇÃO"],
|
|
6688
|
+
"aviso": findings["AVISO"]}
|
|
6689
|
+
if _structured:
|
|
6690
|
+
console.quiet = False
|
|
6691
|
+
payload = to_json(report) if fmt == "json" else to_html(report, client=client_name)
|
|
6692
|
+
if out_file:
|
|
6693
|
+
Path(out_file).write_text(payload, encoding="utf-8")
|
|
6694
|
+
console.print(f"[green]{fmt} gravado em {out_file}[/green] "
|
|
6695
|
+
f"[dim]({findings['CRÍTICO']} crítico, {findings['ATENÇÃO']} atenção, "
|
|
6696
|
+
f"{findings['AVISO']} aviso)[/dim]")
|
|
6697
|
+
else:
|
|
6698
|
+
click.echo(payload)
|
|
6699
|
+
|
|
6591
6700
|
if strict and findings["CRÍTICO"]:
|
|
6592
6701
|
raise SystemExit(2)
|
|
6593
6702
|
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""Saída estruturada do `baucli db check` (pré-voo de IA).
|
|
2
|
+
|
|
3
|
+
O comando sempre montou o diagnóstico em memória e o despejava em tabelas do
|
|
4
|
+
rich. Este módulo recebe o MESMO diagnóstico como dict (ver `empty_report`)
|
|
5
|
+
e o devolve em JSON (para CI, scripts, outro programa) ou HTML (um arquivo
|
|
6
|
+
só, sem dependência externa, que o cliente abre no navegador e imprime em
|
|
7
|
+
PDF). Não há parse de terminal em lugar nenhum: a fonte é o dict.
|
|
8
|
+
|
|
9
|
+
Contrato do dict (schema_version 1): chaves fixas, listas sempre presentes
|
|
10
|
+
(vazias quando nada foi encontrado), números como int, nomes de objeto como
|
|
11
|
+
vieram do dicionário Oracle.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import html as _html
|
|
16
|
+
import json
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
|
|
19
|
+
SCHEMA_VERSION = 1
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def empty_report() -> dict:
|
|
23
|
+
return {
|
|
24
|
+
"schema_version": SCHEMA_VERSION,
|
|
25
|
+
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
26
|
+
"baucli_version": None,
|
|
27
|
+
"database": {}, # alias, engine, host, port, service, user
|
|
28
|
+
"schema": None,
|
|
29
|
+
"thresholds": {}, # source_max_chars, max_columns, lines_*, size_*, chars_per_token, source
|
|
30
|
+
"summary": {"critico": 0, "atencao": 0, "aviso": 0},
|
|
31
|
+
"plsql": {"total": 0, "flagged": []},
|
|
32
|
+
"wide_tables": {"max_columns": None, "items": []},
|
|
33
|
+
"no_pk": {"total": 0, "no_identity": 0, "with_unique": 0, "items": []},
|
|
34
|
+
"big_views": {"limit_chars": None, "items": []},
|
|
35
|
+
"invalid": {"total": 0, "broken": [], "stale": []},
|
|
36
|
+
"packages_no_body": {"total": 0, "declaring": [], "spec_only": []},
|
|
37
|
+
"object_rules": {"source": None, "skipped": None, "rules": 0,
|
|
38
|
+
"total_objects": 0, "excluded": 0, "by_kind": {}},
|
|
39
|
+
"encoding": {"charset": None, "is_utf8": None, "available": True,
|
|
40
|
+
"source_objects": [], "comments": []},
|
|
41
|
+
"timings": [],
|
|
42
|
+
"errors": [],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def to_json(report: dict) -> str:
|
|
47
|
+
return json.dumps(report, ensure_ascii=False, indent=2, default=str)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ─────────────────────────── HTML ───────────────────────────
|
|
51
|
+
_CSS = """
|
|
52
|
+
:root{--red:#C8102E;--ink:#111;--muted:#6B7280;--line:#E5E7EB;--soft:#F7F7F8}
|
|
53
|
+
*{box-sizing:border-box}body{font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;
|
|
54
|
+
color:var(--ink);margin:0;background:#fff}main{max-width:1100px;margin:0 auto;padding:32px 24px}
|
|
55
|
+
header{border-bottom:3px solid var(--red);padding-bottom:12px;margin-bottom:20px}
|
|
56
|
+
h1{font-size:26px;margin:0 0 4px}h2{font-size:18px;color:var(--red);margin:32px 0 8px;
|
|
57
|
+
border-left:4px solid var(--red);padding-left:10px}h3{font-size:14px;margin:18px 0 6px}
|
|
58
|
+
.sub{color:var(--muted);font-size:14px}.kpis{display:grid;grid-template-columns:repeat(5,1fr);
|
|
59
|
+
gap:10px;margin:18px 0}.kpi{border:1px solid var(--line);border-radius:8px;padding:10px;text-align:center}
|
|
60
|
+
.kpi b{display:block;font-size:24px;color:var(--red)}.kpi span{font-size:11px;color:var(--muted);text-transform:uppercase}
|
|
61
|
+
p{line-height:1.5;font-size:14px}.note{font-size:12px;color:var(--muted)}
|
|
62
|
+
table{border-collapse:collapse;width:100%;font-size:12px;margin:8px 0}th{background:var(--ink);color:#fff;
|
|
63
|
+
text-align:left;padding:5px 6px;font-weight:600}td{border-bottom:1px solid var(--line);padding:4px 6px;vertical-align:top}
|
|
64
|
+
tr:nth-child(even) td{background:var(--soft)}td.n,th.n{text-align:right;white-space:nowrap}
|
|
65
|
+
code,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11.5px}
|
|
66
|
+
.lvl-CRITICO{color:var(--red);font-weight:700}.lvl-ATENCAO{color:#B45309;font-weight:600}.lvl-AVISO{color:var(--muted)}
|
|
67
|
+
.cols{columns:3;column-gap:18px;font-size:11.5px;line-height:1.6}.cols div{break-inside:avoid}
|
|
68
|
+
ul{font-size:14px;line-height:1.5}footer{margin-top:36px;padding-top:10px;border-top:1px solid var(--line);
|
|
69
|
+
font-size:11px;color:var(--muted)}@media print{main{padding:0}h2{break-after:avoid}tr{break-inside:avoid}
|
|
70
|
+
.cols{columns:3}a[href]:after{content:""}}
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _e(v) -> str:
|
|
75
|
+
return _html.escape("" if v is None else str(v))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _n(v) -> str:
|
|
79
|
+
try:
|
|
80
|
+
return f"{int(v):,}".replace(",", ".")
|
|
81
|
+
except (TypeError, ValueError):
|
|
82
|
+
return _e(v)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _lvl(level: str) -> str:
|
|
86
|
+
cls = (level or "").replace("Í", "I").replace("Ç", "C").replace("Ã", "A")
|
|
87
|
+
return f'<span class="lvl-{cls}">{_e(level)}</span>'
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _table(headers, rows, numeric=()):
|
|
91
|
+
th = "".join(f'<th class="{"n" if i in numeric else ""}">{_e(h)}</th>' for i, h in enumerate(headers))
|
|
92
|
+
body = []
|
|
93
|
+
for r in rows:
|
|
94
|
+
tds = []
|
|
95
|
+
for i, c in enumerate(r):
|
|
96
|
+
cls = ' class="n"' if i in numeric else ""
|
|
97
|
+
tds.append(f"<td{cls}>{c}</td>")
|
|
98
|
+
body.append("<tr>" + "".join(tds) + "</tr>")
|
|
99
|
+
return f"<table><thead><tr>{th}</tr></thead><tbody>{''.join(body)}</tbody></table>"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _cols(items) -> str:
|
|
103
|
+
return '<div class="cols">' + "".join(f"<div>{_e(i)}</div>" for i in items) + "</div>"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def to_html(report: dict, client: str | None = None) -> str:
|
|
107
|
+
r = report
|
|
108
|
+
db = r.get("database") or {}
|
|
109
|
+
th = r.get("thresholds") or {}
|
|
110
|
+
s = r.get("summary") or {}
|
|
111
|
+
schema = _e(r.get("schema"))
|
|
112
|
+
title = f"Pré-voo de documentação — {schema}" + (f" — {_e(client)}" if client else "")
|
|
113
|
+
out = [f"<!doctype html><html lang='pt-BR'><head><meta charset='utf-8'>"
|
|
114
|
+
f"<meta name='viewport' content='width=device-width,initial-scale=1'>"
|
|
115
|
+
f"<title>{title}</title><style>{_CSS}</style></head><body><main>"]
|
|
116
|
+
out.append(f"<header><h1>{title}</h1><div class='sub'>Banco {_e(db.get('alias'))} "
|
|
117
|
+
f"({_e(db.get('host'))}:{_e(db.get('port'))}/{_e(db.get('service'))}, usuário {_e(db.get('user'))}) · "
|
|
118
|
+
f"gerado em {_e(r.get('generated_at'))} · baucli {_e(r.get('baucli_version'))}</div></header>")
|
|
119
|
+
out.append("<div class='kpis'>"
|
|
120
|
+
f"<div class='kpi'><b>{s.get('critico', 0)}</b><span>crítico</span></div>"
|
|
121
|
+
f"<div class='kpi'><b>{s.get('atencao', 0)}</b><span>atenção</span></div>"
|
|
122
|
+
f"<div class='kpi'><b>{s.get('aviso', 0)}</b><span>aviso</span></div>"
|
|
123
|
+
f"<div class='kpi'><b>{_n(r['plsql'].get('total'))}</b><span>objetos PL/SQL</span></div>"
|
|
124
|
+
f"<div class='kpi'><b>{_n(r['no_pk'].get('total'))}</b><span>tabelas sem PK</span></div></div>")
|
|
125
|
+
out.append("<p>Leitura de catálogo, sem alterar nada e sem ler dados da base: o que o schema tem hoje e que "
|
|
126
|
+
"influencia a documentação assistida por IA. <b>CRÍTICO</b> impede a IA numa chamada (precisa de "
|
|
127
|
+
"fatiamento, refatoração ou provedor com janela maior); <b>ATENÇÃO</b> documenta, mas pede revisão; "
|
|
128
|
+
"<b>AVISO</b> é só registro.</p>")
|
|
129
|
+
out.append(f"<p class='note'>Limiares: {_n(th.get('source_max_chars'))} caracteres por chamada de IA · tabela até "
|
|
130
|
+
f"{_e(th.get('max_columns'))} colunas no prompt · corpo de package com {_n(th.get('lines_unsafe'))} linhas "
|
|
131
|
+
f"ou mais é edição insegura · fonte dos limiares: {_e(th.get('source'))}.</p>")
|
|
132
|
+
|
|
133
|
+
# PL/SQL
|
|
134
|
+
pl = r["plsql"]
|
|
135
|
+
out.append(f"<h2>1. Rotinas PL/SQL sinalizadas</h2><p>{_n(pl.get('total'))} objetos no schema, "
|
|
136
|
+
f"<b>{len(pl['flagged'])}</b> sinalizados.</p>")
|
|
137
|
+
if pl["flagged"]:
|
|
138
|
+
out.append(_table(["Nível", "Tipo", "Objeto", "Linhas", "KB", "~tokens", "Por quê"],
|
|
139
|
+
[[_lvl(f["level"]), _e(f["type"]), f"<code>{_e(f['name'])}</code>", _n(f["lines"]),
|
|
140
|
+
_n(round(f["chars"] / 1024)), _n(f["tokens"]), _e(f["reason"])] for f in pl["flagged"]],
|
|
141
|
+
numeric=(3, 4, 5)))
|
|
142
|
+
|
|
143
|
+
# wide
|
|
144
|
+
w = r["wide_tables"]
|
|
145
|
+
out.append(f"<h2>2. Tabelas largas</h2><p><b>{len(w['items'])}</b> tabelas com mais de {_e(w.get('max_columns'))} "
|
|
146
|
+
"colunas: a IA documenta coluna a coluna (fan-out), multiplicando chamadas e revisão.</p>")
|
|
147
|
+
if w["items"]:
|
|
148
|
+
out.append(_cols([f"{i['table']} ({i['columns']}{'; ' + str(i['lobs']) + ' LOB' if i.get('lobs') else ''})"
|
|
149
|
+
for i in w["items"]]))
|
|
150
|
+
|
|
151
|
+
# no pk
|
|
152
|
+
npk = r["no_pk"]
|
|
153
|
+
out.append(f"<h2>3. Tabelas sem chave primária</h2><p><b>{_n(npk.get('total'))}</b> tabelas sem PK: "
|
|
154
|
+
f"{_n(npk.get('no_identity'))} sem nenhuma identidade de linha e {_n(npk.get('with_unique'))} com chave "
|
|
155
|
+
"ou índice único (caso leve). Sem chave, formulários e relatórios gerados não têm como apontar o registro "
|
|
156
|
+
"e a ordenação de colunas perde o primeiro critério.</p>")
|
|
157
|
+
com = [i for i in npk["items"] if i.get("has_identity")]
|
|
158
|
+
sem = [i for i in npk["items"] if not i.get("has_identity")]
|
|
159
|
+
fmt = lambda i: f"{i['table']} ({i['columns']} col, {_n(i['rows_est']) if i.get('rows_est') is not None else '—'} lin)"
|
|
160
|
+
if com:
|
|
161
|
+
out.append(f"<h3>Com chave ou índice único ({len(com)})</h3>" + _cols([fmt(i) for i in com]))
|
|
162
|
+
if sem:
|
|
163
|
+
out.append(f"<h3>Sem identidade de linha ({len(sem)})</h3>" + _cols([fmt(i) for i in sem]))
|
|
164
|
+
|
|
165
|
+
# views
|
|
166
|
+
bv = r["big_views"]
|
|
167
|
+
out.append(f"<h2>4. Views grandes</h2><p>{len(bv['items'])} acima de {_n(bv.get('limit_chars'))} caracteres.</p>")
|
|
168
|
+
if bv["items"]:
|
|
169
|
+
out.append(_table(["View", "Chars", "~tokens"],
|
|
170
|
+
[[f"<code>{_e(i['view'])}</code>", _n(i["chars"]), _n(i["tokens"])] for i in bv["items"]],
|
|
171
|
+
numeric=(1, 2)))
|
|
172
|
+
|
|
173
|
+
# invalid
|
|
174
|
+
inv = r["invalid"]
|
|
175
|
+
out.append(f"<h2>5. Objetos inválidos</h2><p><b>{_n(inv.get('total'))}</b> objetos INVALID: {len(inv['broken'])} com "
|
|
176
|
+
f"erro de compilação e {len(inv['stale'])} invalidados em cascata. O sync extrai só objetos VALID: tudo "
|
|
177
|
+
"o que está aqui fica fora da documentação até ser resolvido.</p>")
|
|
178
|
+
if inv["broken"]:
|
|
179
|
+
out.append("<h3>Com erro de compilação</h3>" + _table(
|
|
180
|
+
["Tipo", "Objeto", "DDL", "1º erro"],
|
|
181
|
+
[[_e(i["type"]), f"<code>{_e(i['name'])}</code>", _e(i["last_ddl"]), _e(i["first_error"])] for i in inv["broken"]]))
|
|
182
|
+
if inv["stale"]:
|
|
183
|
+
out.append(f"<h3>Só recompilar ({len(inv['stale'])})</h3>" + _cols([i["name"] for i in inv["stale"]])
|
|
184
|
+
+ f"<p class='note'>Resolve com <code>EXEC DBMS_UTILITY.COMPILE_SCHEMA('{schema}', FALSE)</code>.</p>")
|
|
185
|
+
|
|
186
|
+
# no body
|
|
187
|
+
nb = r["packages_no_body"]
|
|
188
|
+
out.append(f"<h2>6. Packages sem corpo</h2><p>{_n(nb.get('total'))} packages só com especificação: "
|
|
189
|
+
f"{len(nb['declaring'])} declaram subprogramas sem corpo (falham em runtime; a documentação por "
|
|
190
|
+
f"subprograma fica sem fonte) e {len(nb['spec_only'])} são só constantes e tipos (legítimo).</p>")
|
|
191
|
+
if nb["declaring"]:
|
|
192
|
+
out.append(_table(["Package", "Subprogramas", "Spec", "DDL"],
|
|
193
|
+
[[f"<code>{_e(i['package'])}</code>", _n(i["subprograms"]), _e(i["spec_status"]), _e(i["last_ddl"])]
|
|
194
|
+
for i in nb["declaring"]], numeric=(1,)))
|
|
195
|
+
if nb["spec_only"]:
|
|
196
|
+
out.append("<p class='note'>Spec-only: " + ", ".join(_e(x) for x in nb["spec_only"]) + "</p>")
|
|
197
|
+
|
|
198
|
+
# rules
|
|
199
|
+
orr = r["object_rules"]
|
|
200
|
+
out.append("<h2>7. Objetos fora da cobertura (regras de nome)</h2>")
|
|
201
|
+
if orr.get("skipped"):
|
|
202
|
+
out.append(f"<p class='note'>Seção pulada: {_e(orr['skipped'])}.</p>")
|
|
203
|
+
else:
|
|
204
|
+
out.append(f"<p>{_e(orr.get('rules'))} regras de nome classificam objetos como não produtivos. "
|
|
205
|
+
f"<b>{_n(orr.get('excluded'))}</b> de {_n(orr.get('total_objects'))} objetos saem da cobertura.</p>")
|
|
206
|
+
for kind, names in sorted((orr.get("by_kind") or {}).items()):
|
|
207
|
+
out.append(f"<h3>{_e(kind)} ({len(names)})</h3>" + _cols(names))
|
|
208
|
+
|
|
209
|
+
# encoding
|
|
210
|
+
enc = r["encoding"]
|
|
211
|
+
out.append("<h2>8. Codificação e acentuação</h2>")
|
|
212
|
+
if not enc.get("available", True):
|
|
213
|
+
out.append("<p class='note'>Checagem indisponível.</p>")
|
|
214
|
+
else:
|
|
215
|
+
out.append(f"<p>Charset do banco: <b>{_e(enc.get('charset'))}</b>"
|
|
216
|
+
+ (" (UTF-8)." if enc.get("is_utf8") else ". Não é UTF-8: o BAU emite anotações sem acento neste banco; "
|
|
217
|
+
"COMMENT ON não sofre dessa limitação.") + "</p>")
|
|
218
|
+
if enc["source_objects"]:
|
|
219
|
+
out.append(f"<p>{len(enc['source_objects'])} objeto(s) PL/SQL com texto UTF-8 gravado como single-byte:</p>"
|
|
220
|
+
+ _table(["Objeto", "Tipo", "Linhas"],
|
|
221
|
+
[[f"<code>{_e(i['name'])}</code>", _e(i["type"]), _n(i["lines"])] for i in enc["source_objects"]],
|
|
222
|
+
numeric=(2,)))
|
|
223
|
+
if enc["comments"]:
|
|
224
|
+
out.append(f"<p>{len(enc['comments'])} comentário(s) com sinal de acentuação quebrada:</p>"
|
|
225
|
+
+ _table(["Onde", "Tabela", "Coluna", "Sinal", "Trecho"],
|
|
226
|
+
[[_e(i["where"]), f"<code>{_e(i['table'])}</code>", f"<code>{_e(i['column'])}</code>",
|
|
227
|
+
_e(i["signals"]), _e((i.get("text") or "")[:90])] for i in enc["comments"]]))
|
|
228
|
+
if enc["source_objects"] or enc["comments"]:
|
|
229
|
+
out.append("<p class='note'>Estes problemas estão no banco de origem agora, antes de o BAU escrever qualquer "
|
|
230
|
+
"coisa; o sync os registra como pré-existentes. A documentação gerada pela IA, aplicada de volta, os corrige.</p>")
|
|
231
|
+
elif enc.get("is_utf8"):
|
|
232
|
+
out.append("<p>Nenhum sinal de acentuação quebrada.</p>")
|
|
233
|
+
|
|
234
|
+
# timings
|
|
235
|
+
if r.get("timings"):
|
|
236
|
+
tot = sum(t["seconds"] for t in r["timings"])
|
|
237
|
+
out.append(f"<h2>9. Tempos do diagnóstico</h2><p class='note'>Total {tot:.1f}s em {len(r['timings'])} etapas.</p>"
|
|
238
|
+
+ _table(["Etapa", "Tempo", "Linhas"],
|
|
239
|
+
[[_e(t["step"]), f"{t['seconds']:.2f}s", "erro" if t["rows"] < 0 else _n(t["rows"])]
|
|
240
|
+
for t in sorted(r["timings"], key=lambda t: -t["seconds"])], numeric=(1, 2)))
|
|
241
|
+
if r.get("errors"):
|
|
242
|
+
out.append("<h2>Avisos</h2><ul>" + "".join(f"<li>{_e(x)}</li>" for x in r["errors"]) + "</ul>")
|
|
243
|
+
|
|
244
|
+
out.append("<footer>BAU — BEG Application Utilities · baucli db check · www.begcloud.com</footer></main></body></html>")
|
|
245
|
+
return "".join(out)
|
|
@@ -275,6 +275,33 @@ Ordem de consulta (pare no primeiro acerto):
|
|
|
275
275
|
- Tools MCP ausentes → `baucli mcp --install` e reabrir a sessao. NAO caia
|
|
276
276
|
para "gerar no escuro": duplicar e mais caro que perguntar.
|
|
277
277
|
|
|
278
|
+
## ORCAMENTO DE TAMANHO: antes de acrescentar, meca (ORA-SIZ-01)
|
|
279
|
+
|
|
280
|
+
Package grande nao nasce grande: cresce uma procedure por vez, cada uma
|
|
281
|
+
"so mais uma". A regua tem a regra `ORA-SIZ-01` (subprograma ~150 linhas,
|
|
282
|
+
body ~1.500, bem abaixo de `DOCPL.LINES_CAUTION` e `LINES_UNSAFE`); os numeros
|
|
283
|
+
vigentes deste schema estao em `resolved/guidelines.md`, nao aqui. Quando a
|
|
284
|
+
mudanca ACRESCENTA codigo a um package que ja existe:
|
|
285
|
+
|
|
286
|
+
1. Meca antes de escrever: `bau_object(<PKG>)` traz linhas e a banda de edicao
|
|
287
|
+
(`ai_edit_safety`); `bau_large_routines()` lista de uma vez tudo que ja esta
|
|
288
|
+
em CAUTION/UNSAFE no schema. So vale banda com `est_tokens` preenchido --
|
|
289
|
+
UNSAFE com tokens nulos e classificacao que falhou, nao tamanho.
|
|
290
|
+
2. SAFE e a soma continua abaixo do orcamento → pode acrescentar ali.
|
|
291
|
+
3. CAUTION ou UNSAFE, ou a soma cruza `LINES_CAUTION` → o codigo novo nasce em
|
|
292
|
+
**package irmao do mesmo dominio** (`PKG_<DOMINIO>_<ASSUNTO>`), e o antigo
|
|
293
|
+
passa a delegar se precisar expor a mesma interface. O package que ja
|
|
294
|
+
passou do limite NUNCA cresce, nem "so desta vez".
|
|
295
|
+
4. O corte e por **dominio funcional** (o que `bau_schema_context` descreve
|
|
296
|
+
para este schema), nao pela ordem de chegada. Um irmao chamado
|
|
297
|
+
`PKG_X_NOVO` ou `PKG_X_2` e o sinal de que o corte foi errado.
|
|
298
|
+
5. Diga ao usuario o que mediu e por que escolheu onde o codigo foi parar.
|
|
299
|
+
Desviar de `ORA-SIZ-01` por motivo concreto e aceitavel; desviar em
|
|
300
|
+
silencio vira achado do DOCREV.
|
|
301
|
+
|
|
302
|
+
Excecoes da propria regra: package gerado (ORDS, APEX, wrapper de API) e
|
|
303
|
+
package so de constantes/tipos, sem logica.
|
|
304
|
+
|
|
278
305
|
## A regra que muda tudo: NAO escreva o cabecalho
|
|
279
306
|
|
|
280
307
|
No BAU o cabecalho e um **artefato derivado**, nao algo que se digita:
|
|
@@ -384,6 +411,8 @@ Um arquivo executavel por objeto: o bloco `CREATE OR REPLACE` + `/` no fim.
|
|
|
384
411
|
- Escrever PL/SQL sem checar `resolved/guidelines.md` primeiro -- inclui
|
|
385
412
|
`WHEN OTHERS THEN NULL`, DML linha a linha em loop, SQL dinamico concatenado
|
|
386
413
|
e as demais regras la listadas.
|
|
414
|
+
- Acrescentar subprograma a um package em CAUTION/UNSAFE sem medir antes
|
|
415
|
+
(`bau_object`) -- o codigo novo vai para package irmao (`ORA-SIZ-01`).
|
|
387
416
|
""" + LESSONS_CROSSREF_MD
|
|
388
417
|
|
|
389
418
|
|
|
@@ -517,6 +546,10 @@ estar em UTC e o BAUCTX em -3h).
|
|
|
517
546
|
`bau_impact(<NOME>)` (quem chama quebra?).
|
|
518
547
|
- Se a rotina tem `refactor` recomendado no resolved/, considere propor a
|
|
519
548
|
quebra do pacote em vez de empilhar mais codigo nele.
|
|
549
|
+
- **Acrescentar codigo NOVO a rotina CAUTION/UNSAFE: nao.** Corrigir o que
|
|
550
|
+
existe, por subprograma, sim; subprograma novo nasce em package irmao do
|
|
551
|
+
mesmo dominio (`ORA-SIZ-01`, passo "orcamento de tamanho" da skill
|
|
552
|
+
`bau-plsql-header`). O package que ja passou do limite nunca cresce.
|
|
520
553
|
|
|
521
554
|
## Regras de edicao (cicatrizes de campo -- todas ja custaram um deploy)
|
|
522
555
|
|
|
@@ -557,6 +590,8 @@ estar em UTC e o BAUCTX em -3h).
|
|
|
557
590
|
## NUNCA
|
|
558
591
|
|
|
559
592
|
- Reescrever inteira uma rotina CAUTION/UNSAFE "para ficar mais facil".
|
|
593
|
+
- Empilhar subprograma novo numa rotina CAUTION/UNSAFE em vez de abrir o
|
|
594
|
+
package irmao.
|
|
560
595
|
- Confiar em VALID como prova de deploy aplicado.
|
|
561
596
|
- Editar entre marcadores BAU:HEADER.
|
|
562
597
|
- Deployar corpo de package com QUALQUER coisa depois do `/` no arquivo.
|
|
@@ -11,6 +11,7 @@ baucli/api.py
|
|
|
11
11
|
baucli/canon.py
|
|
12
12
|
baucli/cli.py
|
|
13
13
|
baucli/config.py
|
|
14
|
+
baucli/db_check_report.py
|
|
14
15
|
baucli/democrm.py
|
|
15
16
|
baucli/diffenvs.py
|
|
16
17
|
baucli/docmig.py
|
|
@@ -67,6 +68,7 @@ tests/test_apexlint_dominio.py
|
|
|
67
68
|
tests/test_api_request_db.py
|
|
68
69
|
tests/test_canon_anchored_markers.py
|
|
69
70
|
tests/test_canon_multiengine.py
|
|
71
|
+
tests/test_db_check_report.py
|
|
70
72
|
tests/test_db_tenant_guard.py
|
|
71
73
|
tests/test_delphi_canon.py
|
|
72
74
|
tests/test_delphi_datasnap.py
|
|
@@ -110,6 +112,7 @@ tests/test_scope_scan_owner.py
|
|
|
110
112
|
tests/test_scope_scan_pkg_func_from.py
|
|
111
113
|
tests/test_skills_apex_domain.py
|
|
112
114
|
tests/test_skills_lessons.py
|
|
115
|
+
tests/test_skills_size_budget.py
|
|
113
116
|
tests/test_spec_sem_beg.py
|
|
114
117
|
tests/test_sync_413.py
|
|
115
118
|
tests/test_sync_charset.py
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""db check --format: o dict do pré-voo vira JSON/HTML sem banco."""
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
from baucli.db_check_report import SCHEMA_VERSION, empty_report, to_html, to_json
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _sample():
|
|
8
|
+
r = empty_report()
|
|
9
|
+
r["baucli_version"] = "9.9.9"
|
|
10
|
+
r["schema"] = "COMPIERE"
|
|
11
|
+
r["database"] = {"alias": "ziz_multisc", "engine": "oracle", "host": "144.33.23.40",
|
|
12
|
+
"port": 1521, "service": "multisc", "user": "COMPIERE"}
|
|
13
|
+
r["thresholds"] = {"source_max_chars": 50000, "max_columns": 30, "lines_unsafe": 6000,
|
|
14
|
+
"chars_per_token": 4.0, "source": "BAU Server"}
|
|
15
|
+
r["summary"] = {"critico": 1, "atencao": 2, "aviso": 1}
|
|
16
|
+
r["plsql"] = {"total": 10, "flagged": [
|
|
17
|
+
{"level": "CRÍTICO", "type": "PACKAGE BODY", "name": "NAC_PCK_MKT_CAMPANHA",
|
|
18
|
+
"lines": 27898, "chars": 1291000, "tokens": 322750, "reason": "edição por IA insegura"}]}
|
|
19
|
+
r["wide_tables"] = {"max_columns": 30, "items": [{"table": "NAC_RH_CST_GESTAX", "columns": 614, "lobs": 0}]}
|
|
20
|
+
r["no_pk"] = {"total": 2, "no_identity": 1, "with_unique": 1, "items": [
|
|
21
|
+
{"table": "AD_ORG_BKP", "columns": 14, "rows_est": 67, "uks": 0, "unique_indexes": 0, "has_identity": False},
|
|
22
|
+
{"table": "BAU_CONFIG", "columns": 9, "rows_est": None, "uks": 1, "unique_indexes": 0, "has_identity": True}]}
|
|
23
|
+
r["invalid"] = {"total": 2,
|
|
24
|
+
"broken": [{"type": "FUNCTION", "name": "BEG_FNC_RETORNA_IPI", "last_ddl": "22/09/26 10:20",
|
|
25
|
+
"first_error": "PL/SQL: ORA-00918: coluna <ambígua>"}],
|
|
26
|
+
"stale": [{"type": "PROCEDURE", "name": "NAC_PRC_B2B_REC_ITENS", "last_ddl": "22/09/26 10:21"}]}
|
|
27
|
+
r["packages_no_body"] = {"total": 2, "declaring": [
|
|
28
|
+
{"package": "PCK_IMPORTACAO_MULTINAC", "subprograms": 26, "spec_status": "VALID", "last_ddl": "09/01/25 08:36"}],
|
|
29
|
+
"spec_only": ["PKG_URLS"]}
|
|
30
|
+
r["object_rules"] = {"source": "BAU Server", "skipped": None, "rules": 31, "total_objects": 6522,
|
|
31
|
+
"excluded": 2, "by_kind": {"BACKUP": ["AD_ORG_BKP"], "TEMP": ["NAC_TMP"]}}
|
|
32
|
+
r["encoding"] = {"charset": "WE8ISO8859P1", "is_utf8": False, "available": True,
|
|
33
|
+
"source_objects": [{"name": "FNC_LIMPA_STR", "type": "FUNCTION", "lines": 16}],
|
|
34
|
+
"comments": [{"where": "COLUNA", "table": "BEG_CPG_RENEG", "column": "NAME",
|
|
35
|
+
"signals": "interrogacao", "text": "Descric?o da renegociac?o"}]}
|
|
36
|
+
r["timings"] = [{"step": "conexao ao banco", "seconds": 0.75, "rows": 0},
|
|
37
|
+
{"step": "PL/SQL: tamanho por objeto", "seconds": 5.85, "rows": 2923}]
|
|
38
|
+
return r
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_json_roundtrip_keeps_everything():
|
|
42
|
+
r = _sample()
|
|
43
|
+
back = json.loads(to_json(r))
|
|
44
|
+
assert back["schema_version"] == SCHEMA_VERSION
|
|
45
|
+
assert back["summary"] == {"critico": 1, "atencao": 2, "aviso": 1}
|
|
46
|
+
assert back["plsql"]["flagged"][0]["name"] == "NAC_PCK_MKT_CAMPANHA"
|
|
47
|
+
assert back["no_pk"]["items"][1]["rows_est"] is None
|
|
48
|
+
assert back["object_rules"]["by_kind"]["TEMP"] == ["NAC_TMP"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_empty_report_has_every_section():
|
|
52
|
+
r = empty_report()
|
|
53
|
+
for k in ("plsql", "wide_tables", "no_pk", "big_views", "invalid",
|
|
54
|
+
"packages_no_body", "object_rules", "encoding", "timings", "summary"):
|
|
55
|
+
assert k in r
|
|
56
|
+
# HTML de um relatório vazio não pode quebrar (schema limpo é o caso feliz)
|
|
57
|
+
html = to_html(r)
|
|
58
|
+
assert "<html" in html and "Pré-voo" in html
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_html_lists_full_names_and_escapes():
|
|
62
|
+
html = to_html(_sample(), client="Ziz Performance")
|
|
63
|
+
for name in ("NAC_PCK_MKT_CAMPANHA", "NAC_RH_CST_GESTAX", "AD_ORG_BKP", "BAU_CONFIG",
|
|
64
|
+
"BEG_FNC_RETORNA_IPI", "NAC_PRC_B2B_REC_ITENS", "PCK_IMPORTACAO_MULTINAC",
|
|
65
|
+
"PKG_URLS", "NAC_TMP", "FNC_LIMPA_STR", "BEG_CPG_RENEG"):
|
|
66
|
+
assert name in html, name
|
|
67
|
+
assert "Ziz Performance" in html
|
|
68
|
+
assert "WE8ISO8859P1" in html
|
|
69
|
+
# o "<ambígua>" do erro Oracle vira entidade, não tag
|
|
70
|
+
assert "<ambígua>" in html and "<ambígua>" not in html
|
|
71
|
+
# sem recurso externo: um arquivo só
|
|
72
|
+
assert "http" not in html.split("<footer>")[0].replace("http-equiv", "")
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""ORA-SIZ-01: as skills geradas levam o orcamento de tamanho para o momento de
|
|
2
|
+
CRIAR, nao so de editar (bau-oracle PR #219 / lição BAU 2218)."""
|
|
3
|
+
from baucli import skills
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_header_skill_manda_medir_antes_de_acrescentar():
|
|
7
|
+
md = skills.SKILL_MD
|
|
8
|
+
assert "ORA-SIZ-01" in md
|
|
9
|
+
assert "bau_object(<PKG>)" in md
|
|
10
|
+
assert "bau_large_routines()" in md
|
|
11
|
+
assert "package irmao" in md.lower()
|
|
12
|
+
# os numeros vigentes vem da regua resolvida, nao ficam fixos na skill
|
|
13
|
+
assert "resolved/guidelines.md" in md
|
|
14
|
+
assert "LINES_CAUTION" in md
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_header_skill_distingue_unsafe_por_falha():
|
|
18
|
+
assert "tokens nulos" in skills.SKILL_MD
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_edit_safety_nao_deixa_rotina_grande_crescer():
|
|
22
|
+
md = skills.EDIT_SAFETY_SKILL_MD
|
|
23
|
+
assert "ORA-SIZ-01" in md
|
|
24
|
+
assert "nunca cresce" in md.lower()
|
|
25
|
+
assert "package irmao" in md.lower()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|