gabarito
A YAML file describes the file your client sends. DuckDB gives you typed tables.
Works with fixed-width files (several record types per file), CSV and Excel, from disk or S3, with nothing imported into a database first. It also writes fixed-width files from a query. Ships with CNAB 240 and CNAB 400 layouts.
The picture as a runnable script, with Postgres in Docker: examples/workflow.
Why
Companies that receive files from clients end up with one hand-written parser per client and a staging database full of untyped tables. The query engine was never the missing piece: DuckDB, Trino and Athena already join a file with a database. What is missing sits before the query:
- DuckDB has no fixed-width reader, and nothing handles files with header, detail and trailer records in one layout.
- A trailer that says "120 records" is usually parsed and never compared with the file.
- A value that fails to convert is logged, or silently becomes garbage.
gabarito is the small layer that covers those three. The layout is data, the SQL is generated, and check tells you whether today's file matches the layout before anything is loaded.
Try it
pip install gabarito-duckdb installs the library and the gabarito command. To run the examples, clone the repo:
git clone https://github.com/francocontigo/gabarito && cd gabarito
pip install .
gabarito check examples/cobranca.yml examples/cobranca.txt
gabarito export examples/cobranca.yml examples/cobranca.txt out/
source: fixed
encoding: latin-1
records:
header:
match: '^0'
length: 50
fields:
data_geracao: {pos: [2, 8], type: date, format: '%d%m%Y'}
carteira: {pos: [10, 41]}
detalhe:
match: '^1'
length: 50
fields:
nome: {pos: [2, 20]}
contrato: {pos: [22, 8]}
valor: {pos: [30, 13], type: decimal, scale: 2}
vencimento: {pos: [43, 8], type: date, format: '%Y%m%d'}
trailer:
match: '^9'
length: 50
fields:
qtd: {pos: [2, 6], type: int}
expect:
- count: detalhe
equals: trailer.qtd
import duckdb, gabarito
con = duckdb.connect()
tables = gabarito.load("examples/cobranca.yml", "examples/cobranca.txt", con)
detalhe = tables["detalhe"]
con.sql("SELECT nome, valor, vencimento FROM detalhe WHERE valor > 1000").show()
Command line
gabarito init file.txt # draft a layout from a sample of the file
gabarito check layout.yml file.txt # does the file match the layout?
gabarito sql layout.yml file.txt # print the generated SQL
gabarito export layout.yml file.txt out/ # one Parquet file per record
gabarito rejects layout.yml file.txt bad.csv # the lines that break the layout, with the reasons
gabarito write layout.yml out.txt --from detalhe="SELECT ..." # tables -> fixed-width file
check exits with 1 and lists what it found:
1 line(s) match no record (lines 5)
detalhe: 1 line(s) with length other than 50 (lines 3)
detalhe.valor: 1 value(s) do not convert to decimal
expect: trailer.qtd says 2, but the file has 3 detalhe record(s)
For CSV and Excel it also reports missing and unexpected columns. An invalid layout exits with 2 and a one-line message, for example field detalhe.valor: unknown key 'typ' (did you mean 'type'?).
init guesses record types from the first character and field boundaries from the sample. It is a starting point: names and types are yours to fill in.
Workflows
Three ways it gets used. The diagrams are generated by docs/make_diagrams.py.
Validate a client file and load it into the database
con.sql("ATTACH 'postgresql://user:pass@host/db' AS pg (TYPE postgres)")
problems = gabarito.check("layout.yml", "cobranca.txt", con)
con.sql(f"COPY ({gabarito.rejects_sql('layout.yml', 'cobranca.txt')}) TO 'rejects.csv'")
detalhe = gabarito.sql("layout.yml", "cobranca.txt")["detalhe"]
con.sql(f"CREATE TABLE pg.public.detalhe AS SELECT * FROM ({detalhe}) WHERE valor IS NOT NULL")
Runnable version, with Postgres in Docker: examples/workflow.
From a landing bucket to the warehouse
S3="CREATE SECRET (TYPE s3, PROVIDER credential_chain)"
gabarito --init "$S3" check cnab240 "s3://landing/*.rem" &&
gabarito --init "$S3" export cnab240 "s3://landing/*.rem" s3://lake/cnab
check exits with 1 when a file breaks the layout, so the export only runs on files that match.
Write the return file from a query
gabarito.write(
"retorno.yml",
{
"header": "SELECT current_date AS data",
"detalhe": "SELECT contrato, status, valor FROM pg.public.aceitos ORDER BY contrato",
"trailer": "SELECT count(*) AS qtd, sum(valor) AS total FROM pg.public.aceitos",
},
"retorno.txt",
con,
)
assert gabarito.check("retorno.yml", "retorno.txt") == []
Layout format
| Key | Meaning |
|---|---|
source |
fixed (default), csv or xlsx |
encoding |
Default utf-8. Legacy files are often latin-1. auto picks the first of utf-8, latin-1 (ISO-8859-1) and CP1252 that decodes the whole file, at the cost of one extra read per attempt |
records.<name>.match |
Regex that identifies the record's lines. Required for fixed |
records.<name>.length |
Expected line length. Optional, used by check |
fields.<name>.pos |
[start, length], start counted from 1. fixed only |
fields.<name>.column |
Column name in the file. csv and xlsx only |
fields.<name>.type |
str (default), int, decimal, date |
fields.<name>.value |
Fixed literal, used by write when no column feeds the field |
expect |
count: <record or '*'> or sum: <record>.<field> must equal equals: <record>.<field> |
delimiter, skip_rows |
csv only. Default delimiter ; |
decimal_comma |
1.234,56 instead of 1234.56. Default: on for csv, off for xlsx |
sheet |
Worksheet name. xlsx only |
How types behave:
- Every field is trimmed. An empty field becomes
NULL. strnever becomes a number, so leading zeros survive.decimalin afixedfile is an implied decimal:0000000123456withscale: 2is1234.56.datetakes astrptimeformat. An all-zero date becomesNULL.- A value that does not convert becomes
NULLin the table and shows up incheck.
Each table has a _file column with the source file (except xlsx).
Rejected lines
check counts problems; rejects gives you the lines, so a pipeline can load the good ones and send the bad ones back.
con.sql(gabarito.rejects_sql("layout.yml", "file.txt")) # _file, _line, reasons, line
_line | reasons | line
3 | detalhe: length 47, expected 50 | 1CURTA ...
4 | detalhe.valor: not a valid decimal; detalhe.vencimento: not a valid date | 1RUIM ...
5 | matches no record | 7 unknown record type
Writing files
The same layout that reads a file writes one. Each record is fed by a query or a table; columns are matched to fields by name.
gabarito.write(
"retorno.yml",
{
"header": "SELECT current_date AS data",
"detalhe": "SELECT contrato, status, valor FROM aceitos ORDER BY contrato",
"trailer": "SELECT count(*) AS qtd, sum(valor) AS total FROM aceitos",
},
"retorno.txt",
con,
)
- Text is padded with spaces, and a line break inside it becomes a space; numbers are zero-padded; decimals lose the point (
scale); dates use the field'sformat;NULLbecomes blanks or zeros. - A value that does not fit its field (text too long, number too large or negative) raises an error instead of being cut. To cut on purpose, do it in the query:
left(nome, 40) AS nome. - A field with no column takes its
value(record type codes, for example), or blanks. - Records come out in layout order, each in the order of its query, streamed to the file: 30 million lines (2 GB) took 26 s with a peak of 0.7 GB of memory, and the same under
memory_limit = '2GB'. - To interleave records (CNAB: each segment P followed by its Q), add an
_ordercolumn to those queries. Interleaving sorts those lines, spilling to disk when memory is short: 15 million P/Q pairs (30 million lines) took 22 s with the default settings and 31 s undermemory_limit = '1GB'. - A layout that was only written to read may leave positions out. To write a file that passes its own
check, every position that matters needs a field, including the record-type character:tipo: {pos: [1, 1], value: '1'}. - Lines end in CRLF by default (
newline=changes it). Output is a local file.
CNAB layouts
Ready-made layouts for Brazilian bank files. Use the name in place of a YAML path:
gabarito check cnab240 retorno.ret
gabarito export cnab400_itau_retorno retorno.ret out/
| Layout | Covers | Source | Checked against |
|---|---|---|---|
cnab240 |
Collection: segments P, Q, R (remessa), T, U (retorno) | FEBRABAN standard v10.1 | Sample remessas from eight banks; Sicredi's sample retorno |
cnab240_pagamentos |
Payments: segments A, B, J | FEBRABAN standard v10.1 | Synthetic file only |
cnab240_santander |
Santander collection, remessa and retorno | Santander H7815 v3.8 (Nov 2021) | Santander's sample remessa and retorno |
cnab400_bradesco_remessa, cnab400_bradesco_retorno |
Bradesco collection | Bradesco manual, March 2023 | Bradesco's sample remessa and retorno |
cnab400_itau_remessa, cnab400_itau_retorno |
Itaú collection | Itaú manual, January 2017 | Itaú's sample remessa and retorno |
The samples are public test fixtures of the brcobranca project, not production files. Before relying on a layout, run check on a real file from your bank and compare with the bank's current manual:
- Banks deviate from FEBRABAN. Santander shifts most of segment T, which is why it has its own layout.
- The Santander layout comes from the 2021 manual; the current edition could not be downloaded.
- CNAB 400 has no standard across banks, and remessa and retorno are separate layouts because the detail line carries no direction flag.
- Optional record types (CNAB 400 types 2 to 7, CNAB 240 segments not listed above) are not transcribed. They show up in
checkas lines that match no record.
To adapt one, copy the file from src/gabarito/layouts/ and edit it. Every layout carries the value literals needed to write files as well as read them.
S3
s3:// paths work for reading, with globs, and for writing Parquet. Credentials live on the DuckDB connection:
con.sql("CREATE SECRET (TYPE s3, PROVIDER credential_chain)")
gabarito.load("layout.yml", "s3://bucket/remessas/*.txt", con)
On the command line, --init runs SQL on the connection before the command:
gabarito --init "CREATE SECRET (TYPE s3, PROVIDER credential_chain)" \
export layout.yml "s3://bucket/remessas/*.txt" s3://bucket/out
Tested against a local S3 (S3Mock) with a fixed key and custom endpoint. Not tested against AWS.
With dbt
On dbt-duckdb there are two ways.
The generated SQL is a model as it is: gabarito sql layout.yml cobranca.txt prints one SELECT per record, and each one can be saved as a .sql file in models/, without the final ;.
Or declare the file as a source and let the plugin read it. In profiles.yml, inside the duckdb output:
plugins:
- module: gabarito.dbt
alias: gabarito
In a sources.yml:
sources:
- name: client
meta: {plugin: gabarito, layout: layout.yml, path: cobranca.txt, check: true}
tables:
- name: detalhe # a record of the layout
- name: fim
identifier: trailer # when the table and the record have different names
SELECT contrato, valor FROM {{ source('client', 'detalhe') }} WHERE valor > 100
With check: true, a file that breaks the layout fails dbt run before anything is loaded; the file is checked once per run, whatever the number of tables. Each record becomes a table. Paths are relative to the directory dbt runs in. Other dbt adapters are not supported: the SQL reads the file with DuckDB's read_csv.
Measured in a Linux container with 16 threads and DuckDB 2.0: a CNAB 240 file of 7.3 GB and 30 million lines, loaded as two source tables, took 46 s with a peak of 2.0 GB of memory. With settings: {memory_limit: 2GB, threads: 4} in the profile it took 87 s and 1.3 GB.
Other databases
DuckDB only executes. Two ways out:
Parquet. gabarito export writes Parquet, which Redshift, Snowflake, BigQuery, Athena and Spark read directly.
Straight through DuckDB. It attaches Postgres and MySQL and writes to them (Postgres is exercised by examples/workflow; MySQL 8.4 was tested by hand: load, read back, and write from a mysql_query(...)):
con.sql("ATTACH 'postgresql://user:pass@host/db' AS pg (TYPE postgres)")
q = gabarito.sql("layout.yml", "file.txt")["detalhe"]
con.sql(f"CREATE TABLE pg.public.detalhe AS {q}")
Large files and memory
No Python code touches the rows. The library builds SQL; DuckDB reads the file in streaming, in parallel, and spills to disk when memory runs out. So there is no chunking code here, and the memory ceiling is a connection setting:
gabarito --init "SET memory_limit='500MB'; SET threads=2" check layout.yml file.txt
memory_limit does not cover read buffers, which grow with the thread count. For a low ceiling, lower threads too.
To consume rows in Python in batches instead of all at once:
cur = con.execute(gabarito.sql("layout.yml", "file.txt")["detalhe"])
while rows := cur.fetchmany(50_000):
...
Measured on synthetic CNAB 240 files, 16-thread Windows machine, DuckDB 1.5.6:
| File | Export one segment to Parquet | check, whole layout (216 fields) |
|---|---|---|
| 2 GB, 8.6 million lines | 6 s, 0.8 GB peak | 41 s, 0.9 GB peak |
2 GB, with memory_limit='500MB' and 2 threads |
28 s, 0.3 GB peak | 123 s, 0.2 GB peak |
| 7.3 GB, 30 million lines | 20 s, 1.3 GB peak | 146 s, 1.0 GB peak |
Limits
- Single machine. For volumes that need a cluster, export Parquet and use another engine.
initis a heuristic.encoding: autochooses one encoding per call: a glob with files in different encodings is an error.CP1252needs DuckDB'sencodingsextension, downloaded on first use.- Line numbers in
checkfollow DuckDB's read order. - Tested with DuckDB 1.5 and 2.0, on Windows and Linux.
License
MIT
Metadata
Release files for gabarito-duckdb 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gabarito_duckdb-0.3.0.tar.gz | 28.7 kB | With provenance | Details for gabarito_duckdb-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gabarito_duckdb-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for gabarito_duckdb-0.3.0-py3-none-any.whl |
Total release size: 65.3 kB
Release files / gabarito_duckdb-0.3.0.tar.gz
| Download URL | gabarito_duckdb-0.3.0.tar.gz |
|---|---|
| Size | 28.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0af91950ec22f977e3246d1c718eaa19456e512a0f1ece8f1713540c33664b39
|
|
BLAKE2b-256 checksum How to use checksums |
52dad338b185845fa7521bd1cd2e8ca149c286a436f44e79cbe5c6f3ca1e9254
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.
Transparency logRelease files / gabarito_duckdb-0.3.0-py3-none-any.whl
| Download URL | gabarito_duckdb-0.3.0-py3-none-any.whl |
|---|---|
| Size | 36.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e7115f7b95e25aebb9a4b99fe730f860e50bda77e1289c4e34d357db9ee7b0dd
|
|
BLAKE2b-256 checksum How to use checksums |
964b76b8513beb4c08726a9d94287f58589bc881f8f2ecfd4ccce7bbc0f06bb0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.
Transparency logSecurity for gabarito-duckdb 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for gabarito_duckdb-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.