Metadata-Version: 2.4
Name: qvd-parser
Version: 0.3.1
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Dist: pydantic>=2.0 ; extra == 'dev'
Requires-Dist: pytest ; extra == 'dev'
Requires-Dist: pytest-benchmark>=4.0 ; extra == 'dev'
Requires-Dist: pydantic>=2.0 ; extra == 'pydantic'
Provides-Extra: dev
Provides-Extra: pydantic
License-File: LICENSE
Summary: Fast QVD file parser — Python bindings for qvd-parser (Rust)
Keywords: qvd,qlik,qlikview,qliksense,parser
Home-Page: https://github.com/nicolasstefaniuk/qvd-parser
Author-email: Nicolas Stefaniuk <287317062+nicolasstefaniuk@users.noreply.github.com>
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/nicolasstefaniuk/qvd-parser
Project-URL: Issues, https://github.com/nicolasstefaniuk/qvd-parser/issues
Project-URL: Repository, https://github.com/nicolasstefaniuk/qvd-parser

# qvd-parser

[![Crates.io](https://img.shields.io/crates/v/qvd-parser.svg)](https://crates.io/crates/qvd-parser)
[![PyPI](https://img.shields.io/pypi/v/qvd-parser.svg)](https://pypi.org/project/qvd-parser/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

Fast, correct QVD (QlikView Data) file parser written in Rust.

Reads the binary format used by QlikView and Qlik Sense to store compressed
data tables. Exposes a Rust API, a Python API (via PyO3), and a CLI. Export
targets: JSON, CSV, Parquet.

> **Note:** QVD is a proprietary file format associated with QlikView and
> Qlik Sense. This project is not affiliated with or endorsed by Qlik.
> See [Legal & Interoperability](#legal--interoperability) for details.

## Workspace structure

```
qvd-parser/
├── core/               # Core parsing library — QvdFile, QvdValue, RowIter
├── convert/            # Export backends: Parquet, JSON, CSV
├── cli/                # Command-line interface (qvd-parser-cli binary)
└── bindings-python/    # Python bindings via PyO3 + maturin
```

## Prerequisites

- Rust toolchain (1.75+): https://rustup.rs
- For Python bindings: `pip install maturin`

## Build

```bash
# Build all crates
cargo build --workspace

# Build release (recommended for performance measurement)
cargo build --release --workspace

# Run all Rust unit tests
cargo test --workspace

# Run integration tests (requires QVD fixtures — see below)
cargo test --workspace --features integration-tests

# Build the Python extension in-place (for development)
maturin develop

# Run Python binding tests
pytest bindings-python/tests/
```

## CLI usage

```bash
# Schema inspection
cargo run -p qvd-parser-cli -- schema --input data.qvd

# Print the first 10 data rows
cargo run -p qvd-parser-cli -- print-row --input data.qvd

# Export to JSON
cargo run -p qvd-parser-cli -- export --input data.qvd --format json --output out.json

# Export to CSV (semicolon delimiter)
cargo run -p qvd-parser-cli -- export --input data.qvd --format csv --output out.csv --csv-delimiter ";"

# Export to Parquet (verbose timing breakdown)
cargo run --release -p qvd-parser-cli -- export --input data.qvd --format parquet --output out.parquet --verbose
```

### Filtering rows

A filter narrows the rows a command works on. It applies to **exactly one
field** and uses **exactly one of three kinds** — mixing them is an error.
Available on `print-row` (rows are printed) and on `export` (only matching rows
are written to the output file).

| Flag | Description |
|---|---|
| `--filter-field NAME` | Field the filter applies to. Required by every other `--filter-*` flag. |
| `--filter-in VALUE` | **Kind 1** — keep rows whose value equals `VALUE`. Repeatable; a row matches if any value matches. One value per occurrence, so a value may contain commas. A value that reads as a number also matches numerically (`--filter-in 100` matches a field displaying `100.0`). |
| `--filter-like PATTERN` | **Kind 2** — keep rows whose value matches `PATTERN`. Repeatable. `*` matches any run of characters (including none), `?` exactly one. Case-sensitive, applied to the value as displayed. |
| `--filter-ge VALUE` | **Kind 3** — inclusive lower bound (`>=`). |
| `--filter-gt VALUE` | **Kind 3** — exclusive lower bound (`>`). |
| `--filter-le VALUE` | **Kind 3** — inclusive upper bound (`<=`). |
| `--filter-lt VALUE` | **Kind 3** — exclusive upper bound (`<`). |
| `--filter-date-format FORMAT` | Read the bounds as dates in this format, forcing date interpretation of the field. Same syntax as `--date-format`. |
| `--limit N` | Maximum number of matching rows. Default 10 for `print-row`, unlimited for `export`. |
| `--all` | Every matching row, ignoring `--limit`. |

**NULL never matches** — on any of the three kinds, including `--filter-like "*"`.

```bash
# Kind 1 — a list of values
cargo run -p qvd-parser-cli -- print-row --input data.qvd \
    --filter-field Country --filter-in FR --filter-in DE --filter-in IT

# Kind 2 — wildcards
cargo run -p qvd-parser-cli -- print-row --input data.qvd \
    --filter-field Product --filter-like "ABC*" --filter-like "X?Z"

# Kind 3 — a numeric range, and JSON output
cargo run -p qvd-parser-cli -- print-row --input data.qvd --format json \
    --filter-field Amount --filter-ge 100 --filter-lt 500

# Export only the matching rows (no --limit ⇒ all of them)
cargo run -p qvd-parser-cli -- export --input data.qvd --format csv --output fr.csv \
    --filter-field Country --filter-in FR

# Print every match instead of the first 10
cargo run -p qvd-parser-cli -- print-row --input data.qvd --all \
    --filter-field Country --filter-in FR
```

#### Date bounds

For `--filter-ge` / `-gt` / `-le` / `-lt`, a field is treated as a **date** when
it carries a `$date`/`$timestamp` tag *or* a `DATE`/`TIMESTAMP`/`INTERVAL`
`NumberFormat` Type. Bounds are then read as `DD/MM/YYYY HH24:MM:SS`, with
date-only values also accepted (interpreted as midnight). A raw Qlik day-offset
also works, so `--filter-ge 45658` and `--filter-ge 01/01/2025` are equivalent.

```bash
# Implicit — Date is $date-tagged, no format needed
cargo run -p qvd-parser-cli -- print-row --input data.qvd \
    --filter-field Date --filter-ge 01/01/2024 --filter-le 31/12/2024

# Timestamps compare with their time of day
cargo run -p qvd-parser-cli -- print-row --input data.qvd \
    --filter-field EventTs --filter-ge "25/12/2024 06:00:00"

# Explicit — a date stored as text in a different layout
cargo run -p qvd-parser-cli -- print-row --input data.qvd \
    --filter-field TxtDate --filter-ge 2024-01-01 --filter-date-format YYYY-MM-DD
```

A bound the field's scale cannot read (`--filter-ge abc` on a number, an ISO
date against the default `DD/MM/YYYY`) is an error naming the formats tried. A
*cell* that cannot be read is simply a non-match, never an error.

> **Performance.** Filtering scans rows one by one — there is no index. It is
> meant for inspecting a file and extracting a subset from it, not for querying
> very large datasets.


### Parquet export options

| Flag | Default | Description |
|---|---|---|
| `--cast FIELD=TYPE` | — | Force a column to a specific Arrow type. Repeat for multiple fields. Valid types: `INT32`, `INT64`, `FLOAT32`, `FLOAT64`, `STRING`, `DATE32`, `TIMESTAMP_MS`, `BOOLEAN`. Takes priority over `--schema-overrides` on conflict. |
| `--schema-overrides FILE` | — | Path to a JSON file containing per-field type overrides. Same `{"FieldName": "TYPE"}` format as `--cast` but file-based. Inline `--cast` values take priority on conflict. |
| `--fallback-type TYPE` | `STRING` | Type used when inference is inconclusive — i.e. a column's symbol table is all-null/empty and `NumberFormat` carries no recognised hint either. Same valid types as `--cast`. Never overrides a genuine text result from the symbol scan. |
| `--date-format FIELD=FORMAT` | — | Date format used to parse a **text** field cast to `DATE32`/`TIMESTAMP_MS`. Repeat for multiple fields. Accepts Qlik-style tokens (`DD`, `MM`, `YYYY`, `HH24`, `MI`, `SS`, …) or strftime syntax when the pattern contains `%`. Several patterns may be separated by `\|` and are tried in order. |
| `--default-date-format FORMAT` | `DD/MM/YYYY HH24:MM:SS` | Format applied to text fields with no `--date-format` entry. Date-only values also parse (the time part is optional). |
| `--no-date-tag-inference` | off | Disable date inference from field tags — a `$timestamp`/`$date`-tagged field with a date-like `NumberFormat` Type exports as `INT64` day-offsets instead of a date column. |
| `--row-group-size N` | 100000 | Rows per Parquet row group |
| `--strict-first` | off | Fail immediately on the first cast error instead of writing null. Mutually exclusive with `--strict-all`. |
| `--strict-all` | off | Run the full export collecting every cast error, then fail with the complete list if any occurred. The output file is still fully written (failed values as null) even though the command exits with an error. Mutually exclusive with `--strict-first`. |
| `--encoding auto\|plain\|dictionary` | `auto` | Arrow array encoding strategy. **CLI-only, experimental** — not exposed in Python bindings (see performance notes below). |
| `--no-statistics` | off | Disable column min/max statistics (~20% faster export, less efficient predicate pushdown for consumers). **CLI-only, experimental** — not exposed in Python bindings. |
| `--max-file-size SIZE` (alias `--max_file_size`) | — | Split the output into several files of at most `SIZE` each. Units: `B`, `KB`, `MB`, `GB` (powers of 1000), `KiB`, `MiB`, `GiB` (powers of 1024); a bare number is bytes. See [Splitting the output](#splitting-the-parquet-output-into-size-limited-files). |

#### Splitting the Parquet output into size-limited files

Useful when an upload path caps file size (Snowsight stage upload: 250 MB).
Snowflake loads all the parts with one `COPY INTO ... PATTERN = '.*\.parquet'`.

- **Naming.** If `--output` contains `<partid>`, it is a template: every
  `<partid>` becomes the part number (`0001`, `0002`, ...). Otherwise
  `_part<partid>` is inserted before the extension: `data.parquet` gives
  `data_part0001.parquet`, `data_part0002.parquet`, ... A run that fits in one
  file still produces `data_part0001.parquet`.
- **`<partid>` without `--max-file-size`** is not taken as a request to split.
  The path is used literally and a warning is printed. On Windows the export
  then fails (`<` and `>` are not allowed in file names); on Linux/macOS a
  file named `..._<partid>.parquet` is created.
- **How the cut is made.** Files are cut between row groups, and in split mode
  each batch is its own row group of exactly `--row-group-size` rows. The
  writer predicts the next part size (data so far + largest row group seen +
  footer, calibrated on the first row group) and checks the real size of every
  closed part. If a part still ends up over the limit (typically one row group
  bigger than the limit), the export fails rather than leave an oversized
  file: lower `--row-group-size`.
- **Leave some margin** (e.g. `240MB` for a 250 MB limit) and avoid tiny row
  groups: each one adds per-column metadata to the footer.
- The written files are listed on stderr: `wrote <path> (<bytes> bytes, <rows> rows)`.

By default (no `--strict-first`/`--strict-all`), cast failures are written
as `null` and reported as warnings on stderr after the export completes —
nothing is silently lost without a trace:

```
warning: 3 value(s) failed to cast and were written as null:
  field 'Amount' row 42: cannot cast Text to FLOAT64: cannot parse 'N/A' as FLOAT64: invalid float literal
  field 'Amount' row 109: cannot cast Text to FLOAT64: cannot parse 'N/A' as FLOAT64: invalid float literal
  field 'Date' row 7: cannot cast Text to DATE32: cannot convert text 'unknown' to DATE32 — not a numeric day-offset and does not match date format(s) [%d/%m/%Y %H:%M:%S]
```

```bash
# Force specific column types
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --cast DateField=DATE32 --cast Amount=FLOAT64

# Use a JSON override file
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --schema-overrides overrides.json

# Both combined — inline --cast takes priority on conflict
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --schema-overrides overrides.json --cast DateField=TIMESTAMP_MS

# Fail with a complete error report if any value fails to cast
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --strict-all

# All-null/empty columns default to STRING; force INT64 instead
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --fallback-type INT64

# Text field holding string dates ($ascii/$text), forced to a timestamp column
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --cast First_Date=TIMESTAMP_MS \
  --date-format "First_Date=DD/MM/YYYY HH24:MI:SS"

# Same column mixing DD/MM and MM/DD values — patterns are tried in order
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --cast First_Date=TIMESTAMP_MS \
  --date-format "First_Date=DD/MM/YYYY HH24:MI:SS|MM/DD/YYYY HH24:MI:SS"

# Keep $timestamp-tagged DATE fields as raw integer day-offsets
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --no-date-tag-inference

# Keep the display string a date cast would discard, as First_Date_str,
# plus the raw serial as First_Date_num. See "Dual fields and companion
# columns" below for why this is pinned rather than detected.
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --cast First_Date=DATE32 \
  --dual-companions explicit --dual-strategy-field First_Date

# Split into files of at most 240 MB: out_part0001.parquet, out_part0002.parquet, ...
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output out.parquet \
  --max-file-size 240MB

# Same, with a name template: sales_0001_2026.parquet, sales_0002_2026.parquet, ...
cargo run --release -p qvd-parser-cli -- export \
  --input data.qvd --format parquet --output "sales_<partid>_2026.parquet" \
  --max-file-size 240MB
```

### Verbose timing output

`--verbose` shows a per-phase breakdown of both parsing and export:

```
[qvd] export: data.qvd
  load header+symbols+rows        124 ms  [140 fields  119820 rows  126 B/rec]
    header                          1 ms
    symbols                        23 ms
    rows                           98 ms
  export parquet                  555 ms  [out.parquet]
    type inference                  0 ms
    index transpose                43 ms
    cast to arrow                 166 ms
    parquet encode                296 ms
    parquet close                  49 ms
```

### Type inference

For each column without an explicit `--cast`/`schema_overrides` entry, the
target Arrow type is resolved in this order:

1. **Date tag inference** — a field carrying a `$timestamp`/`$date` tag *and*
   a date-like `NumberFormat` Type (`DATE` → `DATE32`, `TIMESTAMP`/`INTERVAL`
   → `TIMESTAMP_MS`). Both signals must agree: Qlik only emits these tags for
   genuine date fields, and the symbol scan below cannot see the distinction —
   a date column stored as day offsets is indistinguishable from a plain
   integer column. Values that will not convert become `null` rather than a
   wrong number, so this cannot silently corrupt data. Disable with
   `--no-date-tag-inference` / `date_tag_inference=False`.
2. **Symbol scan** — the full symbol table is scanned; the dominant
   non-null variant wins (`Int64`/`Float64` only if zero text symbols are
   present — any text presence forces `STRING`, since a numeric type would
   silently null out non-numeric values). `Int64` is never chosen when a
   double symbol has a fractional part (or does not fit in i64): such a
   column is `Float64`, so `1234.5` is not truncated to `1234`.
3. **`NumberFormat.type_name` hint** — used only when the symbol scan is
   inconclusive (column is all-null or empty). `NumberFormat` **on its own** is
   a Qlik *display format* declaration, not a data-type guarantee — a pure-text
   field can legally carry `<Type>REAL</Type>` — so it is never trusted
   over actual stored data.
4. **`--fallback-type`** — last resort, used only when both the symbol scan
   and the `NumberFormat` hint are inconclusive. Defaults to `STRING`.

Cast failures (e.g. a `--cast Field=INT64` override on a column containing
non-numeric text) do not abort the export by default — see `--strict-first`
/ `--strict-all` above to change that, and the warning output shown there
for how failures are reported.

### Dates stored as text

A QVD field tagged `$ascii`/`$text` stores string-only symbols with no numeric
side, so a forced date cast has no day-offset to read. Such values are resolved
in two steps:

1. **Numeric day-offset** — if the text is itself a number (`"44690"`), it is
   interpreted exactly like a numeric symbol: days since the Qlik epoch
   (1899-12-30). This makes a forced date cast behave identically on `$text`
   and `$numeric` fields.
2. **Date format** — otherwise the field's `--date-format` pattern is applied,
   falling back to `--default-date-format` (`DD/MM/YYYY HH24:MM:SS`). A
   datetime pattern also accepts date-only input, so `24/06/2020` parses under
   the default.

If neither applies, the value is a cast failure governed by the usual
`--strict-first` / `--strict-all` rules (by default: `null` plus a warning).
Note that the default `DD/MM/YYYY` order deliberately rejects `12/23/2021`
rather than guessing — supply two `|`-separated patterns for a column that
mixes both orders.

### Dual fields and companion columns

Most QVD values are *duals*: a number **and** a display string, stored together.
A date cast reads the number and discards the string; a string cast keeps the
string and discards the number. Either way one side is lost, and sometimes the
lost side is the one that mattered:

| display string | serial | meaning |
|----------------|--------|---------|
| `04/07/2024`   | 45389  | 2024-04-07 |
| `04/07/2024`   | 45477  | 2024-07-04 |

Both rows show the same text. No date-format pattern can separate them — only
the numeric side can. Conversely, `Dual(0, 'lun.')` carries a weekday label that
no amount of arithmetic will reproduce.

Companion columns keep both sides. For a field `F` they add `F_str` (the display
string) and `F_num` (the raw Qlik serial, days since 1899-12-30, *not*
epoch-shifted).

Dual-ness is a property of each individual symbol, not of the field, so whether
a companion is *useful* can only be answered by reading the data. That would make
the output schema data-dependent, which is usually unacceptable in a pipeline —
so the behaviour is explicitly three-way:

| `--dual-companions` | Reads the data? | Use when |
|---------------------|-----------------|----------|
| `off` (default)     | no  | always, unless you need companions |
| `explicit`          | **no** | in a pipeline — emits exactly the fields you pin |
| `auto`              | yes | exploring an unfamiliar QVD |

`explicit` never inspects a symbol: it emits companions for every field named by
`--dual-strategy-field`, whether or not that field would benefit, and even if
the field is **absent from the file** (the columns are then all-null). That is
what makes the schema reproducible across files.

`auto` emits a companion only where a side genuinely carries information — it
skips `Dual(1, "1")`, and is locale-aware, so the French `Dual(45306,25,
"45306,25")` is correctly recognised as a round-trip rather than new
information. It prints a warning, because two QVDs with the same fields can
produce different columns.

The intended workflow is to let `auto`'s analysis decide once, then pin it:

```bash
# 1. Look: what do the duals and date formats in this file actually look like?
qvd-parser-cli duals --input data.qvd

# 2. Copy: the same analysis as a command-line fragment
qvd-parser-cli duals --input data.qvd --format args
#   --dual-companions explicit \
#     --dual-strategy-field First_Date \
#     --date-format First_Date=DD/MM/YYYY
#   # UNRESOLVED: Order_Date — mixes formats; best candidate DD/MM/YYYY covers only 8 of 11...

# 3. Pin: paste it into the export. The schema no longer depends on the data.
qvd-parser-cli export --input data.qvd --output data.parquet --format parquet \
  --cast First_Date=DATE32 \
  --dual-companions explicit --dual-strategy-field First_Date \
  --date-format First_Date=DD/MM/YYYY
```

`duals --format json` writes the same conclusions as a `--schema-overrides`
file. The report deliberately **refuses to recommend a format** when the file
cannot settle the question: where `DD/MM/YYYY` and `MM/DD/YYYY` both parse every
value but disagree on what they mean, guessing would produce silently wrong
dates. A format that merely covers *fewer* values is eliminated instead, so an
ordinary `DD/MM/YYYY` column is reported cleanly even though days 1–12 are also
valid months.

Naming is controlled by four independent options — `--dual-string-prefix`,
`--dual-string-suffix`, `--dual-numeric-prefix`, `--dual-numeric-suffix`. Each
accepts an optional value (`--dual-string-suffix` alone means `_str`), and
supplying any of them enables that companion kind, so string-only or
numeric-only output is just a matter of which you pass. A generated name that
would collide with an existing field is an error rather than a silent rename.
Per-field names can be set in the `--schema-overrides` file:

```json
{
  "First_Date":  { "cast": "DATE32", "date_format": "DD/MM/YYYY", "dual": true },
  "DEL_Pricing": { "string_field": "pricing_label", "numeric_field": "pricing_raw" }
}
```

## Python usage

```python
import qvd_parser

# From a file path (Rust opens the file directly)
f = qvd_parser.QvdFile.open("data.qvd")
print(f.table_name, f.row_count, f.field_names())

for row in f.rows():
    print(row)  # list of Python-native values (int, float, str, tuple, None)

# Export
f.to_parquet("out.parquet")
f.to_parquet("out.parquet", cast_overrides={"DateField": "DATE32", "Amount": "FLOAT64"})
f.to_parquet("out.parquet", schema_overrides_file="overrides.json")
f.to_parquet("out.parquet", strict_mode="strict_first")  # raise on first cast error
f.to_parquet("out.parquet", strict_mode="strict_all")    # raise with the full error list
f.to_parquet("out.parquet", fallback_type="INT64")       # all-null columns default to INT64 instead of STRING

# Text field holding string dates, forced to a timestamp column
f.to_parquet(
    "out.parquet",
    cast_overrides={"First_Date": "TIMESTAMP_MS"},
    date_formats={"First_Date": "DD/MM/YYYY HH24:MI:SS|MM/DD/YYYY HH24:MI:SS"},
)
f.to_parquet("out.parquet", default_date_format="YYYY-MM-DD")
f.to_parquet("out.parquet", date_tag_inference=False)   # keep $timestamp DATE fields as INT64

# Dual companion columns — adds First_Date_str and First_Date_num alongside the
# cast date column. "explicit" does not read the data, so the schema is the same
# for every file; "auto" inspects the symbols and may differ between files.
f.to_parquet(
    "out.parquet",
    cast_overrides={"First_Date": "DATE32"},
    dual_companions="explicit",
    dual_strategy_fields=["First_Date"],
)
f.to_parquet("out.parquet", dual_companions="auto")   # data-dependent schema
f.to_parquet(                                          # custom naming
    "out.parquet",
    dual_companions="explicit",
    dual_strategy_fields=["First_Date"],
    dual_string_prefix="label_",
    dual_numeric_suffix="_serial",
)

# Split into files of at most 240 MB (same naming rules as the CLI).
# max_file_size takes an int (bytes) or a str with a unit.
result = f.to_parquet("out.parquet", max_file_size="240MB")
print(result.files)   # ['out_part0001.parquet', 'out_part0002.parquet', ...]
f.to_parquet("sales_<partid>_2026.parquet", max_file_size=240_000_000)

f.to_json("out.json")
f.to_csv("out.csv", delimiter=";")

# to_parquet() returns a CastWarnings object (default strict_mode="silent"):
# empty/falsy if every value cast successfully, otherwise inspect .entries
warnings = f.to_parquet("out.parquet", cast_overrides={"Amount": "FLOAT64"})
if warnings:
    for w in warnings.entries:
        print(w)  # "field 'Amount' row 42: cannot cast Text to FLOAT64: cannot parse 'N/A' as FLOAT64: ..."
```

### Filtering rows (Python)

The same three filter kinds as the CLI, exposed two ways.

`filter()` returns a **new `QvdFile`** holding only the matching rows, so every
method works on the subset — including the exporters:

```python
f = qvd_parser.QvdFile.open("data.qvd")

# Kind 1 — a list of values
sub = f.filter(field="Country", values=["FR", "DE", "IT"])
print(sub.row_count)
sub.to_csv("subset.csv")

# Kind 2 — wildcards ('*' any run, '?' one character)
f.filter(field="Product", like=["ABC*", "X?Z"]).to_parquet("abc.parquet")

# Kind 3 — bounds: ge/gt for the lower, le/lt for the upper
f.filter(field="Amount", ge="100", lt="500").to_json("mid.json")

# Filters compose — each call returns a QvdFile
f.filter(field="Country", values=["FR"]).filter(field="Amount", ge="100")

# limit=None (default) keeps every match; with no condition, a plain head
f.filter(field="Country", values=["FR"], limit=1000)
f.filter(limit=100)
```

`iter_rows()` takes the same arguments but **yields rows lazily**, so previewing
matches in a large file never builds the full list in Python memory:

```python
for row in f.iter_rows(field="Country", values=["FR"], limit=10):
    print(row)

names = f.field_names()
for row in f.iter_rows(field="Amount", ge="100"):
    record = dict(zip(names, row))
```

Values follow the `rows()` mapping — dual variants arrive as `(numeric, str)`
tuples rather than collapsing to their display string as `to_dict()` does.

Date bounds behave exactly as on the CLI: automatic for a field tagged
`$date`/`$timestamp` or with a `DATE`/`TIMESTAMP`/`INTERVAL` NumberFormat,
overridable with `date_format=`.

```python
# Implicit — Date is $date-tagged
f.filter(field="Date", ge="01/01/2024", le="31/12/2024")

# Timestamps compare with their time of day
f.filter(field="EventTs", ge="25/12/2024 06:00:00")

# Explicit — a date stored as text in a different layout
f.filter(field="TxtDate", ge="2024-01-01", date_format="YYYY-MM-DD")
```

`ValueError` is raised for an unknown field, mixed filter kinds, two bounds on
the same side, a field with no condition (or the reverse), and a bound the
field's scale cannot read. NULL never matches any filter.

### Parsing from in-memory bytes

When the QVD is already in memory — downloaded from a signed URL, read from
object storage, or loaded via any other source that does not produce a file
path — use `from_bytes()`:

```python
# From a signed URL (no temporary file needed)
import requests
data = requests.get(signed_url).content
f = qvd_parser.QvdFile.from_bytes(data)

# AWS S3
data = s3_client.get_object(Bucket="my-bucket", Key="data.qvd")["Body"].read()
f = qvd_parser.QvdFile.from_bytes(data)

# Python file handle (equivalent to open(), Python controls the lifecycle)
with open("data.qvd", "rb") as fh:
    f = qvd_parser.QvdFile.from_bytes(fh.read())
```

All methods available on `open()` results are available on `from_bytes()`
results: `rows()`, `to_dict()`, `to_parquet()`, `to_json()`, `to_csv()`, etc.

> **Note on memory usage:** `from_bytes()` requires the entire QVD to be in
> RAM. This is unavoidable when the source is an in-memory buffer. If you
> have a file path and memory is a concern, prefer `open()` — it lets the OS
> manage buffering.

### Tables from a QVF (Qlik Sense app) — low-level

A QVF stores its data model like a QVD (symbol tables + bit-packed indices),
so qvd-parser exposes decoders for the QVF **data payloads** and turns a QVF
table into an ordinary `QvdFile`: type inference, dual companions, date
handling, filters and every exporter then behave exactly as for a QVD. Reading
the QVF *container* (index, descriptors, zlib) is the job of the QVF library,
which depends on qvd-parser; these functions take bytes already inflated.

Rust (`qvd_parser::qvf`):

```rust
use qvd_parser::qvf::{build_table, QvfColumnParts};

let table = build_table("Sales", n_rows, &[QvfColumnParts {
    name: "Date".into(),
    field_prefix: &prefix,      // bytes in front of the field_N zlib stream
    symbols_payload: &symbols,  // inflated field_N
    stream: &bits,              // inflated column bit stream of table_N
    bit_width: 12,
    bias: 0,
}])?;
let out = std::fs::File::create("sales.parquet")?;
qvd_convert::write_parquet(&table, out, &qvd_convert::ParquetExportOptions::default())?;
```

Lower-level pieces: `read_varint`, `read_pstr`, `decode_field_names`,
`parse_field_prefix`, `decode_symbols`, `unpack_column`. Any reader can also use
`QvdFile::from_parts` / `QvdFile::from_column_indices` directly.

Python:

```python
f = qvd_parser.QvdFile.from_qvf_parts("Sales", n_rows, [
    {"name": "Date", "field_prefix": prefix, "symbols": symbols,
     "stream": bits, "bit_width": 12, "bias": 0},
])
f.to_parquet("sales.parquet")
```

Date fields (QVF number type 3) receive synthetic `$date` / `$timestamp` tags,
so they get the same Arrow type as the QVD Qlik writes for them. Other QVF
number-type codes are not decoded yet and map to `UNKNOWN`.
#### Cross-checking QVF and QVD (`fixtures/generate-qvf-roundtrip.qvs`)

The script builds an app that holds the same data three ways, to check that
QVF -> QVD and QVD -> QVF change nothing and that both decoders agree:

| version | what                                                                 |
|---------|----------------------------------------------------------------------|
| A       | table `T_xxx`, built in memory by the script (in the QVF)            |
| B       | `T_xxx.qvd`, STORE of A                                              |
| C       | table `RT_T_xxx`, optimized LOAD of B under `QUALIFY` (in the QVF)   |

Tables (each with its own field prefix, so none are associated): `T_INT`
(i32 limits and beyond, booleans, a constant field, an all-NULL field),
`T_FLOAT` (number formats: money, percent, decimal comma / point),
`T_TEXT` (empty, Unicode, 200- and 20 000-byte strings, text that looks
numeric), `T_DATE` (dates, timestamps, times, intervals, epoch edges, an
ambiguous `04/07/2024`), `T_DUAL` (explicit and mixed-type duals),
`T_HIGHCARD` (70 000 rows, bit widths > 16), `T_SINGLE`, `T_EMPTY`.

Steps:

1. Create a Qlik Sense app with the script. Set `vDir` (default
   `lib://QVD/qvf-roundtrip/`) to a data connection you can write to. Reload.
2. Export the app **with data** (hub: *Export app*, or QMC).
3. Copy the QVDs from `vDir` into a local folder.
4. Run the comparison script from the QVF project (it uses `qvf_parser.py` to
   read the QVF container and this library's `from_qvf_parts` to decode):

```bash
python crosscheck_qvd_qvf.py roundtrip app.qvf qvd_folder [--prefix RT_] [--out DIR]
```

It compares A, B and C cell by cell (value and symbol kind) and their Parquet
exports (Arrow type and values), and exits with code 1 on any difference.
The same script has an `oracle` mode
(`python crosscheck_qvd_qvf.py oracle app.qvf`) that compares this library's
decoding of a QVF with the reference Python reader. How to read the output is
described in `QVF_FORMAT.md` §8.1 (QVF project).

### Python version compatibility

Tested in CI against CPython 3.11, 3.12 and 3.13 (Linux x86_64).

## Test fixtures

Integration tests require real QVD files generated by Qlik — synthetic QVD
files are not possible due to the proprietary bit-packing format.

Place fixture files in `fixtures/` at the workspace root:

| File | Content |
|---|---|
| `test-data-minimal.qvd` | 2 columns (`id: Int`, `label: Text`), 2 rows: `[1, "test1"], [2, "test2"]` — primary fixture for Rust and Python tests |
| `all-nulls.qvd` | 2 columns, `nullable_col` entirely NULL — 3 rows |
| `all-types.qvd` | 6 columns covering all `QvdValue` variants: Int, Double, Text, DualInt, DualDouble, Null |
| `single-row.qvd` | Exactly 1 row — iterator and size_hint edge case |
| `empty-table.qvd` | 0 rows, schema present — 2 columns |
| `large-integers.qvd` | Values at `i32::MIN`/`i32::MAX` and byte/word boundaries |
| `unicode-strings.qvd` | Multi-byte UTF-8 strings: accented Latin characters, CJK |
| `high-cardinality.qvd` | 100 rows, `unique_label` with 100 distinct values |
| `wide-record.qvd` | `RecordByteSize > 16` — regression fixture for the u128 overflow bug |
| `mixed-types.qvd` | Heterogeneous symbol table: Int, Double, Text, NULL in the same column |
| `bench-symbols.qvd` | 1 000 rows × 3 fields, high-cardinality symbol tables — benchmark fixture |
| `bench-rows.qvd` | 5 000 rows × 8 fields, mixed cardinality, all QvdValue variants — benchmark fixture |
| `all-date-formats.qvd` | 28 columns × 12 rows touring every Qlik date representation. 20 of the 28 fields are duals. Note Qlik re-interprets values during `LOAD INLINE`, so several columns are not the binary type their name suggests — `str_mmddyyyy_raw` is the only genuinely pure-`Text` date column |
| `date-edge-cases.qvd` | 17 columns × 12 rows of deliberately awkward date cases, in three families: **A** (`dualA_*`) all-dual with mixed display formats, **B** (`dualB_*`) mixed dual and text cells with one uniform format, **C** (`textC_*`) pure text with mixed formats. Generated by `generate-date-edge-cases.qvs`. Rows 4 and 5 of `dualA_alt_ddmm_mmdd` both display `04/07/2024` but carry serials 45389 and 45477 — the case no text parsing can resolve |

All fixtures must be generated with Qlik (QlikView or Qlik Sense) using
`generate-fixtures.qvs`. Synthetic QVD generation is not possible due to the
proprietary bit-packing format.

When writing a new date fixture, never reuse one numeric value across rows that
should display differently: Qlik compares duals by their number, so the symbols
collapse into one and the distinct display strings are lost.

Tests that rely on missing fixtures are skipped at runtime when
`--features integration-tests` is active.

## Feature flags

| Flag | Crate | Effect |
|---|---|---|
| `integration-tests` | `core`, `convert` | Enable tests that require fixture files |
| `serde` | `core` | Derive `Serialize`/`Deserialize` on public types |

### Python binding entry points

| Method | Input | Use case |
|---|---|---|
| `QvdFile.open(path: str)` | File path | Rust opens and buffers the file — preferred when a path is available |
| `QvdFile.from_bytes(data: bytes \| bytearray \| memoryview)` | In-memory bytes | QVD already in RAM (signed URL, object storage, `BytesIO`) |
| `QvdFile.from_qvf_parts(table_name, n_rows, columns)` | Decoded QVF table parts | Build a `QvdFile` from columns decoded out of a QVF (see above) |

---

## Release workflow

This project uses two separate repositories:

- **GitLab** (private) — daily development, full commit history
- **GitHub** (public) — published releases only, single commit per version

GitHub receives only validated, committed code from GitLab. The full
development history never appears on GitHub.

### Publishing a new release (Windows)

Ensure the version to publish is committed and pushed on GitLab `main`:

```powershell
# 1. From the GitLab workspace, export the clean content
cd C:\path\to\qvd-parser
git checkout main
git pull origin main
git archive HEAD | tar -x -C C:\path\to\qvd-parser-public

# 2. Commit and push to GitHub
cd C:\path\to\qvd-parser-public
git add .
git commit -m "Release vX.Y.Z"
git push github main
```

`git archive HEAD` exports exactly the content of the last commit, respecting
`.gitignore`. Files not committed (build artifacts, fixtures, `.venv`) are
automatically excluded.

### GitHub repository setup (once)

```powershell
mkdir C:\path\to\qvd-parser-public
cd C:\path\to\qvd-parser-public
git init
git remote add github git@github.com:nicolasstefaniuk/qvd-parser.git
git config user.email "287317062+nicolasstefaniuk@users.noreply.github.com"
git config user.name "Nicolas Stefaniuk"
```

---

## Performance — Parquet export investigation

### Context

QVD files use a columnar symbol table + row-major bit-packed index buffer.
Parsing is inherently row-major (impossible to read one column without traversing
all rows). Parquet is column-major. This impedance mismatch is the core
performance challenge.

### Measurements (release build, 140 fields × 119 820 rows × 16.5 MB QVD)

```
load header+symbols+rows    ~120 ms
  header                       1 ms
  symbols                     23 ms
  rows (bit-unpack)           95 ms

export parquet              ~650 ms
  type inference               0 ms
  index transpose             43 ms   ← column_indices_range
  cast to arrow              160 ms   ← QvdValue → Arrow arrays
  parquet encode             400 ms   ← RLE/dictionary encoding (Arrow writer)
  parquet close               48 ms
```

Ratio parsing:export ≈ 1:5. The bottleneck is the Arrow/Parquet writer, not our code.

### Hypotheses tested

**1. Cache thrashing on strided index access (fixed)**

The original export collected per-column indices by striding through the
row-major buffer (`n_fields × 4` bytes per step), causing cache misses on
wide files. Fixed by adding `QvdFile::column_indices_range()` in `core`:
a single sequential pass that scatters into `n_fields` contiguous vectors.
Measured gain: ~15% on `index transpose`.

**2. Dictionary encoding for string columns (implemented, marginal gain)**

With only 11–15 distinct values per column out of 119 820 rows, passing
pre-built `DictionaryArray<Int32, Utf8>` to the Parquet writer should
avoid per-row string copies and skip the encoder's internal deduplication.

Result: ~6% total gain in release, negligible. The Arrow writer (arrow-rs 53.x)
still does substantial work on `DictionaryArray`. Additionally, numeric
dictionary arrays (`DictionaryArray<Int32, Int64>` etc.) are not supported
by `ArrowWriter` in this version and panic at runtime — restricted to `Utf8` only.

Available as `--encoding dictionary` for experimentation. Not recommended for
production use until arrow-rs improves dictionary support.

**3. Column statistics (implemented, ~20% gain)**

Parquet column statistics (min/max per page) cost ~130 ms on this file.
They are enabled by default because they allow query engines to skip row
groups during reads, which typically saves far more time than the export cost.

Disabling them with `--no-statistics` saves ~20% export time. Use when
export speed is critical and the consumer does not rely on statistics.

### Conclusion

The 5× ratio between parsing and Parquet export is inherent to the Arrow
writer, not to our code. The practical levers available in our layer are:

| Optimisation | Gain | Status |
|---|---|---|
| `column_indices_range` (sequential scatter) | ~15% index transpose | Enabled by default |
| `--no-statistics` | ~20% parquet encode | Opt-in flag |
| `--encoding dictionary` | <10% on Utf8 columns | Experimental, opt-in |

A more significant improvement would require either a lower-level Parquet
crate (e.g. `parquet2`) or parallelising column encoding — both are
substantial changes outside the current scope.

---

## Possible improvements (not implemented)

### CLI usability

- **Example values in `schema`.** Show a few values per field, as
  `check_exported_parquet.py` does, so value storage (casing, padding,
  number/date display) is visible before writing a filter. The symbol table
  could supply them without decoding rows. Make the count configurable
  (e.g. `--examples N`, `0` to disable).
- **Warning on empty export, plus a quiet mode.** Warn on stderr when 0 rows
  are exported. `--verbose` is a boolean, so a way to suppress all non-error
  output is needed: either `--quiet` / `-q` (backward compatible, conflicts
  with `--verbose`) or a level such as `--verbose silent|normal|debug`.
- **Parquet as the default export format.** `export` currently defaults to
  `json`. Better: infer the format from the `--output` extension when
  `--format` is omitted, falling back to `parquet`. Breaking for scripts that
  rely on the default — record in CHANGELOG.
- **Warning when the output extension does not match the format.** E.g.
  `--format json --output out.parquet`. Warn only, never fail; respect quiet
  mode.
- **Readable dates in `print-row`.** Show date/timestamp fields
  (`$date`/`$timestamp` tag or DATE/TIMESTAMP NumberFormat) in a readable
  format, by default `YYYY-MM-DD HH24:MM:SS`, rather than the raw value.
  Respect `--date-format` when given. Add a
  flag `--no-date-cast` to show the original value as stored, with no
  conversion.
- **Filters on several fields in the CLI.** Today one field per command;
  multi-field filtering requires the Python API (chained `filter()` calls).

---

## Legal & Interoperability

### Trademark notice

"Qlik", "QlikView", and "Qlik Sense" are registered trademarks of Qlik
Technologies Inc. The file extension "QVD" is a technical descriptor for
the file format, not a registered trademark.

This project is not affiliated with, endorsed by, or sponsored by Qlik in
any way. The name `qvd-parser` is used solely to describe what the library
does — reading files in the QVD format — and constitutes nominative
descriptive use, not trademark infringement.

### Reverse engineering and interoperability

This library was developed by observing the structure of QVD files produced
by Qlik software. No Qlik source code was copied, decompiled, or
incorporated. The parser is an independent implementation.

Reading a file format for the purpose of interoperability is explicitly
permitted under applicable law:

- **European Union** — Directive 2009/24/EC on the legal protection of
  computer programs, Article 6, permits decompilation and reverse engineering
  for interoperability purposes, notwithstanding any contractual restriction
  to the contrary.
- **United States** — 17 U.S.C. § 1201(f) (DMCA) provides a specific
  exemption for reverse engineering undertaken to achieve interoperability.
  This is supported by established case law (*Sega Enterprises Ltd. v.
  Accolade, Inc.*, 977 F.2d 1510; *Sony Computer Entertainment, Inc. v.
  Connectix Corp.*, 203 F.3d 596).

File formats — as distinct from software implementations — are not protected
by copyright as a matter of EU and US law (*SAS Institute Inc. v. World
Programming Ltd*, CJEU C-406/10, 2012).

Enterprise users who require legal sign-off before adopting a dependency are
encouraged to share this section with their legal team.

### License

This project is licensed under the MIT License. See [LICENSE](LICENSE) for
the full text.

Copyright (c) 2025 Nicolas Stefaniuk
