pipeloom-pandas 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.
- pipeloom_pandas-0.2.0/.gitignore +16 -0
- pipeloom_pandas-0.2.0/LICENSE +202 -0
- pipeloom_pandas-0.2.0/NOTICE +2 -0
- pipeloom_pandas-0.2.0/PKG-INFO +54 -0
- pipeloom_pandas-0.2.0/README.md +27 -0
- pipeloom_pandas-0.2.0/pyproject.toml +43 -0
- pipeloom_pandas-0.2.0/src/pipeloom_pandas/__init__.py +1 -0
- pipeloom_pandas-0.2.0/src/pipeloom_pandas/engine.py +154 -0
- pipeloom_pandas-0.2.0/src/pipeloom_pandas/io.py +120 -0
- pipeloom_pandas-0.2.0/src/pipeloom_pandas/py.typed +0 -0
- pipeloom_pandas-0.2.0/src/pipeloom_pandas/spec.py +43 -0
- pipeloom_pandas-0.2.0/tests/test_contract.py +61 -0
- pipeloom_pandas-0.2.0/tests/test_engine.py +154 -0
- pipeloom_pandas-0.2.0/tests/test_shop_e2e.py +97 -0
- pipeloom_pandas-0.2.0/tests/test_spec_import.py +25 -0
|
@@ -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,54 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pipeloom-pandas
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: pandas engine for pipeloom: eager DataFrames 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,pandas,pipelines,pipeloom
|
|
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: pandas<4,>=2.3.3
|
|
24
|
+
Requires-Dist: pipeloom~=0.2.0
|
|
25
|
+
Requires-Dist: pyarrow>=22
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# pipeloom-pandas
|
|
29
|
+
|
|
30
|
+
The [pandas](https://pandas.pydata.org) engine for [pipeloom](https://github.com/emanuel-luis/pipeloom).
|
|
31
|
+
|
|
32
|
+
```console
|
|
33
|
+
$ pip install "pipeloom[pandas]"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Select it in a target:
|
|
37
|
+
|
|
38
|
+
```yaml
|
|
39
|
+
targets:
|
|
40
|
+
dev:
|
|
41
|
+
engine: {kind: pandas}
|
|
42
|
+
catalog: {kind: filesystem, root: warehouse}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
- Relations are eager `DataFrame`s. Python models receive `DataFrame` inputs, or Narwhals frames
|
|
46
|
+
with `frame_api: narwhals`.
|
|
47
|
+
- No SQL models and no views in 0.2: validation rejects them (PLC502, PLC507).
|
|
48
|
+
- Reads `parquet`, `csv`, `json` and `ndjson` sources. Writes tables through the `filesystem`
|
|
49
|
+
catalog with the `append` and `overwrite` strategies, and an idempotency token makes a repeated
|
|
50
|
+
write a no-op.
|
|
51
|
+
|
|
52
|
+
Documentation: https://emanuel-luis.github.io/pipeloom/latest/plugins/pandas/
|
|
53
|
+
|
|
54
|
+
License: Apache-2.0.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# pipeloom-pandas
|
|
2
|
+
|
|
3
|
+
The [pandas](https://pandas.pydata.org) engine for [pipeloom](https://github.com/emanuel-luis/pipeloom).
|
|
4
|
+
|
|
5
|
+
```console
|
|
6
|
+
$ pip install "pipeloom[pandas]"
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Select it in a target:
|
|
10
|
+
|
|
11
|
+
```yaml
|
|
12
|
+
targets:
|
|
13
|
+
dev:
|
|
14
|
+
engine: {kind: pandas}
|
|
15
|
+
catalog: {kind: filesystem, root: warehouse}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- Relations are eager `DataFrame`s. Python models receive `DataFrame` inputs, or Narwhals frames
|
|
19
|
+
with `frame_api: narwhals`.
|
|
20
|
+
- No SQL models and no views in 0.2: validation rejects them (PLC502, PLC507).
|
|
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/pandas/
|
|
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-pandas"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "pandas engine for pipeloom: eager DataFrames 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", "pandas", "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", "pandas>=2.3.3,<4", "pyarrow>=22"]
|
|
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
|
+
pandas = "pipeloom_pandas.spec:SPEC"
|
|
35
|
+
|
|
36
|
+
[tool.uv.sources]
|
|
37
|
+
pipeloom = { workspace = true }
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/pipeloom_pandas"]
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.sdist]
|
|
43
|
+
only-include = ["src", "tests", "LICENSE", "NOTICE", "README.md"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""pandas engine plugin for pipeloom. Import `pipeloom_pandas.spec` to read its capabilities."""
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""The pandas engine: eager DataFrames, tables on the filesystem catalog. No SQL in 0.2."""
|
|
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 pandas as pd
|
|
10
|
+
|
|
11
|
+
from pipeloom.builtins.filesystem import FilesystemCatalog
|
|
12
|
+
from pipeloom.builtins.fs_table import FsTable
|
|
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_pandas import io
|
|
17
|
+
from pipeloom_pandas.spec import CAPABILITIES
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from pipeloom.runtime.context import RuntimeContext
|
|
21
|
+
|
|
22
|
+
NAME = "pandas"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _rel(frame: pd.DataFrame) -> Relation:
|
|
26
|
+
return Relation(frame, NAME, lazy=False)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _Reader:
|
|
30
|
+
def __init__(self, session: PandasSession, 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.read(self._fmt, spec.location, spec.options))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _Materializer:
|
|
45
|
+
def __init__(self, session: PandasSession, 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: pd.DataFrame = rel.native
|
|
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=len(df),
|
|
66
|
+
token=token,
|
|
67
|
+
result=WriteResult(rows_inserted=len(df), rows_written=len(df)),
|
|
68
|
+
)
|
|
69
|
+
except BaseException:
|
|
70
|
+
table.discard([path])
|
|
71
|
+
raise
|
|
72
|
+
return commit.result
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class PandasSession:
|
|
76
|
+
"""Thread-safe: it holds no mutable state. A model must not mutate its inputs in place."""
|
|
77
|
+
|
|
78
|
+
native: Any
|
|
79
|
+
|
|
80
|
+
def __init__(self, catalog: Catalog) -> None:
|
|
81
|
+
if not isinstance(catalog, FilesystemCatalog):
|
|
82
|
+
raise TypeError(
|
|
83
|
+
f"the pandas engine needs the filesystem catalog, not {type(catalog).__name__}"
|
|
84
|
+
)
|
|
85
|
+
self.catalog = catalog
|
|
86
|
+
self.native = pd
|
|
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"pandas 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" or commit.format is None:
|
|
101
|
+
raise ValueError(f"'{target.relation_name}' is a view; the pandas engine has none")
|
|
102
|
+
return _rel(io.read_parts(commit.format, table.files(), commit.columns))
|
|
103
|
+
|
|
104
|
+
# -- writing ------------------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
def materializer(self, strategy: str) -> Materializer:
|
|
107
|
+
if strategy not in CAPABILITIES.strategies:
|
|
108
|
+
raise ValueError(f"pandas engine does not support strategy '{strategy}'")
|
|
109
|
+
return _Materializer(self, strategy)
|
|
110
|
+
|
|
111
|
+
def create_view(
|
|
112
|
+
self, target: TargetRef, query: str, inputs: Mapping[str, ReadSpec]
|
|
113
|
+
) -> WriteResult:
|
|
114
|
+
raise NotImplementedError("the pandas engine has no views")
|
|
115
|
+
|
|
116
|
+
# -- relations ----------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
def sql(self, query: str, inputs: Mapping[str, Relation]) -> Relation:
|
|
119
|
+
raise NotImplementedError("the pandas engine has no SQL in 0.2")
|
|
120
|
+
|
|
121
|
+
def relation(self, native: Any) -> Relation:
|
|
122
|
+
if not isinstance(native, pd.DataFrame):
|
|
123
|
+
raise TypeError(f"the pandas engine takes a DataFrame, not {type(native).__name__}")
|
|
124
|
+
return _rel(native)
|
|
125
|
+
|
|
126
|
+
def persist(self, rel: Relation) -> Relation:
|
|
127
|
+
return rel # already in memory
|
|
128
|
+
|
|
129
|
+
def schema(self, rel: Relation) -> Schema:
|
|
130
|
+
return portable.schema(rel.native)
|
|
131
|
+
|
|
132
|
+
def count(self, rel: Relation) -> int:
|
|
133
|
+
return portable.count(rel.native)
|
|
134
|
+
|
|
135
|
+
def filter_since(self, rel: Relation, column: str, lower: Any) -> Relation:
|
|
136
|
+
return _rel(portable.filter_since(rel.native, column, lower))
|
|
137
|
+
|
|
138
|
+
def max_value(self, rel: Relation, column: str) -> Any:
|
|
139
|
+
return portable.max_value(rel.native, column)
|
|
140
|
+
|
|
141
|
+
def cancel(self, unit_id: str) -> None:
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class PandasEngine:
|
|
146
|
+
name = NAME
|
|
147
|
+
capabilities = CAPABILITIES
|
|
148
|
+
|
|
149
|
+
def __init__(self) -> None:
|
|
150
|
+
self.version = pd.__version__
|
|
151
|
+
|
|
152
|
+
@contextmanager
|
|
153
|
+
def session(self, ctx: RuntimeContext, *, catalog: Catalog) -> Iterator[EngineSession]:
|
|
154
|
+
yield PandasSession(catalog)
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Reading and writing files, and the logical-to-Arrow type mapping."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import glob
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Final
|
|
10
|
+
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import pyarrow as pa
|
|
13
|
+
|
|
14
|
+
from pipeloom.engine.types import Schema
|
|
15
|
+
|
|
16
|
+
EXTENSIONS: Final = {"parquet": "parquet", "csv": "csv", "ndjson": "ndjson"}
|
|
17
|
+
"""Part file extension by catalog format."""
|
|
18
|
+
|
|
19
|
+
_SIMPLE: Final[Mapping[str, Any]] = {
|
|
20
|
+
"int8": pa.int8(),
|
|
21
|
+
"int16": pa.int16(),
|
|
22
|
+
"int32": pa.int32(),
|
|
23
|
+
"int64": pa.int64(),
|
|
24
|
+
"uint8": pa.uint8(),
|
|
25
|
+
"uint16": pa.uint16(),
|
|
26
|
+
"uint32": pa.uint32(),
|
|
27
|
+
"uint64": pa.uint64(),
|
|
28
|
+
"float32": pa.float32(),
|
|
29
|
+
"float64": pa.float64(),
|
|
30
|
+
"string": pa.string(),
|
|
31
|
+
"boolean": pa.bool_(),
|
|
32
|
+
"date": pa.date32(),
|
|
33
|
+
"time": pa.time64("us"),
|
|
34
|
+
"binary": pa.binary(),
|
|
35
|
+
}
|
|
36
|
+
_TIMESTAMP = re.compile(r"timestamp\[(ms|us|ns)(?:, ([^\]]+))?\]")
|
|
37
|
+
_DECIMAL = re.compile(r"decimal\((\d+),(\d+)\)")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def arrow_type(logical: str) -> Any | None:
|
|
41
|
+
"""The Arrow type of a logical type, or None for one this engine cannot name."""
|
|
42
|
+
simple = _SIMPLE.get(logical)
|
|
43
|
+
if simple is not None:
|
|
44
|
+
return simple
|
|
45
|
+
ts = _TIMESTAMP.fullmatch(logical)
|
|
46
|
+
if ts:
|
|
47
|
+
return pa.timestamp(ts.group(1), tz=ts.group(2))
|
|
48
|
+
dec = _DECIMAL.fullmatch(logical)
|
|
49
|
+
if dec:
|
|
50
|
+
return pa.decimal128(int(dec.group(1)), int(dec.group(2)))
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _concat(frames: list[pd.DataFrame]) -> pd.DataFrame:
|
|
55
|
+
return frames[0] if len(frames) == 1 else pd.concat(frames, ignore_index=True)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _files(location: str) -> list[str]:
|
|
59
|
+
if not any(ch in location for ch in "*?["):
|
|
60
|
+
return [location]
|
|
61
|
+
found = sorted(glob.glob(location))
|
|
62
|
+
if not found:
|
|
63
|
+
raise FileNotFoundError(f"no file matches '{location}'")
|
|
64
|
+
return found
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _read_one(
|
|
68
|
+
fmt: str, path: str, options: Mapping[str, Any], text_columns: Sequence[str] = ()
|
|
69
|
+
) -> pd.DataFrame:
|
|
70
|
+
# Arrow-backed columns keep nulls in integer columns and keep the logical types.
|
|
71
|
+
kw: dict[str, Any] = {"dtype_backend": "pyarrow", **options}
|
|
72
|
+
if fmt == "parquet":
|
|
73
|
+
return pd.read_parquet(path, **kw)
|
|
74
|
+
if fmt == "csv":
|
|
75
|
+
# Strings are read as strings: inferring first would turn "007" into 7.
|
|
76
|
+
return pd.read_csv(path, **{"dtype": dict.fromkeys(text_columns, "string[pyarrow]"), **kw})
|
|
77
|
+
if fmt == "ndjson":
|
|
78
|
+
return pd.read_json(path, lines=True, **{"dtype": False, **kw})
|
|
79
|
+
if fmt == "json":
|
|
80
|
+
return pd.read_json(path, **{"dtype": False, **kw})
|
|
81
|
+
raise ValueError(f"pandas engine cannot read format '{fmt}'")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def read(fmt: str, location: str, options: Mapping[str, Any]) -> pd.DataFrame:
|
|
85
|
+
"""A DataFrame over a source file or a glob."""
|
|
86
|
+
return _concat([_read_one(fmt, p, options) for p in _files(location)])
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def read_parts(fmt: str, files: Sequence[Path], schema: Schema) -> pd.DataFrame:
|
|
90
|
+
"""The committed part files of a table, concatenated, with the stored logical types."""
|
|
91
|
+
frames = []
|
|
92
|
+
for path in files:
|
|
93
|
+
text = [c.name for c in schema if c.dtype == "string"]
|
|
94
|
+
df = _read_one(fmt, str(path), {}, text)
|
|
95
|
+
if fmt != "parquet": # csv and ndjson lose the types; parquet keeps them
|
|
96
|
+
for col in schema:
|
|
97
|
+
dtype = arrow_type(col.dtype)
|
|
98
|
+
if dtype is None or col.name not in df.columns:
|
|
99
|
+
continue # an unnamed type keeps what the reader inferred
|
|
100
|
+
series = df[col.name]
|
|
101
|
+
if pa.types.is_date(dtype) and pd.api.types.is_string_dtype(series):
|
|
102
|
+
series = series.str.slice(0, 10) # ndjson writes a date as an ISO datetime
|
|
103
|
+
if pa.types.is_timestamp(dtype) and pd.api.types.is_string_dtype(series):
|
|
104
|
+
# ndjson writes nanosecond ISO text, which a direct Arrow cast rejects
|
|
105
|
+
stamps = pd.to_datetime(series, utc=dtype.tz is not None)
|
|
106
|
+
series = stamps.dt.tz_convert(dtype.tz) if dtype.tz else stamps
|
|
107
|
+
df[col.name] = series.astype(pd.ArrowDtype(dtype))
|
|
108
|
+
frames.append(df)
|
|
109
|
+
return _concat(frames)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def write(df: pd.DataFrame, fmt: str, path: Path) -> None:
|
|
113
|
+
if fmt == "parquet":
|
|
114
|
+
df.to_parquet(path, engine="pyarrow", index=False)
|
|
115
|
+
elif fmt == "csv":
|
|
116
|
+
df.to_csv(path, index=False, lineterminator="\n")
|
|
117
|
+
elif fmt == "ndjson":
|
|
118
|
+
df.to_json(path, orient="records", lines=True, date_format="iso", date_unit="ns")
|
|
119
|
+
else:
|
|
120
|
+
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", "ephemeral"}),
|
|
15
|
+
sql_models=False,
|
|
16
|
+
views=False,
|
|
17
|
+
idempotent_writes=True,
|
|
18
|
+
cancel=False,
|
|
19
|
+
bytes_metrics=True,
|
|
20
|
+
portable=True,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PandasOptions(OptionsModel):
|
|
25
|
+
"""The pandas engine has no options."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _build(opts: Any) -> Engine:
|
|
29
|
+
from pipeloom_pandas.engine import PandasEngine
|
|
30
|
+
|
|
31
|
+
return PandasEngine()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
SPEC: PluginSpec[Engine] = PluginSpec(
|
|
35
|
+
"pandas",
|
|
36
|
+
"pandas",
|
|
37
|
+
"engines",
|
|
38
|
+
API_VERSION,
|
|
39
|
+
_build,
|
|
40
|
+
PandasOptions,
|
|
41
|
+
capabilities=CAPABILITIES,
|
|
42
|
+
description="Eager pandas DataFrames; tables on the filesystem catalog; no SQL in 0.2.",
|
|
43
|
+
)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""The pandas 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 pandas as pd
|
|
10
|
+
import pyarrow as pa
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
from pipeloom.builtins.filesystem import FilesystemCatalog
|
|
14
|
+
from pipeloom.engine.protocols import EngineSession
|
|
15
|
+
from pipeloom.engine.types import Relation, Schema
|
|
16
|
+
from pipeloom.testing.contract.engine import EngineContract, EngineHarness
|
|
17
|
+
from pipeloom_pandas import io
|
|
18
|
+
from pipeloom_pandas.engine import PandasEngine
|
|
19
|
+
|
|
20
|
+
Rows = Sequence[Mapping[str, Any]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _frame(rows: Rows, schema: Schema) -> pd.DataFrame:
|
|
24
|
+
arrow = pa.schema([(c.name, io.arrow_type(c.dtype)) for c in schema])
|
|
25
|
+
table = pa.Table.from_pylist([dict(r) for r in rows], schema=arrow)
|
|
26
|
+
return table.to_pandas(types_mapper=pd.ArrowDtype)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def harness(tmp_path: Path) -> EngineHarness:
|
|
30
|
+
def write_source(fmt: str, path: Path, rows: Rows, schema: Schema) -> None:
|
|
31
|
+
df = _frame(rows, schema)
|
|
32
|
+
if fmt == "json":
|
|
33
|
+
df.to_json(path, orient="records")
|
|
34
|
+
else:
|
|
35
|
+
io.write(df, fmt, path)
|
|
36
|
+
|
|
37
|
+
def to_rows(native: Any) -> list[dict[str, Any]]:
|
|
38
|
+
table = pa.Table.from_pandas(native, preserve_index=False)
|
|
39
|
+
return list(table.to_pylist())
|
|
40
|
+
|
|
41
|
+
def failing(session: EngineSession) -> Relation:
|
|
42
|
+
return session.relation(pd.DataFrame({"a": [object()]})) # parquet cannot store it
|
|
43
|
+
|
|
44
|
+
return EngineHarness(
|
|
45
|
+
engine=PandasEngine(),
|
|
46
|
+
catalog=FilesystemCatalog(tmp_path / "wh"),
|
|
47
|
+
make_native=_frame,
|
|
48
|
+
to_rows=to_rows,
|
|
49
|
+
write_source=write_source,
|
|
50
|
+
failing_relation=failing,
|
|
51
|
+
settings_snapshot=lambda: {
|
|
52
|
+
"string_storage": pd.get_option("mode.string_storage"),
|
|
53
|
+
"max_rows": pd.get_option("display.max_rows"),
|
|
54
|
+
},
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class TestPandasEngine(EngineContract):
|
|
59
|
+
@pytest.fixture
|
|
60
|
+
def engine_factory(self) -> Callable[[Path], EngineHarness]:
|
|
61
|
+
return harness
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""pandas engine details beyond the contract."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from pipeloom.api import Project, ProjectOptions
|
|
11
|
+
from pipeloom.builtins.filesystem import FilesystemCatalog
|
|
12
|
+
from pipeloom.engine import portable
|
|
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_pandas.engine import PandasEngine
|
|
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 PandasEngine().session(ctx(tmp_path), catalog=catalog) as s:
|
|
31
|
+
catalog.ensure_namespace(T.namespace)
|
|
32
|
+
rel = s.relation(pd.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
|
+
frame = out.native.sort_values("id")
|
|
36
|
+
assert [(r.id, None if pd.isna(r.label) else r.label) for r in frame.itertuples()] == [
|
|
37
|
+
(1, "a"),
|
|
38
|
+
(2, None),
|
|
39
|
+
]
|
|
40
|
+
assert [c.dtype for c in s.schema(out)] == ["int64", "string"]
|
|
41
|
+
assert len(list((tmp_path / "wh" / "main" / "t").glob(f"part-*.{fmt}"))) == 1
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_a_replayed_token_keeps_the_commit(tmp_path: Path) -> None:
|
|
45
|
+
catalog = FilesystemCatalog(tmp_path / "wh")
|
|
46
|
+
with PandasEngine().session(ctx(tmp_path), catalog=catalog) as s:
|
|
47
|
+
catalog.ensure_namespace(T.namespace)
|
|
48
|
+
rel = s.relation(pd.DataFrame({"id": [1]}))
|
|
49
|
+
mat = s.materializer("append")
|
|
50
|
+
first = mat.materialize(rel, T, WriteConfig("append"), "r:1")
|
|
51
|
+
before = sorted(p.name for p in (tmp_path / "wh" / "main" / "t").iterdir())
|
|
52
|
+
assert mat.materialize(rel, T, WriteConfig("append"), "r:1") == first
|
|
53
|
+
assert sorted(p.name for p in (tmp_path / "wh" / "main" / "t").iterdir()) == before
|
|
54
|
+
assert first.rows_written == 1 and first.bytes_written and first.target_version == 1
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_the_session_needs_the_filesystem_catalog(tmp_path: Path) -> None:
|
|
58
|
+
with (
|
|
59
|
+
pytest.raises(TypeError, match="filesystem catalog"),
|
|
60
|
+
PandasEngine().session(ctx(tmp_path), catalog=MemoryCatalog()),
|
|
61
|
+
):
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_unsupported_format_strategy_sql_and_view(tmp_path: Path) -> None:
|
|
66
|
+
catalog = FilesystemCatalog(tmp_path / "wh")
|
|
67
|
+
with PandasEngine().session(ctx(tmp_path), catalog=catalog) as s:
|
|
68
|
+
with pytest.raises(ValueError, match="format"):
|
|
69
|
+
s.reader("orc")
|
|
70
|
+
with pytest.raises(ValueError, match="strategy"):
|
|
71
|
+
s.materializer("merge")
|
|
72
|
+
with pytest.raises(NotImplementedError):
|
|
73
|
+
s.sql("select 1", {})
|
|
74
|
+
with pytest.raises(NotImplementedError):
|
|
75
|
+
s.create_view(T, "select 1", {})
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_a_missing_table_raises(tmp_path: Path) -> None:
|
|
79
|
+
catalog = FilesystemCatalog(tmp_path / "wh")
|
|
80
|
+
with (
|
|
81
|
+
PandasEngine().session(ctx(tmp_path), catalog=catalog) as s,
|
|
82
|
+
pytest.raises(FileNotFoundError),
|
|
83
|
+
):
|
|
84
|
+
s.reader("table").read(ReadSpec("table", table=T))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_string_columns_map_to_string_in_either_pandas_generation() -> None:
|
|
88
|
+
df = pd.DataFrame({"a": ["x", "y"], "b": pd.array(["x", None], dtype="string")})
|
|
89
|
+
assert [(c.name, c.dtype) for c in portable.schema(df)] == [("a", "string"), ("b", "string")]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
PANDAS_PROJECT = {
|
|
93
|
+
"pipeloom.yml": (
|
|
94
|
+
"config_version: 1\nname: p\npython_paths: [src]\n"
|
|
95
|
+
"targets:\n dev:\n engine: {kind: pandas}\n"
|
|
96
|
+
" catalog: {kind: filesystem, root: wh}\n"
|
|
97
|
+
),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def codes(tmp_path: Path, model: str) -> set[str]:
|
|
102
|
+
files = {**PANDAS_PROJECT, "models/m.yml": f"models:\n - {model}\n"}
|
|
103
|
+
for rel, content in files.items():
|
|
104
|
+
(tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
(tmp_path / rel).write_bytes(content.encode("utf-8"))
|
|
106
|
+
root = tmp_path
|
|
107
|
+
outcome = Project(ProjectOptions(project_dir=root, target="dev", env={})).validate()
|
|
108
|
+
return {d.code for d in outcome.diagnostics}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_a_sql_model_on_pandas_is_plc502(tmp_path: Path) -> None:
|
|
112
|
+
assert "PLC502" in codes(tmp_path, "{name: a, sql: select 1}")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_a_view_on_pandas_is_plc507(tmp_path: Path) -> None:
|
|
116
|
+
assert "PLC507" in codes(tmp_path, "{name: a, sql: select 1, materialized: view}")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@pytest.mark.parametrize("fmt", ["csv", "ndjson"])
|
|
120
|
+
def test_text_formats_restore_each_stored_type_even_beside_an_unknown_one(
|
|
121
|
+
tmp_path: Path, fmt: str
|
|
122
|
+
) -> None:
|
|
123
|
+
from datetime import UTC, date, datetime
|
|
124
|
+
from decimal import Decimal
|
|
125
|
+
|
|
126
|
+
import pyarrow as pa
|
|
127
|
+
|
|
128
|
+
arrow = pa.table(
|
|
129
|
+
{
|
|
130
|
+
"d": pa.array([date(2026, 1, 2), None], pa.date32()),
|
|
131
|
+
"t": pa.array(
|
|
132
|
+
[datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), None], pa.timestamp("us", "UTC")
|
|
133
|
+
),
|
|
134
|
+
"n": pa.array([Decimal("12.34"), None], pa.decimal128(18, 2)),
|
|
135
|
+
"i": pa.array([1, None], pa.int64()),
|
|
136
|
+
"z": pa.array(["007", None], pa.string()),
|
|
137
|
+
"us": pa.array([datetime(2026, 1, 2, 3, 4, 5, 123456), None], pa.timestamp("us")),
|
|
138
|
+
"u": pa.array([[1], None], pa.list_(pa.int64())), # a type the engine cannot name
|
|
139
|
+
}
|
|
140
|
+
)
|
|
141
|
+
catalog = FilesystemCatalog(tmp_path / "wh", format=fmt)
|
|
142
|
+
with PandasEngine().session(ctx(tmp_path), catalog=catalog) as s:
|
|
143
|
+
catalog.ensure_namespace(T.namespace)
|
|
144
|
+
rel = s.relation(arrow.to_pandas(types_mapper=pd.ArrowDtype))
|
|
145
|
+
s.materializer("overwrite").materialize(rel, T, WriteConfig("overwrite"), "r:1")
|
|
146
|
+
out = s.reader("table").read(ReadSpec("table", table=T))
|
|
147
|
+
got = {c.name: c.dtype for c in s.schema(out)}
|
|
148
|
+
want = {c.name: c.dtype for c in s.schema(rel)}
|
|
149
|
+
keys = ["d", "t", "n", "i", "z", "us"]
|
|
150
|
+
assert {k: got[k] for k in keys} == {k: want[k] for k in keys}
|
|
151
|
+
assert out.native["z"].iloc[0] == "007"
|
|
152
|
+
assert out.native["us"].iloc[0] == pd.Timestamp("2026-01-02 03:04:05.123456")
|
|
153
|
+
assert out.native["t"].iloc[0] == pd.Timestamp("2026-01-02 03:04:05", tz="UTC")
|
|
154
|
+
assert out.native["n"].iloc[0] == Decimal("12.34")
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""The pandas smoke project end to end, with both executors.
|
|
2
|
+
|
|
3
|
+
The project is `tests/fixtures/smoke-pandas`: csv sources, Python models (one on Narwhals frames),
|
|
4
|
+
an ephemeral model and an append table, 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 pandas as pd
|
|
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-pandas"
|
|
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="pandas", 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
|
+
df = pd.concat([pd.read_parquet(f) for f in t.files()], ignore_index=True)
|
|
55
|
+
df = df.sort_values(list(df.columns)).reset_index(drop=True)
|
|
56
|
+
return [
|
|
57
|
+
{k: v.item() if hasattr(v, "item") else v for k, v in r.items()}
|
|
58
|
+
for r in df.to_dict("records")
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def snapshot(root: Path) -> dict[str, bytes]:
|
|
63
|
+
wh = root / "target" / "warehouse"
|
|
64
|
+
return {
|
|
65
|
+
p.relative_to(wh).as_posix(): p.read_bytes() for p in sorted(wh.rglob("*")) if p.is_file()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@pytest.mark.parametrize(("boundary", "executor"), [("process", "thread"), ("task", "process")])
|
|
70
|
+
def test_smoke_runs_and_a_rerun_with_the_same_run_id_writes_nothing(
|
|
71
|
+
tmp_path: Path, boundary: str, executor: str
|
|
72
|
+
) -> None:
|
|
73
|
+
root = project(tmp_path, boundary)
|
|
74
|
+
outcome, sink = run(root, "r1")
|
|
75
|
+
assert (outcome.status, outcome.exit_code) == ("succeeded", 0), outcome.diagnostics
|
|
76
|
+
doc = json.loads((root / "target" / "runs" / "r1" / "run_results.json").read_bytes())
|
|
77
|
+
assert {r["executor"] for r in doc["results"]} == {executor}
|
|
78
|
+
assert {r["engine"] for r in doc["results"]} == {"pandas"}
|
|
79
|
+
assert table(root, "stg_customers") == [
|
|
80
|
+
{"id": 1, "email": "a@x.com"},
|
|
81
|
+
{"id": 2, "email": "b@x.com"},
|
|
82
|
+
]
|
|
83
|
+
assert table(root, "fct_orders") == [
|
|
84
|
+
{"id": 10, "customer_id": 1, "email": "a@x.com", "amount": 5.0},
|
|
85
|
+
{"id": 11, "customer_id": 2, "email": "b@x.com", "amount": 7.5},
|
|
86
|
+
{"id": 12, "customer_id": 1, "email": "a@x.com", "amount": 2.5},
|
|
87
|
+
]
|
|
88
|
+
assert table(root, "rpt_revenue") == [
|
|
89
|
+
{"customer_id": 1, "revenue": 7.5},
|
|
90
|
+
{"customer_id": 2, "revenue": 7.5},
|
|
91
|
+
]
|
|
92
|
+
assert not [e for e in sink.events if e.type == "unit.failed"]
|
|
93
|
+
|
|
94
|
+
before = snapshot(root)
|
|
95
|
+
again, _ = run(root, "r1")
|
|
96
|
+
assert again.exit_code == 0
|
|
97
|
+
assert snapshot(root) == before # token replay: no new part file, commits untouched
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""The spec module is readable without importing pandas or pyarrow."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
CODE = """
|
|
9
|
+
import sys
|
|
10
|
+
import pipeloom_pandas.spec as spec
|
|
11
|
+
assert spec.SPEC.capabilities.portable
|
|
12
|
+
assert not spec.SPEC.capabilities.sql_models
|
|
13
|
+
assert "pandas" not in sys.modules, "pandas was imported"
|
|
14
|
+
assert "pyarrow" not in sys.modules, "pyarrow was imported"
|
|
15
|
+
assert "pipeloom_pandas.engine" not in sys.modules
|
|
16
|
+
print("ok")
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_spec_import_does_not_import_pandas() -> None:
|
|
21
|
+
proc = subprocess.run(
|
|
22
|
+
[sys.executable, "-I", "-c", CODE], capture_output=True, text=True, check=False
|
|
23
|
+
)
|
|
24
|
+
assert proc.returncode == 0, proc.stderr
|
|
25
|
+
assert proc.stdout.strip() == "ok"
|