Skip to content

Releases

v3.0.0

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 20 Jul 18:46
769aa29

CNPJ alfanumérico e docs/schema em português

A versão 3.0.0 do CNPJ DB Loader introduz suporte completo ao novo formato alfanumérico do CNPJ e migra para português toda a estrutura do banco de dados gerado.

CNPJ alfanumérico

O loader passa a aceitar CNPJs com:

  • 8 posições alfanuméricas para o CNPJ básico;
  • 4 posições alfanuméricas para a ordem;
  • 2 dígitos verificadores numéricos.

Caracteres de 0-9 e A-Z são aceitos nos segmentos alfanuméricos. Os CNPJs exclusivamente numéricos continuam válidos.

Exemplo:

12.ABC.345/01DE-35

O cálculo dos dígitos verificadores segue a regra oficial, utilizando o valor correspondente ao código ASCII do caractere menos 48.

Domínio centralizado

As operações de CNPJ foram concentradas em um único módulo responsável por:

  • normalização;
  • validação;
  • composição;
  • formatação;
  • separação dos segmentos;
  • cálculo dos dígitos verificadores.

Não são utilizadas conversões para number, parseInt, bigint ou outros tipos numéricos sobre os segmentos do CNPJ.

Essa decisão evita perda de zeros à esquerda e garante suporte seguro aos caracteres alfanuméricos.

Banco de dados em português

Todas as tabelas, colunas, constraints e índices passam a utilizar nomes em português, no padrão snake_case e sem acentos.

Alguns exemplos:

  • companies → empresas;
  • establishments → estabelecimentos;
  • partners → socios;
  • simples_options → simples;
  • import_plans → planos_importacao;
  • import_quarantine → quarentena_importacao.

A alteração também se aplica às tabelas de domínio, staging, checkpoints, quarentena e controle das importações.

Tipos textuais para o CNPJ

Os campos abaixo passam a ser armazenados exclusivamente como texto:

  • cnpj_basico;
  • cnpj_ordem;
  • cnpj_dv;
  • cnpj_completo.

O banco aplica validações de comprimento e charset por meio de constraints CHECK.

A composição do CNPJ completo preserva exatamente as 14 posições, sem conversões numéricas e sem remoção de zeros à esquerda.

Novo grupo rfb

O grupo de comandos:

cnpj-db-loader federal-revenue

foi renomeado para:

cnpj-db-loader rfb

O nome antigo permanece disponível temporariamente como alias e exibe um aviso de depreciação. Ele será removido em uma futura versão.

Os comandos e as flags da CLI continuam em inglês.

Geração de schema e scripts

Os seguintes componentes foram atualizados para gerar exclusivamente o schema 3.0.0 em português:

  • schema generate;
  • sql/schema.sql;
  • builders SQL em TypeScript;
  • estruturas de staging;
  • tabelas de controle de importação;
  • gerador postgres generate-script.

A deduplicação dos estabelecimentos passa a utilizar cnpj_completo, enquanto a deduplicação de sócios utiliza chave_deduplicacao_socio.

Atenção: atualização incompatível

Não existe migração automática de bancos 2.x para o schema 3.0.0.

Também não são criadas views, aliases ou adaptadores em inglês para manter compatibilidade com consumidores anteriores.

Para atualizar com segurança:

  1. faça backup da base 2.x;
  2. não atualize diretamente o ambiente de produção;
  3. gere o novo schema com cnpj-db-loader schema generate;
  4. crie um novo banco para a versão 3.0.0;
  5. aplique o schema gerado;
  6. reimporte os dados;
  7. valide contagens e amostras de CNPJs numéricos e alfanuméricos;
  8. altere os ambientes somente após a homologação.

Limitações conhecidas

  • bancos da versão 2.x precisam ser recriados e reimportados;
  • não há conversão automática do schema anterior;
  • o alias federal-revenue é temporário e será removido futuramente.

v2.4.0

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 30 May 19:38
715d35c

Hybrid PostgreSQL Import and Data Preparation Improvements

This release introduces a new hybrid PostgreSQL direct import workflow and improves the preparation of RFB datasets for large-scale database loading.

The CNPJ DB Loader can now handle extraction, validation and sanitization while PostgreSQL performs the heavier loading and materialization steps directly from sanitized source files.

Hybrid PostgreSQL direct import

  • Added postgres generate-script support for generating PostgreSQL direct import scripts.
  • Added direct psql-based loading from sanitized Receita Federal files.
  • Added PostgreSQL-side raw loading, staging and materialization.
  • Added generation of establishment_secondary_cnaes.
  • Added modular SQL scripts by phase.
  • Added import-postgres-direct.sql as the orchestration script.
  • Added manifest metadata with generated steps and dependencies.

Transaction modes

Added configurable transaction strategies:

  • single: uses one transaction for the entire import. It is the safest option because everything is committed only at the end, but any failure requires restarting the complete run.
  • phase: uses one transaction per generated phase. It is the recommended option for large imports because completed phases remain committed and failures are easier to isolate and rerun.
  • none: does not wrap generated scripts in explicit transactions. It can be faster for local benchmarks or disposable databases, but failures may leave partially imported data.

Selective script generation

  • Added --include support for generating only selected phases.
  • Added --skip-indexes support.
  • Added --skip-analyze support.
  • Added clearer \echo messages for long-running PostgreSQL operations.
  • Added PostgreSQL monitoring documentation and ready-to-use SQL snippets.

Hybrid quarantine handling

  • Added quarantine handling during hybrid staging validation.
  • Reused the existing import_quarantine table and operational model.
  • Preserved compatibility with the Node-driven import flow.
  • Added summarized logs and checkpoints for quarantined records.

Technical limitation

Because hybrid validation happens after the raw COPY step, the exact original byte offset may not always be available. In these cases, checkpoint_offset can remain NULL, and raw_line is stored as a textual JSON representation of the raw temporary row.

Federal Revenue configuration

  • Added federal-revenue config set.
  • Added federal-revenue config show.
  • Added federal-revenue config test.
  • Added federal-revenue config reset.
  • Added support for configuring share-token, webdav-url and user-agent.

Large ZIP and ZIP64 extraction

  • Added support for large ZIP and ZIP64 archives.
  • Added support for split ZIP volumes such as .zip.001.
  • Added automatic detection of supported split archive entry points.
  • Added safer extraction using temporary directories before replacing the final destination.
  • Fixed extraction failures where valid large archives could be incorrectly reported as unsupported multi-disk ZIP files.

Sanitization encoding improvements

  • Added streaming normalization from ISO-8859-1 / LATIN1 to UTF-8.
  • Added byte-level removal of NUL characters.
  • Added detection of Unicode replacement characters (�).
  • Added temporary output files and safe replacement after validation.
  • Added optional --allow-replacement-chars support for controlled manual inspection.
  • Preserved the existing sanitization command behavior.

Recommended flow

Download the current Receita Federal reference:

cnpj-db-loader federal-revenue download --current --output C:\ReceitaDB

Then use the generated reference directory in the next steps:

cnpj-db-loader extract C:\ReceitaDB\2026-05

cnpj-db-loader validate C:\ReceitaDB\2026-05\extracted

cnpj-db-loader sanitize C:\ReceitaDB\2026-05\extracted --output C:\ReceitaDB\2026-05\sanitized --force

cnpj-db-loader postgres generate-script C:\ReceitaDB\2026-05\sanitized --output C:\ReceitaDB\2026-05\postgres-direct --source-encoding UTF8 --transaction-mode phase --force

psql -d "postgres://postgres:postgres@localhost:5432/cnpj" -f "C:\ReceitaDB\2026-05\postgres-direct\import-postgres-direct.sql"

The --current flag automatically selects the current RFB reference during download.

Notes

For large imports, phase is the recommended transaction mode because it provides a practical balance between safety and recoverability.

v2.4.0-beta.7

v2.4.0-beta.7 Pre-release
Pre-release

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 30 May 19:02
b34a497

Sanitization Encoding Fix

This beta release fixes the sanitization flow for Receita Federal source files encoded as ISO-8859-1 / LATIN1.

Sanitized files are now normalized to UTF-8 before parsing and database import, preventing corrupted accented characters from being persisted in PostgreSQL.

Fixed

  • Fixed incorrect encoding normalization during sanitization.
  • Fixed corrupted Portuguese characters caused by decoding source files before proper normalization.
  • Fixed NUL byte handling by removing 0x00 at byte level.
  • Fixed unsafe output replacement by validating temporary files before promoting them to the final sanitized destination.

Added

  • Added streaming file normalization to support large Receita Federal datasets without loading entire files into memory.
  • Added detection of Unicode replacement characters (�) in sanitized output.
  • Added optional --allow-replacement-chars support for controlled manual inspection.

Notes

The normal sanitization command remains unchanged:

cnpj-db-loader sanitize <input> --output <output> --force

By default, the loader now reads RFB source files as LATIN1 and produces validated UTF-8 output ready for import.

v2.4.0-beta.6

v2.4.0-beta.6 Pre-release
Pre-release

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 30 May 17:45
3cc88e1

Large ZIP and ZIP64 Archive Support

This beta release improves archive extraction for large Receita Federal datasets.

The extraction flow now supports standard ZIP archives, ZIP64 archives and split ZIP volumes through a dedicated 7-Zip-based extractor.

Added

  • Added support for large ZIP and ZIP64 archives.
  • Added support for split ZIP volumes such as .zip.001.
  • Added automatic detection of supported split archive entry points.
  • Added safer extraction using temporary directories before replacing the final destination.

Fixed

  • Fixed extraction failures where valid large Receita Federal archives could be incorrectly reported as unsupported multi-disk ZIP files.

v2.4.0-beta.5

v2.4.0-beta.5 Pre-release
Pre-release

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 29 May 23:57
fc6c7e8

Hybrid Import Quarantine Handling

This beta release adds quarantine handling to the hybrid PostgreSQL direct import flow.

Invalid records detected during staging validation are now sent to the existing import_quarantine table, preserving the same quarantine model and compatibility used by the Node-driven import flow.

Added

  • Added quarantine handling for invalid records during hybrid staging validation.
  • Reused the existing import_quarantine structure without introducing a separate quarantine model.
  • Added summarized logs and checkpoints for quarantined records.

Technical limitation

Because hybrid validation happens after the raw COPY step, the exact original byte offset may not always be available. In these cases, checkpoint_offset can remain NULL, and raw_line is stored as a textual JSON representation of the raw temporary row.

v2.4.0-beta.4

v2.4.0-beta.4 Pre-release
Pre-release

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 26 May 15:49

Federal Revenue Configuration

This beta release adds support for configuring Federal Revenue file access directly through the CLI.

It is now possible to configure the share-token, WebDAV URL and request user agent used by the Federal Revenue integration, storing these values in the local CNPJ DB Loader configuration file.

Added

  • Added federal-revenue config set.
  • Added federal-revenue config show.
  • Added federal-revenue config test.
  • Added federal-revenue config reset.
  • Added support for configuring share-token.
  • Added support for configuring webdav-url.
  • Added support for configuring user-agent.

Example

cnpj-db-loader federal-revenue config set share-token "<public-share-token>"
cnpj-db-loader federal-revenue config test
cnpj-db-loader federal-revenue config show

v2.4.0-beta.3

v2.4.0-beta.3 Pre-release
Pre-release

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 25 May 21:18

Modular Hybrid PostgreSQL Import

This beta release improves the hybrid PostgreSQL direct import mode by making the generated SQL flow modular, configurable and easier to monitor during large Receita Federal dataset imports.

The main goal of this version is to make the hybrid import path more flexible and easier to operate, especially for long-running database loads.

Added

  • Added --transaction-mode support for PostgreSQL direct import script generation.
  • Added support for transaction modes:
    • single: uses one transaction for the entire import. It is the safest option because everything is committed only at the end, but if any phase fails, the whole run is rolled back and must be restarted.

    • phase: uses one transaction per generated phase. It is the recommended option for large imports because completed phases can remain committed, making failures easier to isolate and rerun later.

    • none: does not wrap the generated scripts in explicit transactions. It can be faster for local benchmarks or disposable databases, but it is less safe because failures may leave partially imported data.

  • Added modular SQL script generation by phase.
  • Added import-postgres-direct.sql as the orchestration script.
  • Added generated scripts for individual import phases, including:
    • setup.sql
    • load-domains.sql
    • load-companies.sql
    • load-establishments.sql
    • load-partners.sql
    • load-simples.sql
    • materialize.sql
    • materialize-secondary-cnaes.sql
    • indexes.sql
    • analyze.sql
  • Added manifest metadata with generated steps and dependencies.
  • Added --include support to generate only selected phases.
  • Added --skip-indexes support.
  • Added --skip-analyze support.
  • Added clearer \echo messages in generated SQL scripts.
  • Added PostgreSQL monitoring documentation.
  • Added ready-to-use SQL snippets for:
    • active queries through pg_stat_activity;
    • COPY progress through pg_stat_progress_copy;
    • lock inspection;
    • table size inspection.

Changed

  • The hybrid PostgreSQL import script is no longer generated as a single large SQL file only.
  • The generated import flow is now split into smaller SQL files by responsibility.
  • The main import script now works as an orchestrator that executes the generated phase scripts in the correct order.
  • The manifest now provides more useful information about generated steps and dependencies.
  • PostgreSQL direct import logs are easier to follow during long-running executions.

Why this matters

Previous beta versions proved that the hybrid PostgreSQL direct import path can reduce unnecessary intermediate file generation and move the heavy loading work to PostgreSQL.

This release makes that path more maintainable and operationally useful by allowing the import process to be split into phases. This helps with debugging, partial execution, future checkpoint support and long-running database imports.

Recommended flow

cnpj-db-loader sanitize C:\ReceitaDB\test\2026-05\extracted --output C:\ReceitaDB\test\2026-05\sanitized --force

cnpj-db-loader postgres generate-script C:\ReceitaDB\test\2026-05\sanitized --output C:\ReceitaDB\test\2026-05\postgres-direct --source-encoding UTF8 --transaction-mode phase --force

psql -d "postgres://postgres:postgres@localhost:5432/cnpj_2_teste" -f "C:\ReceitaDB\test\2026-05\postgres-direct\import-postgres-direct.sql"

Notes

This is a beta release. The modular hybrid import mode is intended for validation with large Receita Federal datasets before becoming part of the stable release channel.

The recommended transaction mode for large imports is:

phase

This mode provides a better balance between safety and recoverability than a single global transaction.

v2.4.0-beta.2

v2.4.0-beta.2 Pre-release
Pre-release

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 25 May 20:41

Robust UTF-8 Sanitization

This beta release improves the sanitization layer used by the CNPJ DB Loader, especially for the hybrid PostgreSQL direct import flow.

The sanitize command now produces cleaner UTF-8 output and removes problematic bytes and control characters that could break PostgreSQL COPY/\copy operations during large Receita Federal dataset imports.

Added

  • Added robust UTF-8 normalization during sanitization.
  • Added removal of invalid bytes from sanitized output.
  • Added removal of problematic control characters.
  • Added preservation of valid line breaks required for tabular file processing.
  • Added configurable source encoding support for sanitization.

Changed

  • The sanitization output is now safer for direct PostgreSQL import.
  • The hybrid PostgreSQL script generation flow now expects sanitized files to be clean UTF-8 by default.
  • Documentation was updated to explain the robust sanitization behavior and the recommended hybrid import flow.

Why this matters

Some Receita Federal files may contain legacy encoding issues, invalid bytes or control characters that are accepted by older tooling but can break PostgreSQL imports when the database expects UTF-8.

This release makes the sanitization step more reliable by preparing files in a safer format before they are used by the PostgreSQL direct import mode.

Recommended flow

cnpj-db-loader sanitize C:\ReceitaDB\test\2026-05\extracted --output C:\ReceitaDB\test\2026-05\sanitized --force

cnpj-db-loader postgres generate-script C:\ReceitaDB\test\2026-05\sanitized --output C:\ReceitaDB\test\2026-05\postgres-direct --source-encoding UTF8 --force

psql -d "postgres://postgres:postgres@localhost:5432/cnpj_2_teste" -f "C:\ReceitaDB\test\2026-05\postgres-direct\import-postgres-direct.sql"

Notes

This is a beta release. The goal is to validate the new sanitization behavior against full Receita Federal datasets and confirm that PostgreSQL direct imports no longer fail due to invalid encoding or problematic control characters.

v2.4.0-beta.1

v2.4.0-beta.1 Pre-release
Pre-release

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 25 May 19:09

Hybrid PostgreSQL Direct Import

This beta release introduces the first version of the hybrid PostgreSQL direct import mode.

The new mode allows the CNPJ DB Loader to handle the safe preparation steps — extraction, validation and sanitization — while PostgreSQL performs the heavier loading and materialization work directly from the sanitized Receita Federal files.

This release is intended for validation and performance testing before the hybrid mode becomes part of the stable release channel.

Added

  • Added a hybrid PostgreSQL direct import workflow.
  • Added support for generating a PostgreSQL import script from sanitized Receita Federal files.
  • Added direct psql-based import support using sanitized files as the source.
  • Added PostgreSQL-side loading into temporary/raw tables.
  • Added PostgreSQL-side staging and materialization flow.
  • Added support for loading lookup/domain tables directly from sanitized files.
  • Added support for materializing final tables through generated SQL.
  • Added support for generating establishment_secondary_cnaes during the PostgreSQL direct import flow.
  • Added configurable source encoding for psql copy operations.

Changed

  • The hybrid flow no longer requires generating large intermediate canonical CSV files before importing into PostgreSQL.
  • The loader can now prepare the files and let PostgreSQL handle the heavy import/materialization steps.
  • Documentation was updated to describe the hybrid PostgreSQL path and its intended workflow.

Recommended flow

cnpj-db-loader federal-revenue download 2026-05 --output C:\ReceitaDB\test

cnpj-db-loader extract C:\ReceitaDB\test\2026-05

cnpj-db-loader validate C:\ReceitaDB\test\2026-05\extracted

cnpj-db-loader sanitize C:\ReceitaDB\test\2026-05\extracted --output C:\ReceitaDB\test\2026-05\sanitized --force

cnpj-db-loader postgres generate-script C:\ReceitaDB\test\2026-05\sanitized --output C:\ReceitaDB\test\2026-05\postgres-direct --source-encoding LATIN1 --force

psql -d "postgres://postgres:postgres@localhost:5432/cnpj" -f "C:\ReceitaDB\test\2026-05\postgres-direct\import-postgres-direct.sql"

Notes

This is a beta release. The hybrid import mode is already usable for validation, but it still needs real-world testing with full Receita Federal datasets, especially around encoding, long-running imports, transaction strategy and PostgreSQL performance tuning.

Known limitation

The current hybrid flow may still depend on the source file encoding used by the sanitized files. Some datasets may require LATIN1 instead of WIN1252 during psql copy operations.

The next beta version should improve the sanitization layer to produce safer sanitized files with:

  • clean UTF-8 output;
  • no invalid bytes;
  • no problematic control characters.

This will make the PostgreSQL direct import flow more predictable and reduce encoding-related failures during large imports.

v2.3.1

Choose a tag to compare

@DanielArndt0 DanielArndt0 released this 23 May 22:43

Fixes

  • Fixed release workflows to sync the package version before generating the dist build.
  • Added CLI version validation before publishing packages, preventing mismatches between the release tag and the generated CLI output.
  • Fixed the CLI version source by removing the hardcoded 2.2.0 value from the application config.