map-conform 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- map_conform/__init__.py +5 -0
- map_conform/__main__.py +7 -0
- map_conform/batch/__init__.py +1 -0
- map_conform/batch/arrow.py +80 -0
- map_conform/batch/columnar.py +125 -0
- map_conform/batch/engine.py +191 -0
- map_conform/batch/files.py +207 -0
- map_conform/cli.py +460 -0
- map_conform/doctor.py +178 -0
- map_conform/errors.py +107 -0
- map_conform/expr/__init__.py +6 -0
- map_conform/expr/compiler.py +562 -0
- map_conform/expr/functions.py +542 -0
- map_conform/expr/sandbox.py +333 -0
- map_conform/expr/sdk.py +116 -0
- map_conform/map-conform-spec.schema.json +1204 -0
- map_conform/mapper.py +355 -0
- map_conform/metadata.py +73 -0
- map_conform/metrics.py +62 -0
- map_conform/naming/__init__.py +1 -0
- map_conform/naming/ascii-table.json +980 -0
- map_conform/naming/conform.py +262 -0
- map_conform/naming/flatten.py +148 -0
- map_conform/naming/nested.py +117 -0
- map_conform/naming/reserved/ansi.txt +369 -0
- map_conform/naming/reserved/duckdb.txt +114 -0
- map_conform/naming/reserved/postgres.txt +105 -0
- map_conform/naming/reserved/snowflake.txt +90 -0
- map_conform/naming/reserved.py +34 -0
- map_conform/naming/shape.py +96 -0
- map_conform/naming/streams.py +76 -0
- map_conform/naming/translit.py +170 -0
- map_conform/plan/__init__.py +1 -0
- map_conform/plan/chain.py +667 -0
- map_conform/plan/compile.py +551 -0
- map_conform/plan/lower.py +281 -0
- map_conform/plan/ops.py +336 -0
- map_conform/plan/row.py +212 -0
- map_conform/plan/vector.py +71 -0
- map_conform/rejects.py +92 -0
- map_conform/settings.py +157 -0
- map_conform/spec/__init__.py +1 -0
- map_conform/spec/_struct.py +483 -0
- map_conform/spec/bridge.py +109 -0
- map_conform/spec/check.py +380 -0
- map_conform/spec/errors.py +22 -0
- map_conform/spec/importer.py +87 -0
- map_conform/spec/jsonschema.py +54 -0
- map_conform/spec/load.py +357 -0
- map_conform/spec/model.py +473 -0
- map_conform/spec/reference.py +179 -0
- map_conform/spec/steps.py +297 -0
- map_conform/spec/stream_maps.py +233 -0
- map_conform/spec/zamboni.py +99 -0
- map_conform/transforms/__init__.py +1 -0
- map_conform/transforms/builtins.py +63 -0
- map_conform/transforms/casts.py +310 -0
- map_conform/transforms/fake.py +150 -0
- map_conform/transforms/nested.py +111 -0
- map_conform/transforms/numeric.py +318 -0
- map_conform/transforms/polars_vector.py +151 -0
- map_conform/transforms/privacy.py +220 -0
- map_conform/transforms/registry.py +116 -0
- map_conform/transforms/temporal.py +410 -0
- map_conform/transforms/text.py +249 -0
- map_conform/transforms/vector.py +386 -0
- map_conform/types/__init__.py +1 -0
- map_conform/types/canonical.py +255 -0
- map_conform/types/from_jsonschema.py +177 -0
- map_conform/types/jsontext.py +63 -0
- map_conform/types/to_arrow.py +52 -0
- map_conform/types/to_jsonschema.py +65 -0
- map_conform/types/wire.py +53 -0
- map_conform/udfs.py +327 -0
- map_conform-0.1.0.dist-info/METADATA +157 -0
- map_conform-0.1.0.dist-info/RECORD +79 -0
- map_conform-0.1.0.dist-info/WHEEL +4 -0
- map_conform-0.1.0.dist-info/entry_points.txt +2 -0
- map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
map_conform/__init__.py
ADDED
map_conform/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""BATCH messages: read the manifest files, conform their rows, write them out (§10.3)."""
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Conformed rows as Arrow data, with the plan's declared schema (detailed design §10.2).
|
|
2
|
+
|
|
3
|
+
Rows reach this module in their wire form, the exact values a RECORD message carries, so a
|
|
4
|
+
BATCH file holds the same data as the RECORD path would. Each wire value is turned back into
|
|
5
|
+
the Python value its Arrow type takes: exact decimals, temporals, UUID bytes, binary bytes,
|
|
6
|
+
and structs and lists member by member.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import datetime as dt
|
|
13
|
+
import uuid
|
|
14
|
+
from decimal import Decimal
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
import pyarrow as pa
|
|
18
|
+
|
|
19
|
+
from map_conform.metadata import INTEGER_COLUMNS, TIMESTAMP_COLUMNS
|
|
20
|
+
from map_conform.types.canonical import CType
|
|
21
|
+
from map_conform.types.to_arrow import to_arrow
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
25
|
+
|
|
26
|
+
from map_conform.plan.compile import StreamPlan
|
|
27
|
+
|
|
28
|
+
_TIMESTAMPTZ = CType("timestamptz")
|
|
29
|
+
_INT64 = CType("int64")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _parse(kind: str) -> Callable[[Any], Any]:
|
|
33
|
+
parsers: dict[str, Callable[[Any], Any]] = {
|
|
34
|
+
"decimal": Decimal,
|
|
35
|
+
"date": dt.date.fromisoformat,
|
|
36
|
+
"time": dt.time.fromisoformat,
|
|
37
|
+
"timestamp": dt.datetime.fromisoformat,
|
|
38
|
+
"timestamptz": dt.datetime.fromisoformat,
|
|
39
|
+
"uuid": lambda v: uuid.UUID(v).bytes,
|
|
40
|
+
"binary": base64.b64decode,
|
|
41
|
+
}
|
|
42
|
+
return parsers.get(kind, lambda v: v)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def arrow_value(value: object, ctype: CType) -> object:
|
|
46
|
+
"""A wire value as the Python value its Arrow type takes."""
|
|
47
|
+
if value is None:
|
|
48
|
+
return None
|
|
49
|
+
if ctype.kind == "struct" and isinstance(value, dict):
|
|
50
|
+
members = dict(ctype.members)
|
|
51
|
+
return {name: arrow_value(value.get(name), member) for name, member in members.items()}
|
|
52
|
+
if ctype.kind == "list" and isinstance(value, list):
|
|
53
|
+
return [arrow_value(v, ctype.list_item) for v in value]
|
|
54
|
+
return _parse(ctype.kind)(value)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def output_columns(plan: StreamPlan, *, metadata: bool) -> list[tuple[str, CType, bool]]:
|
|
58
|
+
"""(name, CType, nullable) of every output column, ``_sdc_*`` last when added."""
|
|
59
|
+
columns = [(c.name, c.ctype, c.nullable) for c in plan.columns]
|
|
60
|
+
if metadata:
|
|
61
|
+
columns += [(name, _TIMESTAMPTZ, True) for name in TIMESTAMP_COLUMNS]
|
|
62
|
+
columns += [(name, _INT64, True) for name in INTEGER_COLUMNS]
|
|
63
|
+
return columns
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def arrow_schema(columns: Sequence[tuple[str, CType, bool]]) -> pa.Schema:
|
|
67
|
+
"""The declared Arrow schema: ``to_arrow`` of each column."""
|
|
68
|
+
return pa.schema([pa.field(n, to_arrow(t), nullable=nullable) for n, t, nullable in columns])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def to_table(
|
|
72
|
+
rows: Sequence[Mapping[str, Any]], columns: Sequence[tuple[str, CType, bool]]
|
|
73
|
+
) -> pa.Table:
|
|
74
|
+
"""Wire rows as a table with exactly the declared schema."""
|
|
75
|
+
schema = arrow_schema(columns)
|
|
76
|
+
arrays = [
|
|
77
|
+
pa.array([arrow_value(row.get(name), ctype) for row in rows], type=field.type)
|
|
78
|
+
for (name, ctype, _), field in zip(columns, schema, strict=True)
|
|
79
|
+
]
|
|
80
|
+
return pa.Table.from_arrays(arrays, schema=schema)
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""The columnar executor: conform a whole Arrow batch at once (detailed design §10.2).
|
|
2
|
+
|
|
3
|
+
Vectorised columns (:mod:`map_conform.plan.vector`) run as Arrow chains on the whole column.
|
|
4
|
+
Everything else runs through the row executor, row by row, skipping the vectorised columns
|
|
5
|
+
for the rows they computed: columns with expressions, the filter, ``_sdc_*``, policies,
|
|
6
|
+
rejects and metrics all behave exactly as on the RECORD path. Rows a vector op left as todo
|
|
7
|
+
are computed by the row executor too, and *spliced* into the column (WBS 8.5).
|
|
8
|
+
|
|
9
|
+
Rejected rows (``on_error: reject``) and rows the filter drops are taken out of the batch;
|
|
10
|
+
the output table has exactly the declared schema.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import TYPE_CHECKING, Any
|
|
17
|
+
|
|
18
|
+
import pyarrow as pa
|
|
19
|
+
import pyarrow.compute as _compute
|
|
20
|
+
|
|
21
|
+
from map_conform.batch.arrow import arrow_schema, arrow_value, output_columns
|
|
22
|
+
from map_conform.errors import RowRejected
|
|
23
|
+
from map_conform.plan.row import RowExecutor
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from collections.abc import Callable
|
|
27
|
+
|
|
28
|
+
# The pyarrow stubs type compute kernels as returning unions of arrays, chunked arrays and
|
|
29
|
+
# scalars, so array-in, array-out code cannot be checked through them. The parity suite
|
|
30
|
+
# (tests/parity) checks this module against the scalar path instead.
|
|
31
|
+
_pa: Any = pa
|
|
32
|
+
pc: Any = _compute
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def columnar(executor: RowExecutor) -> bool:
|
|
36
|
+
"""Whether the stream's plan has vectorised columns worth a columnar run."""
|
|
37
|
+
plan = executor.plan
|
|
38
|
+
return not plan.shaped and plan.flattener is None and any(c.vector for c in plan.columns)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class ColumnarExecutor:
|
|
43
|
+
"""Runs one output stream's plan on Arrow batches."""
|
|
44
|
+
|
|
45
|
+
executor: RowExecutor
|
|
46
|
+
|
|
47
|
+
def run(
|
|
48
|
+
self,
|
|
49
|
+
table: pa.Table,
|
|
50
|
+
*,
|
|
51
|
+
passed: dict[str, Any],
|
|
52
|
+
first_row: int,
|
|
53
|
+
batched_at: str,
|
|
54
|
+
reject: Callable[[RowRejected, dict[str, Any]], None],
|
|
55
|
+
) -> pa.Table:
|
|
56
|
+
"""The conformed batch; rejected and filtered rows are left out."""
|
|
57
|
+
plan = self.executor.plan
|
|
58
|
+
vectors = {
|
|
59
|
+
i: column.vector.run(self._source(table, column.sources))
|
|
60
|
+
for i, column in enumerate(plan.columns)
|
|
61
|
+
if column.vector is not None
|
|
62
|
+
}
|
|
63
|
+
todo: dict[int, list[bool]] = {
|
|
64
|
+
i: [bool(flag) for flag in mask.to_pylist()] for i, (_, mask) in vectors.items()
|
|
65
|
+
}
|
|
66
|
+
records = table.to_pylist()
|
|
67
|
+
kept: list[int] = []
|
|
68
|
+
outputs: list[dict[str, Any] | None] = []
|
|
69
|
+
for n, record in enumerate(records):
|
|
70
|
+
skip = frozenset(i for i, rows in todo.items() if not rows[n])
|
|
71
|
+
try:
|
|
72
|
+
out = self.executor.run(record, passed, first_row + n, batched_at=batched_at,
|
|
73
|
+
skip=skip) # fmt: skip
|
|
74
|
+
except RowRejected as rejected:
|
|
75
|
+
reject(rejected, record)
|
|
76
|
+
out = None
|
|
77
|
+
outputs.append(out)
|
|
78
|
+
if out is not None:
|
|
79
|
+
kept.append(n)
|
|
80
|
+
return self._assemble(vectors, todo, outputs, kept)
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def _source(table: pa.Table, sources: tuple[str, ...]) -> pa.Array:
|
|
84
|
+
present = [table.column(s).combine_chunks() for s in sources if s in table.column_names]
|
|
85
|
+
if not present:
|
|
86
|
+
return _pa.nulls(table.num_rows)
|
|
87
|
+
if len(present) == 1 or len({a.type for a in present}) > 1:
|
|
88
|
+
return present[0] if len(present) == 1 else _pa.nulls(table.num_rows)
|
|
89
|
+
return pc.coalesce(*present)
|
|
90
|
+
|
|
91
|
+
def _assemble(
|
|
92
|
+
self,
|
|
93
|
+
vectors: dict[int, tuple[pa.Array, pa.Array]],
|
|
94
|
+
todo: dict[int, list[bool]],
|
|
95
|
+
outputs: list[dict[str, Any] | None],
|
|
96
|
+
kept: list[int],
|
|
97
|
+
) -> pa.Table:
|
|
98
|
+
executor = self.executor
|
|
99
|
+
columns = output_columns(executor.plan, metadata=executor.metadata is not None)
|
|
100
|
+
schema = arrow_schema(columns)
|
|
101
|
+
index = _pa.array(kept, type=pa.int64())
|
|
102
|
+
arrays: list[pa.Array] = []
|
|
103
|
+
for position, ((name, ctype, _), field) in enumerate(zip(columns, schema, strict=True)):
|
|
104
|
+
if position in vectors:
|
|
105
|
+
values, mask = vectors[position]
|
|
106
|
+
rows = todo[position]
|
|
107
|
+
spliced = [
|
|
108
|
+
arrow_value(out.get(name), ctype) if out is not None else None
|
|
109
|
+
for out, flag in zip(outputs, rows, strict=True)
|
|
110
|
+
if flag
|
|
111
|
+
]
|
|
112
|
+
if spliced:
|
|
113
|
+
values = pc.replace_with_mask(values, mask, _pa.array(spliced, type=field.type))
|
|
114
|
+
arrays.append(values.take(index))
|
|
115
|
+
else:
|
|
116
|
+
arrays.append(_pa.array(
|
|
117
|
+
[arrow_value(_get(outputs[n], name), ctype) for n in kept],
|
|
118
|
+
type=field.type,
|
|
119
|
+
)) # fmt: skip
|
|
120
|
+
return _pa.Table.from_arrays(arrays, schema=schema)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _get(out: dict[str, Any] | None, name: str) -> object:
|
|
124
|
+
"""A kept row's wire value (kept rows always have an output)."""
|
|
125
|
+
return None if out is None else out.get(name)
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Conform a BATCH message (detailed design §10.3, WBS 8.1-8.3 and 8.8).
|
|
2
|
+
|
|
3
|
+
Each manifest file is read in chunks and every row is conformed by the stream's executors,
|
|
4
|
+
exactly as a RECORD would be: the same plan, ``on_error``, rejects, filter and metrics.
|
|
5
|
+
Then, per ``batch_output.mode``:
|
|
6
|
+
|
|
7
|
+
- ``batch``: one output file per input file and output stream, in the input's order, then one
|
|
8
|
+
BATCH message per output stream listing its files (``version`` and ``time_extracted``
|
|
9
|
+
passed on);
|
|
10
|
+
- ``record``: RECORD messages, for targets that do not read BATCH.
|
|
11
|
+
|
|
12
|
+
``_sdc_batched_at`` is the input file's last-modified time. With ``delete_input`` each input
|
|
13
|
+
file is deleted once every output written from it is complete.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from collections.abc import Callable, Iterator
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import TYPE_CHECKING, Any
|
|
21
|
+
|
|
22
|
+
from map_conform.batch.arrow import output_columns
|
|
23
|
+
from map_conform.batch.columnar import ColumnarExecutor, columnar
|
|
24
|
+
from map_conform.batch.files import (
|
|
25
|
+
Writer,
|
|
26
|
+
compression_for,
|
|
27
|
+
delete,
|
|
28
|
+
last_modified,
|
|
29
|
+
output_uri,
|
|
30
|
+
read_rows,
|
|
31
|
+
read_tables,
|
|
32
|
+
)
|
|
33
|
+
from map_conform.errors import RowRejected
|
|
34
|
+
from map_conform.settings import BatchOutputSettings
|
|
35
|
+
|
|
36
|
+
if TYPE_CHECKING:
|
|
37
|
+
from map_conform.plan.row import RowExecutor
|
|
38
|
+
|
|
39
|
+
Reject = Callable[["RowExecutor", RowRejected, dict[str, Any]], None]
|
|
40
|
+
"""The mapper's reject handler: counts the row and writes it to the reject sink."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class BatchEngine:
|
|
45
|
+
"""Conforms the BATCH messages of one run."""
|
|
46
|
+
|
|
47
|
+
settings: BatchOutputSettings
|
|
48
|
+
run_id: str
|
|
49
|
+
reject: Reject
|
|
50
|
+
rows: dict[str, int] = field(default_factory=dict)
|
|
51
|
+
"""Rows seen per tap stream, shared with the RECORD path."""
|
|
52
|
+
_numbers: dict[str, int] = field(default_factory=dict)
|
|
53
|
+
|
|
54
|
+
def process(
|
|
55
|
+
self, message: dict[str, Any], executors: list[RowExecutor]
|
|
56
|
+
) -> Iterator[dict[str, Any]]:
|
|
57
|
+
"""The messages that replace one BATCH message."""
|
|
58
|
+
tap_stream = message["stream"]
|
|
59
|
+
passed: dict[str, Any] = {
|
|
60
|
+
k: message[k] for k in ("version", "time_extracted") if k in message
|
|
61
|
+
}
|
|
62
|
+
manifests: dict[int, list[str]] = {id(e): [] for e in executors}
|
|
63
|
+
params = self.settings.storage.params
|
|
64
|
+
encoding = message.get("encoding") or {}
|
|
65
|
+
for uri in message.get("manifest", []):
|
|
66
|
+
batched_at = last_modified(uri, params).isoformat()
|
|
67
|
+
writers: dict[int, Writer] = {}
|
|
68
|
+
if self._columnar(encoding, executors):
|
|
69
|
+
self._columnar_file(
|
|
70
|
+
uri, tap_stream=tap_stream, executors=executors, passed=passed,
|
|
71
|
+
batched_at=batched_at, writers=writers,
|
|
72
|
+
) # fmt: skip
|
|
73
|
+
chunks: Iterator[list[dict[str, Any]]] = iter(())
|
|
74
|
+
else:
|
|
75
|
+
chunks = read_rows(uri, encoding, params, self.settings.row_group_size)
|
|
76
|
+
for chunk in chunks:
|
|
77
|
+
yield from self._chunk(
|
|
78
|
+
chunk,
|
|
79
|
+
tap_stream=tap_stream,
|
|
80
|
+
executors=executors,
|
|
81
|
+
passed=passed,
|
|
82
|
+
batched_at=batched_at,
|
|
83
|
+
uri=uri,
|
|
84
|
+
writers=writers,
|
|
85
|
+
)
|
|
86
|
+
for executor in executors:
|
|
87
|
+
writer = writers.get(id(executor))
|
|
88
|
+
if writer is not None:
|
|
89
|
+
writer.close()
|
|
90
|
+
manifests[id(executor)].append(writer.uri)
|
|
91
|
+
if self.settings.delete_input:
|
|
92
|
+
delete(uri, params)
|
|
93
|
+
if self.settings.mode == "batch":
|
|
94
|
+
fmt = self.settings.format
|
|
95
|
+
encoding = {
|
|
96
|
+
"format": fmt,
|
|
97
|
+
"compression": compression_for(fmt, self.settings.compression),
|
|
98
|
+
}
|
|
99
|
+
for executor in executors:
|
|
100
|
+
files = manifests[id(executor)]
|
|
101
|
+
if files:
|
|
102
|
+
yield {"type": "BATCH", "stream": executor.plan.name, "encoding": encoding,
|
|
103
|
+
"manifest": files, **passed} # fmt: skip
|
|
104
|
+
|
|
105
|
+
def _chunk( # noqa: PLR0913 -- the chunk and where it goes
|
|
106
|
+
self,
|
|
107
|
+
chunk: list[dict[str, Any]],
|
|
108
|
+
*,
|
|
109
|
+
tap_stream: str,
|
|
110
|
+
executors: list[RowExecutor],
|
|
111
|
+
passed: dict[str, Any],
|
|
112
|
+
batched_at: str,
|
|
113
|
+
uri: str,
|
|
114
|
+
writers: dict[int, Writer],
|
|
115
|
+
) -> Iterator[dict[str, Any]]:
|
|
116
|
+
buffers: dict[int, list[dict[str, Any]]] = {id(e): [] for e in executors}
|
|
117
|
+
for record in chunk:
|
|
118
|
+
row = self.rows[tap_stream] = self.rows.get(tap_stream, 0) + 1
|
|
119
|
+
for executor in executors:
|
|
120
|
+
try:
|
|
121
|
+
out = executor.run(record, passed, row, batched_at=batched_at)
|
|
122
|
+
except RowRejected as rejected:
|
|
123
|
+
self.reject(executor, rejected, record)
|
|
124
|
+
continue
|
|
125
|
+
if out is None:
|
|
126
|
+
continue
|
|
127
|
+
executor.metrics.rows_out += 1
|
|
128
|
+
if self.settings.mode == "record":
|
|
129
|
+
yield {"type": "RECORD", "stream": executor.plan.name, "record": out, **passed}
|
|
130
|
+
else:
|
|
131
|
+
buffers[id(executor)].append(out)
|
|
132
|
+
if self.settings.mode == "batch":
|
|
133
|
+
for executor in executors:
|
|
134
|
+
rows = buffers[id(executor)]
|
|
135
|
+
if rows:
|
|
136
|
+
self._writer(executor, uri, writers).write(rows)
|
|
137
|
+
|
|
138
|
+
def _columnar(self, encoding: dict[str, Any], executors: list[RowExecutor]) -> bool:
|
|
139
|
+
"""Parquet in, parquet out, and every output stream has vectorised columns."""
|
|
140
|
+
return (
|
|
141
|
+
encoding.get("format") == "parquet"
|
|
142
|
+
and self.settings.mode == "batch"
|
|
143
|
+
and self.settings.format == "parquet"
|
|
144
|
+
and bool(executors)
|
|
145
|
+
and all(columnar(e) for e in executors)
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
def _columnar_file( # noqa: PLR0913 -- the file and where it goes
|
|
149
|
+
self,
|
|
150
|
+
uri: str,
|
|
151
|
+
*,
|
|
152
|
+
tap_stream: str,
|
|
153
|
+
executors: list[RowExecutor],
|
|
154
|
+
passed: dict[str, Any],
|
|
155
|
+
batched_at: str,
|
|
156
|
+
writers: dict[int, Writer],
|
|
157
|
+
) -> None:
|
|
158
|
+
"""Conform a parquet file batch by batch with the columnar executor."""
|
|
159
|
+
runners = {id(e): ColumnarExecutor(e) for e in executors}
|
|
160
|
+
for table in read_tables(uri, self.settings.storage.params, self.settings.row_group_size):
|
|
161
|
+
first = self.rows.get(tap_stream, 0) + 1
|
|
162
|
+
self.rows[tap_stream] = first + table.num_rows - 1
|
|
163
|
+
for executor in executors:
|
|
164
|
+
|
|
165
|
+
def reject(
|
|
166
|
+
rejected: RowRejected, record: dict[str, Any], e: RowExecutor = executor
|
|
167
|
+
) -> None:
|
|
168
|
+
self.reject(e, rejected, record)
|
|
169
|
+
|
|
170
|
+
out = runners[id(executor)].run(
|
|
171
|
+
table, passed=passed, first_row=first, batched_at=batched_at, reject=reject
|
|
172
|
+
)
|
|
173
|
+
executor.metrics.rows_out += out.num_rows
|
|
174
|
+
if out.num_rows:
|
|
175
|
+
self._writer(executor, uri, writers).write_table(out)
|
|
176
|
+
|
|
177
|
+
def _writer(self, executor: RowExecutor, uri: str, writers: dict[int, Writer]) -> Writer:
|
|
178
|
+
writer = writers.get(id(executor))
|
|
179
|
+
if writer is None:
|
|
180
|
+
stream = executor.plan.name
|
|
181
|
+
number = self._numbers[stream] = self._numbers.get(stream, 0) + 1
|
|
182
|
+
fmt = self.settings.format
|
|
183
|
+
compression = compression_for(fmt, self.settings.compression)
|
|
184
|
+
root = self.settings.storage.root or uri.rsplit("/", 1)[0]
|
|
185
|
+
target = output_uri(root, stream, self.run_id, number, fmt=fmt, compression=compression)
|
|
186
|
+
columns = output_columns(executor.plan, metadata=executor.metadata is not None)
|
|
187
|
+
writer = writers[id(executor)] = Writer(
|
|
188
|
+
target, self.settings.storage.params, fmt=fmt, compression=compression,
|
|
189
|
+
columns=columns, row_group_size=self.settings.row_group_size,
|
|
190
|
+
) # fmt: skip
|
|
191
|
+
return writer
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""BATCH file I/O over fsspec: manifest files in, conformed files out (WBS 8.1-8.3).
|
|
2
|
+
|
|
3
|
+
- **Input.** Each manifest URI is opened with fsspec (``file://``, ``memory://``, ``s3://``
|
|
4
|
+
with the ``s3`` extra, …) using ``batch_output.storage.params``. JSONL is read line by line,
|
|
5
|
+
gzipped or plain, with fractions as exact decimals, as the Singer SDK decodes them. Parquet
|
|
6
|
+
is read in row groups of ``row_group_size`` rows, so a large file never sits in memory.
|
|
7
|
+
- **Last modified.** ``_sdc_batched_at`` is the input file's last-modified time from
|
|
8
|
+
fsspec ``info()``, or the time it was opened for stores that do not report one.
|
|
9
|
+
- **Output.** ``<root>/<stream>/<run id>-<n>.parquet`` (or ``.jsonl``/``.jsonl.gz``), where
|
|
10
|
+
root is ``batch_output.storage.root`` or the input file's directory. Parquet is written
|
|
11
|
+
with the plan's declared Arrow schema; JSONL with the RECORD path's wire values.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import datetime as dt
|
|
17
|
+
import gzip
|
|
18
|
+
import io
|
|
19
|
+
import json
|
|
20
|
+
from decimal import Decimal
|
|
21
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
22
|
+
|
|
23
|
+
import fsspec
|
|
24
|
+
import pyarrow as pa
|
|
25
|
+
import pyarrow.parquet as pq
|
|
26
|
+
|
|
27
|
+
from map_conform.batch.arrow import to_table
|
|
28
|
+
from map_conform.types.jsontext import dumps
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
32
|
+
|
|
33
|
+
from map_conform.types.canonical import CType
|
|
34
|
+
|
|
35
|
+
_COMPRESSION_DEFAULTS = {"parquet": "zstd", "jsonl": "gzip"}
|
|
36
|
+
_EXTENSIONS = {"parquet": ".parquet", "jsonl": ".jsonl"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class BatchFileError(ValueError):
|
|
40
|
+
"""A manifest file that cannot be read, or an encoding map-conform does not read."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _fs(uri: str, params: Mapping[str, Any]) -> tuple[fsspec.AbstractFileSystem, str]:
|
|
44
|
+
fs, path = fsspec.core.url_to_fs(uri, **dict(params))
|
|
45
|
+
return fs, path
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def last_modified(uri: str, params: Mapping[str, Any]) -> dt.datetime:
|
|
49
|
+
"""The file's last-modified time, in UTC (now, when the store does not say)."""
|
|
50
|
+
fs, path = _fs(uri, params)
|
|
51
|
+
try:
|
|
52
|
+
modified = fs.modified(path)
|
|
53
|
+
except (NotImplementedError, OSError, KeyError):
|
|
54
|
+
return dt.datetime.now(tz=dt.UTC)
|
|
55
|
+
return (
|
|
56
|
+
modified.replace(tzinfo=dt.UTC) if modified.tzinfo is None else modified.astimezone(dt.UTC)
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def read_rows(
|
|
61
|
+
uri: str, encoding: Mapping[str, Any], params: Mapping[str, Any], chunk: int
|
|
62
|
+
) -> Iterator[list[dict[str, Any]]]:
|
|
63
|
+
"""The file's records, in chunks of at most ``chunk`` rows.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
BatchFileError: for an unknown format or compression, or an unreadable file.
|
|
67
|
+
"""
|
|
68
|
+
fmt = encoding.get("format")
|
|
69
|
+
compression = encoding.get("compression") or "none"
|
|
70
|
+
fs, path = _fs(uri, params)
|
|
71
|
+
try:
|
|
72
|
+
if fmt == "jsonl":
|
|
73
|
+
yield from _jsonl(fs, path, compression, chunk)
|
|
74
|
+
elif fmt == "parquet":
|
|
75
|
+
with fs.open(path, "rb") as handle:
|
|
76
|
+
for batch in pq.ParquetFile(handle).iter_batches(batch_size=chunk):
|
|
77
|
+
yield batch.to_pylist()
|
|
78
|
+
else:
|
|
79
|
+
msg = f"BATCH format {fmt!r} is not supported (jsonl or parquet)"
|
|
80
|
+
raise BatchFileError(msg)
|
|
81
|
+
except (OSError, pa.ArrowException, json.JSONDecodeError) as exc:
|
|
82
|
+
msg = f"cannot read {uri}: {exc}"
|
|
83
|
+
raise BatchFileError(msg) from exc
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def read_tables(uri: str, params: Mapping[str, Any], chunk: int) -> Iterator[pa.Table]:
|
|
87
|
+
"""A parquet file's rows as Arrow tables of at most ``chunk`` rows.
|
|
88
|
+
|
|
89
|
+
Raises:
|
|
90
|
+
BatchFileError: for an unreadable file.
|
|
91
|
+
"""
|
|
92
|
+
fs, path = _fs(uri, params)
|
|
93
|
+
try:
|
|
94
|
+
with fs.open(path, "rb") as handle:
|
|
95
|
+
for batch in pq.ParquetFile(handle).iter_batches(batch_size=chunk):
|
|
96
|
+
yield pa.Table.from_batches([batch])
|
|
97
|
+
except (OSError, pa.ArrowException) as exc:
|
|
98
|
+
msg = f"cannot read {uri}: {exc}"
|
|
99
|
+
raise BatchFileError(msg) from exc
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _jsonl(
|
|
103
|
+
fs: fsspec.AbstractFileSystem, path: str, compression: str, chunk: int
|
|
104
|
+
) -> Iterator[list[dict[str, Any]]]:
|
|
105
|
+
if compression not in {"gzip", "none"}:
|
|
106
|
+
msg = f"JSONL compression {compression!r} is not supported (gzip or none)"
|
|
107
|
+
raise BatchFileError(msg)
|
|
108
|
+
with fs.open(path, "rb") as raw, _text_reader(raw, compression) as handle:
|
|
109
|
+
rows: list[dict[str, Any]] = []
|
|
110
|
+
for line in handle:
|
|
111
|
+
if line.strip():
|
|
112
|
+
rows.append(json.loads(line, parse_float=Decimal))
|
|
113
|
+
if len(rows) >= chunk:
|
|
114
|
+
yield rows
|
|
115
|
+
rows = []
|
|
116
|
+
if rows:
|
|
117
|
+
yield rows
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _text_reader(raw: Any, compression: str) -> Any: # noqa: ANN401 -- a binary file object
|
|
121
|
+
"""A text reader over a binary file, gunzipping when asked."""
|
|
122
|
+
if compression == "gzip":
|
|
123
|
+
return gzip.open(raw, "rt", encoding="utf-8")
|
|
124
|
+
return io.TextIOWrapper(raw, encoding="utf-8")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def compression_for(fmt: str, configured: str | None) -> str:
|
|
128
|
+
"""The output compression: the configured one, or the format's default."""
|
|
129
|
+
return configured or _COMPRESSION_DEFAULTS[fmt]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def output_uri( # noqa: PLR0913 -- the parts of the name
|
|
133
|
+
root: str, stream: str, run_id: str, number: int, *, fmt: str, compression: str
|
|
134
|
+
) -> str:
|
|
135
|
+
"""``<root>/<stream>/<run id>-<n>.<ext>``."""
|
|
136
|
+
extension = _EXTENSIONS[fmt] + (".gz" if fmt == "jsonl" and compression == "gzip" else "")
|
|
137
|
+
return f"{root.rstrip('/')}/{stream}/{run_id}-{number:04d}{extension}"
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class Writer:
|
|
141
|
+
"""Writes one output file, chunk by chunk."""
|
|
142
|
+
|
|
143
|
+
def __init__( # noqa: PLR0913 -- the file's whole description
|
|
144
|
+
self,
|
|
145
|
+
uri: str,
|
|
146
|
+
params: Mapping[str, Any],
|
|
147
|
+
*,
|
|
148
|
+
fmt: str,
|
|
149
|
+
compression: str,
|
|
150
|
+
columns: Sequence[tuple[str, CType, bool]],
|
|
151
|
+
row_group_size: int,
|
|
152
|
+
) -> None:
|
|
153
|
+
"""Open ``uri`` for writing, creating its directory."""
|
|
154
|
+
self.uri = uri
|
|
155
|
+
self.columns = columns
|
|
156
|
+
self.fmt = fmt
|
|
157
|
+
self.rows = 0
|
|
158
|
+
self.row_group_size = row_group_size
|
|
159
|
+
fs, path = _fs(uri, params)
|
|
160
|
+
fs.makedirs(path.rsplit("/", 1)[0], exist_ok=True)
|
|
161
|
+
self._handle = fs.open(path, "wb")
|
|
162
|
+
self._parquet: pq.ParquetWriter | None = None
|
|
163
|
+
self._text: Any = None
|
|
164
|
+
if fmt == "parquet":
|
|
165
|
+
codec = None if compression == "none" else compression
|
|
166
|
+
schema = to_table([], columns).schema
|
|
167
|
+
self._parquet = pq.ParquetWriter(self._handle, schema, compression=cast("Any", codec))
|
|
168
|
+
elif compression == "gzip":
|
|
169
|
+
self._text = gzip.open(self._handle, "wt", encoding="utf-8") # noqa: SIM115 -- close()
|
|
170
|
+
else:
|
|
171
|
+
self._text = io.TextIOWrapper(self._handle, encoding="utf-8")
|
|
172
|
+
|
|
173
|
+
def write(self, rows: Sequence[Mapping[str, Any]]) -> None:
|
|
174
|
+
"""Append conformed rows (wire values)."""
|
|
175
|
+
if not rows:
|
|
176
|
+
return
|
|
177
|
+
self.rows += len(rows)
|
|
178
|
+
if self._parquet is not None:
|
|
179
|
+
self._parquet.write_table(
|
|
180
|
+
to_table(rows, self.columns), row_group_size=self.row_group_size
|
|
181
|
+
)
|
|
182
|
+
else:
|
|
183
|
+
self._text.write("".join(dumps(dict(row), compact=True) + "\n" for row in rows))
|
|
184
|
+
|
|
185
|
+
def write_table(self, table: pa.Table) -> None:
|
|
186
|
+
"""Append a conformed Arrow table (parquet output only)."""
|
|
187
|
+
if self._parquet is None:
|
|
188
|
+
msg = "write_table is for parquet output"
|
|
189
|
+
raise TypeError(msg)
|
|
190
|
+
self.rows += table.num_rows
|
|
191
|
+
if table.num_rows:
|
|
192
|
+
self._parquet.write_table(table, row_group_size=self.row_group_size)
|
|
193
|
+
|
|
194
|
+
def close(self) -> None:
|
|
195
|
+
"""Finish the file."""
|
|
196
|
+
if self._parquet is not None:
|
|
197
|
+
self._parquet.close()
|
|
198
|
+
else:
|
|
199
|
+
self._text.close()
|
|
200
|
+
if not self._handle.closed:
|
|
201
|
+
self._handle.close()
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def delete(uri: str, params: Mapping[str, Any]) -> None:
|
|
205
|
+
"""Remove an input file."""
|
|
206
|
+
fs, path = _fs(uri, params)
|
|
207
|
+
fs.rm(path)
|