Metadata-Version: 2.5
Name: paradoxdb
Version: 0.1.0
Summary: Pure-Python reader and writer for Paradox tables (.DB / .MB / .PX) with explicit per-cell state
Project-URL: Homepage, https://github.com/arielgiamportone/paradox-db-py
Project-URL: Repository, https://github.com/arielgiamportone/paradox-db-py
Project-URL: Issues, https://github.com/arielgiamportone/paradox-db-py/issues
Project-URL: Changelog, https://github.com/arielgiamportone/paradox-db-py/blob/main/CHANGELOG.md
Author: arielgiamportone
License-Expression: MIT
License-File: LICENSE
Keywords: b-tree,bcd,bde,borland,database,delphi,file-format,legacy,memo,migration,paradox
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: dev
Requires-Dist: hypothesis>=6; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# paradox-db-py

[![CI](https://github.com/arielgiamportone/paradox-db-py/actions/workflows/ci.yml/badge.svg)](https://github.com/arielgiamportone/paradox-db-py/actions/workflows/ci.yml)
![Python 3.11 | 3.12](https://img.shields.io/badge/python-3.11%20%7C%203.12-blue)
![License MIT](https://img.shields.io/badge/license-MIT-green)

**Pure-Python reader and writer for Paradox tables** (`.DB` data, `.MB` memos
and BLOBs, `.PX` primary index), versions 3.0 to 7. No native code, no copyleft
dependencies, no silent conversions: every cell comes back as `OK`, `NULL` or
`INVALID` together with its raw bytes.

*Versión en español: [README.es.md](https://github.com/arielgiamportone/paradox-db-py/blob/main/README.es.md).*

> Patterns developed during my work at Intervalor Data and published with permission. Independent clean-room implementation with synthetic data; it contains no code or data from the company or its clients.

---

## 1. The problem

A fixed-asset management system written in Delphi on top of the Borland
Database Engine kept decades of history in Paradox tables. Modernising it meant
two things at once:

1. **Extract** every record without loss. Not "most records": the legacy
   engine left records in the data blocks that the header never counted, and
   whole columns of monetary values stored as BCD that no longer decoded.
2. **Give tables back** to the legacy application during a long transition,
   so the old and the new system could coexist for months.

The Python ecosystem offered only bindings over a C library (GPL) that is
read-only in practice, forces one global text encoding, skips the records the
header does not declare and corrupts its memory heap after a few dozen write
operations. For an on-premise product none of that was acceptable.

## 2. Constraints

| Constraint | Consequence in the design |
|---|---|
| Distributed on-premise inside a commercial product | Pure Python, MIT licence, zero runtime dependencies |
| Real tables hold personal and financial data of third parties | Every fixture is generated by `paradoxdb.synthetic`; the repo contains no `.DB` file |
| The cipher of encrypted tables is only available in GPL code | Decryption is delegated to an optional external `Decryptor`; this library only decodes plain bytes |
| The legacy engine must still open what we write | The writer copies an existing header (template) and only rewrites counters; new files are produced, nothing is modified in place |
| Mixed code pages in one dataset (CP437 core, CP1252 later tables) | Code page per table, read from the header, never global |
| Monetary amounts and 32-digit BCD | `Decimal` everywhere; `float` only as the on-disk representation |

## 3. Architecture

```
paradoxdb/
├── fields.py     FieldType, FieldDef, code pages, physical sizes
├── numeric.py    order-preserving codecs: Paradox int, Paradox double, BCD
├── values.py     CellValue(state, value, raw_bytes, reason); decode_value; encode_*
├── header.py     TableHeader, parse_header, patch_counters (0x06, 0x0A-0x10, 0x49)
├── blocks.py     block-chain walker (every record, anomalies) and block packer
├── memo.py       MemoPointer, MemoFile (types 2 and 3), MemoWriter (type 2)
├── table.py      open_table, ParadoxTable, Record, Decryptor protocol
├── writer.py     write_table on a template, WriteRecord, legacy_sort_key
├── index.py      DataBlock, read_data_blocks, build_index, verify_index
├── profile.py    profile_table, export_csv, export_json
├── cli.py        paradoxdb profile | export | verify-index
└── synthetic.py  table factory used by tests and examples
```

Reading pipeline:

```
.DB bytes ──► parse_header ──► iter_blocks ──► decode_value per field ──► Record
                 │                                   ▲
                 └── code page, descriptors          └── MemoFile (.MB sibling, any case)
```

Writing pipeline:

```
template .DB header ──copy──► patch counters ──► pack_blocks(records) ──► new .DB
template .MB first block ──► MemoWriter (one single-block entry per memo) ──► new .MB
template .PX header ──► build_index(read_data_blocks(new .DB)) ──► new .PX
```

### Quick start

```python
from paradoxdb import open_table

table = open_table("ASSETS.DB")  # finds assets.mb / ASSETS.MB too
print(table.header.version_label, table.header.codec)

for record in table.records():  # every record in every block
    amount = record["Amount"]  # case-insensitive field lookup
    if amount.is_ok:
        total = amount.value  # Decimal, date, int, bool, str, bytes
    else:
        print(amount.state, amount.reason, amount.raw_bytes.hex())

print(table.block_record_count(), table.declared_record_count, table.header_mismatch)
```

```python
from paradoxdb import WriteRecord, write_table, verify_index, read_data_blocks

records = [
    WriteRecord(r.raw_bytes, {3: r["Note"].value.encode(table.codec)}) for r in table.records()
]
result = write_table("ASSETS.DB", "out/ASSETS.DB", records, sort=False)
assert verify_index(result.px_path, read_data_blocks(result.db_path)) == []
```

```bash
paradoxdb profile ./tables --output profile.json   # aggregates, SHA-256, mismatches
paradoxdb export ./tables/ASSETS.DB --format csv   # value, state and reason per cell
paradoxdb verify-index ./tables/ASSETS.DB          # exit 1 when the .PX is inconsistent
```

## 4. Decisions and the alternatives they replaced

| Decision | Rejected alternative | Why |
|---|---|---|
| Own reader in pure Python | Bindings over the C library | GPL licence, one global encoding, skips undeclared records, no 64-bit guarantee on Linux |
| Decryption delegated to an optional component | Re-implement the cipher | The only public implementation is GPL; encrypted tables are a small minority |
| Explicit state per cell plus raw bytes | `None` / `0` when in doubt | The earlier approach turned garbage currency values and sentinel dates into `None`: silent loss at scale |
| `Decimal` for doubles and BCD | `float` | Accounting amounts and 32-digit BCD; arithmetic parity with the legacy engine is the consumer's job |
| Code page per table | Global `latin1` or `cp1252` | `latin1` accepts every byte but misreads `ñ` / `º` from CP437 tables; datasets mix code pages |
| Header copied from a template | Build headers from scratch | Keeps version, descriptors, key and code page, including in empty tables, without modelling obscure header fields |
| Always new files | Modify in place | The C library corrupted memory after ~50 in-place writes |
| One single-block entry per memo | Sub-allocated blocks | Correctness first; the size cost is measured below and planned for v2 |
| Source order by default, legacy order on request | Always re-sort | The legacy engine accepts the original order; the reproduced collation matched the real one in most but not all tables |
| Whole file in memory | Block-by-block streaming | Tables of tens of MB; revisit if hundreds appear |

Decisions that the specification left open (error-message language, how the
`.PX` entry count is defined, how the leak guard matches words, and so on) are
listed with their rationale in [docs/DECISIONES.md](https://github.com/arielgiamportone/paradox-db-py/blob/main/docs/DECISIONES.md).

## 5. What was measured and how to reproduce it

Everything below runs on synthetic data produced by the repository itself.

```bash
pip install -e ".[dev]"
pytest                          # 100+ tests, including Hypothesis round-trip properties
python examples/benchmark.py    # timings and .MB growth on a 50 000-row table
```

Results on a laptop-class container (Python 3.12):

| Measurement | Value |
|---|---|
| Open and decode 50 000 mixed-type records | 1.3 s |
| Write `.DB` + `.PX` for those records on a template | 0.09 s |
| Verify the resulting two-level `.PX` | < 0.01 s |
| `.MB` written for 5 000 memos of ~150 bytes each | 20 MiB for 0.7 MiB of payload (×27) |

The test-suite covers every case of the original specification: headers with
and without the 4.0+ extension, CP437 and CP1252 text, every field type with
sign, null versus zero, unreadable BCD, records beyond the declared count,
memos in the three storage forms, missing `.MB`, encrypted tables with and
without a decryptor, incoherent headers, round-trips with memos and index,
multi-level indexes, legacy collation (`NA, nz, Ñu, Oa, ob`), duplicate keys,
empty tables, autoincrement, secondary indexes left untouched, the index
verifier and the profile / CLI output.

In the original project the same design was validated against about 120 real
tables (roughly 225 000 rows) with zero byte or value differences versus the
C library, and the verifier accepted 106 of 108 original indexes (the other two
had counts corrupted by interrupted writes). Those tables cannot be published;
the figures are given only as context.

## 6. Known limits

- **`.MB` growth.** Every memo gets at least one 4 KiB block. Sub-allocated
  (type 3) blocks are read but never written. Planned for v2.
- **Not yet opened in a real BDE.** Round-trips are validated with this
  library's reader; opening the written files in the legacy engine is pending.
- **Secondary indexes** (`.Xnn`, `.Ynn`, `.XGn`, `.YGn`) are detected and
  reported, never regenerated.
- **Encrypted tables are never written**, and decryption requires an external
  component.
- Index entry counts are limited to 32 767 per entry, BCD to 32 digits; text
  that does not fit a field is an error, not a truncation.
- Whole files are loaded in memory.

## 7. How it was built

Three-phase clean-room process. Phase 1 produced a specification of the format,
behaviour and invariants from the original (private) code, without copying
code, identifiers or data. Phase 2, this repository, was implemented in a
separate session with access to that specification and to public documentation
only, using an AI coding assistant as pair programmer; every decision not fixed
by the specification is documented. Phase 3 is an independent review comparing
this repository against the original before publication. The CI runs a leak
guard (`tests/test_no_leaks.py`) over the tree and the git history, plus
`gitleaks`.

## 8. Attribution and licence

Patterns developed during my work at Intervalor Data and published with permission. Independent clean-room implementation with synthetic data; it contains no code or data from the company or its clients.

MIT licence. See [LICENSE](https://github.com/arielgiamportone/paradox-db-py/blob/main/LICENSE), [CHANGELOG.md](https://github.com/arielgiamportone/paradox-db-py/blob/main/CHANGELOG.md) and
[CONTRIBUTING.md](https://github.com/arielgiamportone/paradox-db-py/blob/main/CONTRIBUTING.md).
