pipeloom-polars 0.2.0__tar.gz

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.
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ build/
5
+ dist/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+ .coverage
11
+ coverage.xml
12
+ htmlcov/
13
+ site/
14
+ target/
15
+ .pipeloom/
16
+ .env
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ pipeloom
2
+ Copyright 2026 Emanuel Luis
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.5
2
+ Name: pipeloom-polars
3
+ Version: 0.2.0
4
+ Summary: Polars engine for pipeloom: lazy frames, SQL and file tables.
5
+ Project-URL: Repository, https://github.com/emanuel-luis/pipeloom
6
+ Project-URL: Documentation, https://emanuel-luis.github.io/pipeloom/
7
+ Project-URL: Changelog, https://github.com/emanuel-luis/pipeloom/blob/main/CHANGELOG.md
8
+ Author-email: Emanuel Luis <emanuel.filho08@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Keywords: data-engineering,pipelines,pipeloom,polars
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: pipeloom~=0.2.0
24
+ Requires-Dist: polars<3,>=1.30
25
+ Description-Content-Type: text/markdown
26
+
27
+ # pipeloom-polars
28
+
29
+ The [Polars](https://pola.rs) engine for [pipeloom](https://github.com/emanuel-luis/pipeloom).
30
+
31
+ ```console
32
+ $ pip install "pipeloom[polars]"
33
+ ```
34
+
35
+ Select it in a target:
36
+
37
+ ```yaml
38
+ targets:
39
+ dev:
40
+ engine: {kind: polars}
41
+ catalog: {kind: filesystem, root: warehouse}
42
+ ```
43
+
44
+ - Relations are `LazyFrame`s. Python models receive `LazyFrame` inputs, or Narwhals frames with
45
+ `frame_api: narwhals`.
46
+ - SQL models and views run on `pl.SQLContext`.
47
+ - Reads `parquet`, `csv`, `json` and `ndjson` sources. Writes tables through the `filesystem`
48
+ catalog with the `append` and `overwrite` strategies, and an idempotency token makes a repeated
49
+ write a no-op.
50
+
51
+ Documentation: https://emanuel-luis.github.io/pipeloom/latest/plugins/polars/
52
+
53
+ License: Apache-2.0.
@@ -0,0 +1,27 @@
1
+ # pipeloom-polars
2
+
3
+ The [Polars](https://pola.rs) engine for [pipeloom](https://github.com/emanuel-luis/pipeloom).
4
+
5
+ ```console
6
+ $ pip install "pipeloom[polars]"
7
+ ```
8
+
9
+ Select it in a target:
10
+
11
+ ```yaml
12
+ targets:
13
+ dev:
14
+ engine: {kind: polars}
15
+ catalog: {kind: filesystem, root: warehouse}
16
+ ```
17
+
18
+ - Relations are `LazyFrame`s. Python models receive `LazyFrame` inputs, or Narwhals frames with
19
+ `frame_api: narwhals`.
20
+ - SQL models and views run on `pl.SQLContext`.
21
+ - Reads `parquet`, `csv`, `json` and `ndjson` sources. Writes tables through the `filesystem`
22
+ catalog with the `append` and `overwrite` strategies, and an idempotency token makes a repeated
23
+ write a no-op.
24
+
25
+ Documentation: https://emanuel-luis.github.io/pipeloom/latest/plugins/polars/
26
+
27
+ License: Apache-2.0.
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pipeloom-polars"
7
+ version = "0.2.0"
8
+ description = "Polars engine for pipeloom: lazy frames, SQL and file tables."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [{ name = "Emanuel Luis", email = "emanuel.filho08@gmail.com" }]
14
+ keywords = ["pipeloom", "polars", "data-engineering", "pipelines"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = ["pipeloom~=0.2.0", "polars>=1.30,<3"]
27
+
28
+ [project.urls]
29
+ Repository = "https://github.com/emanuel-luis/pipeloom"
30
+ Documentation = "https://emanuel-luis.github.io/pipeloom/"
31
+ Changelog = "https://github.com/emanuel-luis/pipeloom/blob/main/CHANGELOG.md"
32
+
33
+ [project.entry-points."pipeloom.engines"]
34
+ polars = "pipeloom_polars.spec:SPEC"
35
+
36
+ [tool.uv.sources]
37
+ pipeloom = { workspace = true }
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/pipeloom_polars"]
41
+
42
+ [tool.hatch.build.targets.sdist]
43
+ only-include = ["src", "tests", "LICENSE", "NOTICE", "README.md"]
@@ -0,0 +1 @@
1
+ """Polars engine plugin for pipeloom. Import `pipeloom_polars.spec` to read its capabilities."""
@@ -0,0 +1,181 @@
1
+ """The polars engine: lazy frames, SQL on `pl.SQLContext`, tables on the filesystem catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Mapping
6
+ from contextlib import contextmanager
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ import polars as pl
10
+
11
+ from pipeloom.builtins.filesystem import FilesystemCatalog
12
+ from pipeloom.builtins.fs_table import FsTable, ViewDefinition
13
+ from pipeloom.engine import portable
14
+ from pipeloom.engine.protocols import Catalog, EngineSession, Materializer, Reader
15
+ from pipeloom.engine.types import ReadSpec, Relation, Schema, TargetRef, WriteConfig, WriteResult
16
+ from pipeloom_polars import io
17
+ from pipeloom_polars.spec import CAPABILITIES
18
+
19
+ if TYPE_CHECKING:
20
+ from pipeloom.runtime.context import RuntimeContext
21
+
22
+ NAME = "polars"
23
+
24
+
25
+ def _rel(frame: pl.LazyFrame) -> Relation:
26
+ return Relation(frame, NAME, lazy=True)
27
+
28
+
29
+ class _Reader:
30
+ def __init__(self, session: PolarsSession, fmt: str) -> None:
31
+ self._session = session
32
+ self._fmt = fmt
33
+
34
+ def read(self, spec: ReadSpec) -> Relation:
35
+ if self._fmt == "table":
36
+ if spec.table is None:
37
+ raise ValueError("a table read needs a table")
38
+ return self._session.read_table(spec.table)
39
+ if spec.location is None:
40
+ raise ValueError(f"reading {self._fmt} needs a location")
41
+ return _rel(io.scan(self._fmt, spec.location, spec.options))
42
+
43
+
44
+ class _Materializer:
45
+ def __init__(self, session: PolarsSession, strategy: str) -> None:
46
+ self.strategy = strategy
47
+ self._session = session
48
+
49
+ def materialize(
50
+ self, rel: Relation, target: TargetRef, cfg: WriteConfig, token: str
51
+ ) -> WriteResult:
52
+ catalog = self._session.catalog
53
+ table = catalog.table(target)
54
+ replay = table.applied(token)
55
+ if replay is not None:
56
+ return replay
57
+ path = table.new_file(io.EXTENSIONS[catalog.format])
58
+ try:
59
+ df: pl.DataFrame = rel.native.collect()
60
+ io.write(df, catalog.format, path)
61
+ commit = table.commit(
62
+ mode="append" if self.strategy == "append" else "overwrite",
63
+ files=[path],
64
+ columns=portable.schema(df),
65
+ rows=df.height,
66
+ token=token,
67
+ result=WriteResult(rows_inserted=df.height, rows_written=df.height),
68
+ )
69
+ except BaseException:
70
+ table.discard([path])
71
+ raise
72
+ return commit.result
73
+
74
+
75
+ class PolarsSession:
76
+ """Thread-safe: it holds no mutable state, and a LazyFrame is immutable."""
77
+
78
+ native: Any
79
+
80
+ def __init__(self, catalog: Catalog) -> None:
81
+ if not isinstance(catalog, FilesystemCatalog):
82
+ raise TypeError(
83
+ f"the polars engine needs the filesystem catalog, not {type(catalog).__name__}"
84
+ )
85
+ self.catalog = catalog
86
+ self.native = pl
87
+
88
+ # -- reading ------------------------------------------------------------------------------
89
+
90
+ def reader(self, fmt: str) -> Reader:
91
+ if fmt != "table" and fmt not in CAPABILITIES.formats:
92
+ raise ValueError(f"polars engine cannot read format '{fmt}'")
93
+ return _Reader(self, fmt)
94
+
95
+ def read_table(self, target: TargetRef) -> Relation:
96
+ table: FsTable = self.catalog.table(target)
97
+ commit = table.current()
98
+ if commit is None:
99
+ raise FileNotFoundError(f"table '{target.relation_name}' does not exist")
100
+ if commit.kind == "view":
101
+ assert commit.view is not None
102
+ return self._run_view(commit.view)
103
+ assert commit.format is not None
104
+ return _rel(io.scan_parts(commit.format, table.files(), commit.columns))
105
+
106
+ def _run_view(self, view: ViewDefinition) -> Relation:
107
+ inputs = {a: self.reader(s.format).read(s) for a, s in view.inputs.items()}
108
+ return self.sql(view.query, inputs)
109
+
110
+ # -- writing ------------------------------------------------------------------------------
111
+
112
+ def materializer(self, strategy: str) -> Materializer:
113
+ if strategy not in CAPABILITIES.strategies:
114
+ raise ValueError(f"polars engine does not support strategy '{strategy}'")
115
+ return _Materializer(self, strategy)
116
+
117
+ def create_view(
118
+ self, target: TargetRef, query: str, inputs: Mapping[str, ReadSpec]
119
+ ) -> WriteResult:
120
+ view = ViewDefinition(query, dict(inputs))
121
+ rel = self._run_view(view) # bad SQL fails here
122
+ table = self.catalog.table(target)
123
+ current = table.current()
124
+ if current is not None and current.kind == "view" and current.view == view:
125
+ return current.result # same definition: a rerun commits nothing
126
+ commit = table.commit(
127
+ mode="view",
128
+ files=[],
129
+ columns=portable.schema(rel.native),
130
+ rows=None,
131
+ token="view",
132
+ result=WriteResult(),
133
+ view=view,
134
+ )
135
+ return commit.result
136
+
137
+ # -- relations ----------------------------------------------------------------------------
138
+
139
+ def sql(self, query: str, inputs: Mapping[str, Relation]) -> Relation:
140
+ # A fresh context per query: aliases never leak into another one.
141
+ ctx = pl.SQLContext(frames={a: r.native for a, r in inputs.items()}, eager=False)
142
+ frame = ctx.execute(query)
143
+ frame.collect_schema() # resolve the plan now: an unknown table or column fails here
144
+ return _rel(frame)
145
+
146
+ def relation(self, native: Any) -> Relation:
147
+ if isinstance(native, pl.DataFrame):
148
+ native = native.lazy()
149
+ if not isinstance(native, pl.LazyFrame):
150
+ raise TypeError(f"the polars engine takes a LazyFrame, not {type(native).__name__}")
151
+ return _rel(native)
152
+
153
+ def persist(self, rel: Relation) -> Relation:
154
+ return _rel(rel.native.collect().lazy())
155
+
156
+ def schema(self, rel: Relation) -> Schema:
157
+ return portable.schema(rel.native)
158
+
159
+ def count(self, rel: Relation) -> int:
160
+ return portable.count(rel.native)
161
+
162
+ def filter_since(self, rel: Relation, column: str, lower: Any) -> Relation:
163
+ return _rel(portable.filter_since(rel.native, column, lower))
164
+
165
+ def max_value(self, rel: Relation, column: str) -> Any:
166
+ return portable.max_value(rel.native, column)
167
+
168
+ def cancel(self, unit_id: str) -> None:
169
+ return None
170
+
171
+
172
+ class PolarsEngine:
173
+ name = NAME
174
+ capabilities = CAPABILITIES
175
+
176
+ def __init__(self) -> None:
177
+ self.version = pl.__version__
178
+
179
+ @contextmanager
180
+ def session(self, ctx: RuntimeContext, *, catalog: Catalog) -> Iterator[EngineSession]:
181
+ yield PolarsSession(catalog)
@@ -0,0 +1,107 @@
1
+ """Reading and writing files, and the logical-to-polars type mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Mapping, Sequence
7
+ from pathlib import Path
8
+ from typing import Any, Final
9
+
10
+ import polars as pl
11
+
12
+ from pipeloom.engine.types import Schema
13
+
14
+ EXTENSIONS: Final = {"parquet": "parquet", "csv": "csv", "ndjson": "ndjson"}
15
+ """Part file extension by catalog format."""
16
+
17
+ _SIMPLE: dict[str, Any] = {
18
+ "int8": pl.Int8,
19
+ "int16": pl.Int16,
20
+ "int32": pl.Int32,
21
+ "int64": pl.Int64,
22
+ "int128": pl.Int128,
23
+ "uint8": pl.UInt8,
24
+ "uint16": pl.UInt16,
25
+ "uint32": pl.UInt32,
26
+ "uint64": pl.UInt64,
27
+ "float32": pl.Float32,
28
+ "float64": pl.Float64,
29
+ "string": pl.String,
30
+ "boolean": pl.Boolean,
31
+ "date": pl.Date,
32
+ "time": pl.Time,
33
+ "binary": pl.Binary,
34
+ }
35
+ if hasattr(pl, "UInt128"): # polars 1.34 and later; the floor is 1.30
36
+ _SIMPLE["uint128"] = pl.UInt128
37
+ _TIMESTAMP = re.compile(r"timestamp\[(ms|us|ns)(?:, ([^\]]+))?\]")
38
+ _DECIMAL = re.compile(r"decimal\((\d+),(\d+)\)")
39
+
40
+
41
+ def polars_dtype(logical: str) -> Any | None:
42
+ """The polars dtype of a logical type, or None for one this engine cannot name."""
43
+ simple = _SIMPLE.get(logical)
44
+ if simple is not None:
45
+ return simple
46
+ ts = _TIMESTAMP.fullmatch(logical)
47
+ if ts:
48
+ return pl.Datetime(ts.group(1), ts.group(2)) # type: ignore[arg-type]
49
+ dec = _DECIMAL.fullmatch(logical)
50
+ if dec:
51
+ return pl.Decimal(int(dec.group(1)), int(dec.group(2)))
52
+ return None
53
+
54
+
55
+ def typed_columns(columns: Schema) -> dict[str, Any]:
56
+ """The polars dtype of every column this engine can name; the others are left out."""
57
+ out: dict[str, Any] = {}
58
+ for col in columns:
59
+ dtype = polars_dtype(col.dtype)
60
+ if dtype is not None:
61
+ out[col.name] = dtype
62
+ return out
63
+
64
+
65
+ def scan(fmt: str, location: str, options: Mapping[str, Any]) -> pl.LazyFrame:
66
+ """A lazy frame over a source file, a directory or a glob."""
67
+ if fmt == "parquet":
68
+ return pl.scan_parquet(location, **options)
69
+ if fmt == "csv":
70
+ return pl.scan_csv(location, **options)
71
+ if fmt == "ndjson":
72
+ return pl.scan_ndjson(location, **options)
73
+ if fmt == "json":
74
+ return pl.read_json(location, **options).lazy()
75
+ raise ValueError(f"polars engine cannot read format '{fmt}'")
76
+
77
+
78
+ def scan_parts(fmt: str, files: Sequence[Path], schema: Schema) -> pl.LazyFrame:
79
+ """A lazy frame over the committed part files of a table.
80
+
81
+ csv and ndjson lose type information, so the stored logical types are applied column by
82
+ column; a column this engine cannot name keeps what polars infers.
83
+ """
84
+ paths = [str(f) for f in files]
85
+ if fmt == "parquet":
86
+ return pl.scan_parquet(paths)
87
+ known = typed_columns(schema)
88
+ if fmt == "csv":
89
+ return pl.concat([pl.scan_csv(p, schema_overrides=known) for p in paths])
90
+ if fmt == "ndjson":
91
+ # A decimal is a JSON number there: read it as text and cast, or the schema fails.
92
+ decimals = {n: t for n, t in known.items() if isinstance(t, pl.Decimal)}
93
+ read = {n: pl.String if n in decimals else t for n, t in known.items()}
94
+ frames = [pl.scan_ndjson(p, schema_overrides=read) for p in paths]
95
+ return pl.concat(frames).with_columns(*(pl.col(n).cast(t) for n, t in decimals.items()))
96
+ raise ValueError(f"cannot read a table stored as '{fmt}'")
97
+
98
+
99
+ def write(df: pl.DataFrame, fmt: str, path: Path) -> None:
100
+ if fmt == "parquet":
101
+ df.write_parquet(path)
102
+ elif fmt == "csv":
103
+ df.write_csv(path)
104
+ elif fmt == "ndjson":
105
+ df.write_ndjson(path)
106
+ else:
107
+ raise ValueError(f"cannot write format '{fmt}'")
File without changes
@@ -0,0 +1,43 @@
1
+ """The plugin spec. It imports no dataframe library: the engine module loads on first use."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from pipeloom.engine.protocols import Engine
8
+ from pipeloom.engine.types import EngineCapabilities
9
+ from pipeloom.plugins import API_VERSION, OptionsModel, PluginSpec
10
+
11
+ CAPABILITIES = EngineCapabilities(
12
+ formats=frozenset({"parquet", "csv", "json", "ndjson"}),
13
+ strategies=frozenset({"append", "overwrite"}),
14
+ materializations=frozenset({"table", "view", "ephemeral"}),
15
+ sql_models=True,
16
+ views=True,
17
+ idempotent_writes=True,
18
+ cancel=False,
19
+ bytes_metrics=True,
20
+ portable=True,
21
+ )
22
+
23
+
24
+ class PolarsOptions(OptionsModel):
25
+ """The polars engine has no options."""
26
+
27
+
28
+ def _build(opts: Any) -> Engine:
29
+ from pipeloom_polars.engine import PolarsEngine
30
+
31
+ return PolarsEngine()
32
+
33
+
34
+ SPEC: PluginSpec[Engine] = PluginSpec(
35
+ "polars",
36
+ "polars",
37
+ "engines",
38
+ API_VERSION,
39
+ _build,
40
+ PolarsOptions,
41
+ capabilities=CAPABILITIES,
42
+ description="Polars lazy frames; SQL through pl.SQLContext; tables on the filesystem catalog.",
43
+ )
@@ -0,0 +1,13 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from pathlib import Path
5
+
6
+
7
+ def write_files(root: Path, files: Mapping[str, str]) -> Path:
8
+ """Write text files under `root` with LF endings."""
9
+ for rel, content in files.items():
10
+ target = root / rel
11
+ target.parent.mkdir(parents=True, exist_ok=True)
12
+ target.write_bytes(content.encode("utf-8"))
13
+ return root
@@ -0,0 +1,64 @@
1
+ """The polars engine passes the engine contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping, Sequence
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import polars as pl
10
+ import pytest
11
+
12
+ from pipeloom.builtins.filesystem import FilesystemCatalog
13
+ from pipeloom.engine.protocols import EngineSession
14
+ from pipeloom.engine.types import Relation, Schema
15
+ from pipeloom.testing.contract.engine import EngineContract, EngineHarness
16
+ from pipeloom_polars import io
17
+ from pipeloom_polars.engine import PolarsEngine
18
+
19
+ Rows = Sequence[Mapping[str, Any]]
20
+
21
+
22
+ def _frame(rows: Rows, schema: Schema) -> pl.DataFrame:
23
+ dtypes = {c.name: io.polars_dtype(c.dtype) for c in schema}
24
+ return pl.DataFrame([dict(r) for r in rows], schema=dtypes)
25
+
26
+
27
+ def _boom(df: pl.DataFrame) -> pl.DataFrame:
28
+ raise RuntimeError("cannot produce rows")
29
+
30
+
31
+ def harness(tmp_path: Path) -> EngineHarness:
32
+ def write_source(fmt: str, path: Path, rows: Rows, schema: Schema) -> None:
33
+ df = _frame(rows, schema)
34
+ if fmt == "parquet":
35
+ df.write_parquet(path)
36
+ elif fmt == "csv":
37
+ df.write_csv(path)
38
+ elif fmt == "ndjson":
39
+ df.write_ndjson(path)
40
+ else:
41
+ path.write_text(df.write_json(), encoding="utf-8")
42
+
43
+ def to_rows(native: Any) -> list[dict[str, Any]]:
44
+ df = native.collect() if isinstance(native, pl.LazyFrame) else native
45
+ return list(df.to_dicts())
46
+
47
+ def failing(session: EngineSession) -> Relation:
48
+ return session.relation(pl.LazyFrame({"a": [1]}).map_batches(_boom))
49
+
50
+ return EngineHarness(
51
+ engine=PolarsEngine(),
52
+ catalog=FilesystemCatalog(tmp_path / "wh"),
53
+ make_native=lambda rows, schema: _frame(rows, schema).lazy(),
54
+ to_rows=to_rows,
55
+ write_source=write_source,
56
+ failing_relation=failing,
57
+ settings_snapshot=lambda: pl.Config.state(),
58
+ )
59
+
60
+
61
+ class TestPolarsEngine(EngineContract):
62
+ @pytest.fixture
63
+ def engine_factory(self) -> Callable[[Path], EngineHarness]:
64
+ return harness
@@ -0,0 +1,102 @@
1
+ """Polars engine details beyond the contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime
6
+ from decimal import Decimal
7
+ from pathlib import Path
8
+
9
+ import polars as pl
10
+ import pytest
11
+
12
+ from pipeloom.builtins.filesystem import FilesystemCatalog
13
+ from pipeloom.engine.types import ReadSpec, TargetRef, WriteConfig
14
+ from pipeloom.platform import Identity
15
+ from pipeloom.runtime.context import RuntimeContext
16
+ from pipeloom.testing.clock import FakeClock
17
+ from pipeloom.testing.memory import MemoryCatalog
18
+ from pipeloom_polars.engine import PolarsEngine
19
+
20
+ T = TargetRef(None, "main", "t")
21
+
22
+
23
+ def ctx(tmp_path: Path) -> RuntimeContext:
24
+ return RuntimeContext("r", "i", "p", "t", tmp_path, FakeClock(), Identity("u", "h"), {})
25
+
26
+
27
+ @pytest.mark.parametrize("fmt", ["parquet", "csv", "ndjson"])
28
+ def test_tables_round_trip_in_every_catalog_format(tmp_path: Path, fmt: str) -> None:
29
+ catalog = FilesystemCatalog(tmp_path / "wh", format=fmt)
30
+ with PolarsEngine().session(ctx(tmp_path), catalog=catalog) as s:
31
+ catalog.ensure_namespace(T.namespace)
32
+ rel = s.relation(pl.DataFrame({"id": [1, 2], "label": ["a", None]}))
33
+ s.materializer("overwrite").materialize(rel, T, WriteConfig("overwrite"), "r:1")
34
+ out = s.reader("table").read(ReadSpec("table", table=T))
35
+ assert out.native.collect().sort("id").to_dicts() == [
36
+ {"id": 1, "label": "a"},
37
+ {"id": 2, "label": None},
38
+ ]
39
+ assert [c.dtype for c in s.schema(out)] == ["int64", "string"]
40
+ assert len(list((tmp_path / "wh" / "main" / "t").glob(f"part-*.{fmt}"))) == 1
41
+
42
+
43
+ def test_a_replayed_token_keeps_the_commit(tmp_path: Path) -> None:
44
+ catalog = FilesystemCatalog(tmp_path / "wh")
45
+ with PolarsEngine().session(ctx(tmp_path), catalog=catalog) as s:
46
+ catalog.ensure_namespace(T.namespace)
47
+ rel = s.relation(pl.DataFrame({"id": [1]}))
48
+ mat = s.materializer("append")
49
+ first = mat.materialize(rel, T, WriteConfig("append"), "r:1")
50
+ before = sorted(p.name for p in (tmp_path / "wh" / "main" / "t").iterdir())
51
+ assert mat.materialize(rel, T, WriteConfig("append"), "r:1") == first
52
+ assert sorted(p.name for p in (tmp_path / "wh" / "main" / "t").iterdir()) == before
53
+ assert first.rows_written == 1 and first.bytes_written and first.target_version == 1
54
+
55
+
56
+ def test_the_session_needs_the_filesystem_catalog(tmp_path: Path) -> None:
57
+ with (
58
+ pytest.raises(TypeError, match="filesystem catalog"),
59
+ PolarsEngine().session(ctx(tmp_path), catalog=MemoryCatalog()),
60
+ ):
61
+ pass
62
+
63
+
64
+ def test_unsupported_format_and_strategy(tmp_path: Path) -> None:
65
+ catalog = FilesystemCatalog(tmp_path / "wh")
66
+ with PolarsEngine().session(ctx(tmp_path), catalog=catalog) as s:
67
+ with pytest.raises(ValueError, match="format"):
68
+ s.reader("orc")
69
+ with pytest.raises(ValueError, match="strategy"):
70
+ s.materializer("merge")
71
+
72
+
73
+ def test_a_missing_table_raises(tmp_path: Path) -> None:
74
+ catalog = FilesystemCatalog(tmp_path / "wh")
75
+ with (
76
+ PolarsEngine().session(ctx(tmp_path), catalog=catalog) as s,
77
+ pytest.raises(FileNotFoundError),
78
+ ):
79
+ s.reader("table").read(ReadSpec("table", table=T))
80
+
81
+
82
+ @pytest.mark.parametrize("fmt", ["csv", "ndjson"])
83
+ def test_text_formats_keep_types_per_column(tmp_path: Path, fmt: str) -> None:
84
+ df = pl.DataFrame(
85
+ {
86
+ "d": [date(2024, 1, 2), None],
87
+ "ts": pl.Series([datetime(2024, 1, 2, 3, 4, 5), None]).cast(pl.Datetime("us", "UTC")),
88
+ "n": pl.Series([Decimal("12.34"), None]).cast(pl.Decimal(18, 2)),
89
+ "s": ["007", None],
90
+ "i": [1, None],
91
+ "tags": [[1, 2], [3]], # a type the csv format cannot hold and the engine cannot name
92
+ }
93
+ )
94
+ if fmt == "csv":
95
+ df = df.drop("tags")
96
+ catalog = FilesystemCatalog(tmp_path / "wh", format=fmt)
97
+ with PolarsEngine().session(ctx(tmp_path), catalog=catalog) as s:
98
+ catalog.ensure_namespace(T.namespace)
99
+ s.materializer("overwrite").materialize(s.relation(df), T, WriteConfig("overwrite"), "r:1")
100
+ back = s.reader("table").read(ReadSpec("table", table=T)).native.collect()
101
+ assert back.schema == df.schema
102
+ assert back.to_dicts() == df.to_dicts()
@@ -0,0 +1,99 @@
1
+ """A shop-style project end to end on polars, with both executors.
2
+
3
+ The project is `tests/fixtures/smoke`: csv sources, SQL and Python models (one on Narwhals
4
+ frames), an ephemeral model, an append table and a view, on the filesystem catalog and json state.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import shutil
11
+ from datetime import UTC, datetime, timedelta
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import polars as pl
16
+ import pytest
17
+
18
+ from pipeloom.api import Project, ProjectOptions
19
+ from pipeloom.builtins.fs_table import FsTable
20
+ from pipeloom.events.bus import EventBus
21
+ from pipeloom.runtime.run import RunOptions, RunOutcome
22
+ from pipeloom.testing.clock import FakeClock
23
+ from pipeloom.testing.recording import RecordingSink
24
+
25
+ SMOKE = Path(__file__).resolve().parents[3] / "tests" / "fixtures" / "smoke"
26
+
27
+
28
+ def project(tmp_path: Path, boundary: str) -> Path:
29
+ shutil.copytree(
30
+ SMOKE, tmp_path, ignore=shutil.ignore_patterns("target", ".pipeloom"), dirs_exist_ok=True
31
+ )
32
+ yml = tmp_path / "pipeloom.yml"
33
+ text = yml.read_text(encoding="utf-8").replace(
34
+ "python_paths:", f"boundary: {boundary}\npython_paths:"
35
+ )
36
+ yml.write_text(text, encoding="utf-8", newline="\n")
37
+ return tmp_path
38
+
39
+
40
+ def run(root: Path, run_id: str) -> tuple[RunOutcome, RecordingSink]:
41
+ clock = FakeClock(datetime(2026, 1, 1, tzinfo=UTC), step=timedelta(0))
42
+ sink = RecordingSink()
43
+ proj = Project(
44
+ ProjectOptions(project_dir=root, target="polars", env={"PIPELOOM_USER": "tester"}),
45
+ clock=clock,
46
+ invocation_id="inv",
47
+ )
48
+ with EventBus([(sink, 5)], clock=clock, invocation_id="inv") as bus:
49
+ return proj.run(RunOptions(run_id=run_id, workers=2), bus), sink
50
+
51
+
52
+ def table(root: Path, name: str) -> list[dict[str, Any]]:
53
+ t = FsTable(root / "target" / "warehouse" / "main" / name, clock=FakeClock())
54
+ return pl.scan_parquet([str(f) for f in t.files()]).collect().sort(pl.all()).to_dicts()
55
+
56
+
57
+ def snapshot(root: Path) -> dict[str, bytes]:
58
+ wh = root / "target" / "warehouse"
59
+ return {
60
+ p.relative_to(wh).as_posix(): p.read_bytes() for p in sorted(wh.rglob("*")) if p.is_file()
61
+ }
62
+
63
+
64
+ @pytest.mark.parametrize(("boundary", "executor"), [("process", "thread"), ("task", "process")])
65
+ def test_shop_runs_and_a_rerun_with_the_same_run_id_writes_nothing(
66
+ tmp_path: Path, boundary: str, executor: str
67
+ ) -> None:
68
+ root = project(tmp_path, boundary)
69
+ outcome, sink = run(root, "r1")
70
+ assert (outcome.status, outcome.exit_code) == ("succeeded", 0), outcome.diagnostics
71
+ doc = json.loads((root / "target" / "runs" / "r1" / "run_results.json").read_bytes())
72
+ assert {r["executor"] for r in doc["results"]} == {executor}
73
+ assert {r["engine"] for r in doc["results"]} == {"polars"}
74
+ assert table(root, "stg_customers") == [
75
+ {"id": 1, "email": "a@x.com"},
76
+ {"id": 2, "email": "b@x.com"},
77
+ ]
78
+ assert table(root, "fct_orders") == [
79
+ {"id": 10, "customer_id": 1, "email": "a@x.com", "amount": 5.0},
80
+ {"id": 11, "customer_id": 2, "email": "b@x.com", "amount": 7.5},
81
+ {"id": 12, "customer_id": 1, "email": "a@x.com", "amount": 2.5},
82
+ ]
83
+ assert table(root, "dim_customers") == [
84
+ {"customer_id": 1, "email": "a@x.com"},
85
+ {"customer_id": 2, "email": "b@x.com"},
86
+ ]
87
+ assert table(root, "rpt_revenue") == [
88
+ {"customer_id": 1, "revenue": 7.5},
89
+ {"customer_id": 2, "revenue": 7.5},
90
+ ]
91
+ view = FsTable(root / "target" / "warehouse" / "main" / "v_big_customers", clock=FakeClock())
92
+ commit = view.current()
93
+ assert commit is not None and commit.kind == "view" and commit.files == ()
94
+ assert not [e for e in sink.events if e.type == "unit.failed"]
95
+
96
+ before = snapshot(root)
97
+ again, _ = run(root, "r1")
98
+ assert again.exit_code == 0
99
+ assert snapshot(root) == before # token replay: no new part file, commits untouched
@@ -0,0 +1,23 @@
1
+ """The spec module is readable without importing polars."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ import sys
7
+
8
+ CODE = """
9
+ import sys
10
+ import pipeloom_polars.spec as spec
11
+ assert spec.SPEC.capabilities.portable
12
+ assert "polars" not in sys.modules, "polars was imported"
13
+ assert "pipeloom_polars.engine" not in sys.modules
14
+ print("ok")
15
+ """
16
+
17
+
18
+ def test_spec_import_does_not_import_polars() -> None:
19
+ proc = subprocess.run(
20
+ [sys.executable, "-I", "-c", CODE], capture_output=True, text=True, check=False
21
+ )
22
+ assert proc.returncode == 0, proc.stderr
23
+ assert proc.stdout.strip() == "ok"