dlt-altertable 0.1.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.
- dlt_altertable-0.1.0/LICENSE +202 -0
- dlt_altertable-0.1.0/PKG-INFO +234 -0
- dlt_altertable-0.1.0/README.md +209 -0
- dlt_altertable-0.1.0/pyproject.toml +68 -0
- dlt_altertable-0.1.0/pyproject.toml.orig +48 -0
- dlt_altertable-0.1.0/src/dlt_altertable/__init__.py +3 -0
- dlt_altertable-0.1.0/src/dlt_altertable/api.py +80 -0
- dlt_altertable-0.1.0/src/dlt_altertable/configuration.py +54 -0
- dlt_altertable-0.1.0/src/dlt_altertable/destination.py +114 -0
- dlt_altertable-0.1.0/src/dlt_altertable/py.typed +0 -0
- dlt_altertable-0.1.0/src/dlt_altertable/table_schema.py +126 -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,234 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dlt-altertable
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: dlt destination that loads into the Altertable lakehouse through its HTTP API
|
|
5
|
+
Keywords: dlt,altertable,lakehouse,parquet
|
|
6
|
+
Author: Altertable
|
|
7
|
+
Author-email: Altertable <hello@altertable.ai>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Topic :: Database
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Requires-Dist: dlt[parquet]~=1.19
|
|
17
|
+
Requires-Dist: pyarrow>=15.0.0
|
|
18
|
+
Requires-Dist: requests>=2.26
|
|
19
|
+
Requires-Dist: urllib3>=2
|
|
20
|
+
Requires-Python: >=3.12
|
|
21
|
+
Project-URL: Homepage, https://altertable.ai
|
|
22
|
+
Project-URL: Repository, https://github.com/altertable-ai/dlt-altertable
|
|
23
|
+
Project-URL: Changelog, https://github.com/altertable-ai/dlt-altertable/blob/main/CHANGELOG.md
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# dlt-altertable
|
|
27
|
+
|
|
28
|
+
[](https://github.com/altertable-ai/dlt-altertable/actions/workflows/ci.yml)
|
|
29
|
+
[](https://pypi.org/project/dlt-altertable/)
|
|
30
|
+
[](https://www.python.org)
|
|
31
|
+
[](LICENSE)
|
|
32
|
+
|
|
33
|
+
A [dlt](https://dlthub.com) destination that loads into the [Altertable](https://altertable.ai)
|
|
34
|
+
lakehouse through the HTTP Lakehouse API. Each dlt load job is one parquet file, posted verbatim
|
|
35
|
+
to `/upload` or `/upsert`. An append or replace file written before dlt evolved the load's schema
|
|
36
|
+
is padded with typed `NULL` columns first, because those uploads must match the table column for
|
|
37
|
+
column. Merge files always post as they are, so columns a file omits keep their stored values.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
uv add dlt-altertable
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Supported: Python 3.12 to 3.14, `dlt >= 1.19`. The only other dependencies are `pyarrow`, `requests`, and `urllib3`.
|
|
46
|
+
|
|
47
|
+
## Use
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import dlt
|
|
51
|
+
from dlt_altertable import altertable
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dlt.resource(
|
|
55
|
+
name="contacts",
|
|
56
|
+
write_disposition="merge",
|
|
57
|
+
primary_key="id",
|
|
58
|
+
columns={"lastmodifieddate": {"dedup_sort": "desc"}},
|
|
59
|
+
)
|
|
60
|
+
def contacts():
|
|
61
|
+
yield [
|
|
62
|
+
{"id": 1, "email": "ada@example.com", "lastmodifieddate": 100},
|
|
63
|
+
{"id": 2, "email": "grace@example.com", "lastmodifieddate": 100},
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
pipeline = dlt.pipeline(pipeline_name="crm", destination=altertable)
|
|
68
|
+
pipeline.run(contacts())
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Configure the connection in `.dlt/secrets.toml`:
|
|
72
|
+
|
|
73
|
+
```toml
|
|
74
|
+
[destination.altertable]
|
|
75
|
+
host = "api.altertable.ai"
|
|
76
|
+
catalog = "lakehouse"
|
|
77
|
+
dataset_name = "crm"
|
|
78
|
+
username = "..."
|
|
79
|
+
password = "..."
|
|
80
|
+
# port = 443, tls = true and compute_size = "XS" (for schema queries) are the defaults
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Every setting can also come from dlt's environment variables, which override the toml file
|
|
84
|
+
(`DESTINATION__ALTERTABLE__HOST`, `DESTINATION__ALTERTABLE__PASSWORD`, and so on), or be passed
|
|
85
|
+
directly: `altertable(host=..., catalog=..., dataset_name=...)`.
|
|
86
|
+
|
|
87
|
+
No configuration is needed in an environment that already exports the `ALTERTABLE_HOST`,
|
|
88
|
+
`ALTERTABLE_PORT`, `ALTERTABLE_TLS`, `ALTERTABLE_USERNAME`, `ALTERTABLE_PASSWORD`,
|
|
89
|
+
`ALTERTABLE_CATALOG` and `ALTERTABLE_SCHEMA` variables. The host must be the HTTP API host
|
|
90
|
+
(`api.…`), not the Flight SQL endpoint.
|
|
91
|
+
|
|
92
|
+
Two notes on naming:
|
|
93
|
+
|
|
94
|
+
- The pipeline's `dataset_name` is not used. dlt does not route it to custom destinations, so the
|
|
95
|
+
target schema is the destination's own `dataset_name` setting.
|
|
96
|
+
- To point several pipelines at different backends, name each configuration:
|
|
97
|
+
`altertable(destination_name="altertable_staging")` reads `[destination.altertable_staging]`.
|
|
98
|
+
|
|
99
|
+
## Write dispositions
|
|
100
|
+
|
|
101
|
+
| dlt write disposition | HTTP call | Notes |
|
|
102
|
+
| --------------------- | ---------------------------------------- | ---------------------------------------------------- |
|
|
103
|
+
| `append` | `POST /upload?mode=append` | The destination creates or evolves the table first. |
|
|
104
|
+
| `replace` | `mode=overwrite`, then `mode=append` | The first file of each load recreates the table. |
|
|
105
|
+
| `merge` | `POST /upsert?primary_key=…&cursor_field=…` | Server-side upsert on the `primary_key`. |
|
|
106
|
+
|
|
107
|
+
Merge always runs as a server-side upsert on the `primary_key`, dlt's `upsert` merge strategy.
|
|
108
|
+
A resource that does not name a strategy is accepted and upserted the same way. Configurations
|
|
109
|
+
the upsert cannot honor fail the load with a terminal error instead of loading under different
|
|
110
|
+
semantics: an explicit `delete-insert` or `scd2` strategy, a `merge_key`, a `hard_delete`
|
|
111
|
+
column, a missing `primary_key`, or an ascending `dedup_sort`.
|
|
112
|
+
|
|
113
|
+
A merge that sends a subset of columns updates only those columns on matched rows; omitted
|
|
114
|
+
columns keep their current values in the lakehouse.
|
|
115
|
+
|
|
116
|
+
### Picking the winning row
|
|
117
|
+
|
|
118
|
+
When two rows collide on the primary key, Altertable keeps the one with the highest value of the
|
|
119
|
+
column marked with dlt's standard [`dedup_sort` hint](https://dlthub.com/docs/general-usage/merge-loading):
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
@dlt.resource(
|
|
123
|
+
write_disposition="merge",
|
|
124
|
+
primary_key="id",
|
|
125
|
+
columns={"lastmodifieddate": {"dedup_sort": "desc"}},
|
|
126
|
+
)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Altertable arbitrates against existing table rows as well as within the batch, a superset of
|
|
130
|
+
dlt's batch-only deduplication. Without the hint, which row wins is up to the server.
|
|
131
|
+
|
|
132
|
+
## dlt system columns and tables
|
|
133
|
+
|
|
134
|
+
Like dlt's SQL destinations, this destination loads dlt's lineage columns: every row carries
|
|
135
|
+
`_dlt_id` and `_dlt_load_id`, making it traceable to the load that produced it. The dataset also
|
|
136
|
+
gains a `_dlt_pipeline_state` table. dlt maintains `_dlt_loads` and `_dlt_version` only inside
|
|
137
|
+
SQL destinations, so those tables do not appear here.
|
|
138
|
+
|
|
139
|
+
## Schema evolution
|
|
140
|
+
|
|
141
|
+
The destination owns the target table's schema. Before each load it syncs the table through
|
|
142
|
+
`POST /query`: a missing table is created with typed DDL derived from dlt's schema, and when
|
|
143
|
+
dlt's schema evolution adds a column, the destination issues `ALTER TABLE ... ADD COLUMN`, so
|
|
144
|
+
existing tables follow the source. Removed columns stay in the table and keep their values.
|
|
145
|
+
Columns that only ever contained `NULL` are dropped by dlt at normalize time with a warning,
|
|
146
|
+
before they reach the destination.
|
|
147
|
+
|
|
148
|
+
Nested data does not become child tables: the destination sets `max_table_nesting=0`, dlt's
|
|
149
|
+
default for custom destinations, so lists and objects land as JSON strings in the parent table.
|
|
150
|
+
|
|
151
|
+
## Atomicity and retries
|
|
152
|
+
|
|
153
|
+
Each parquet file is one HTTP POST, applied atomically by the server: a file either lands fully
|
|
154
|
+
or not at all. A load split across several files is not atomic as a whole, and the first file of
|
|
155
|
+
a `replace` load recreates the table.
|
|
156
|
+
|
|
157
|
+
Failures map onto dlt's retry contract: errors a retry cannot fix, such as bad credentials or
|
|
158
|
+
an invalid request, fail the job immediately with a terminal error, while server errors,
|
|
159
|
+
capacity timeouts and connection failures are retried by dlt until the fifth attempt fails
|
|
160
|
+
(`load.raise_on_max_retries`). Errors streamed mid-response by `/query` retry as well, which
|
|
161
|
+
is safe because every statement the destination issues is `IF NOT EXISTS`-idempotent. The upload
|
|
162
|
+
read timeout is one hour, because the server answers only once the file is fully ingested. Do
|
|
163
|
+
not lower it: a request aborted client side can still complete on the server, which turns dlt's
|
|
164
|
+
retry into duplicate appended rows. `merge` tables are idempotent under retry, `append` is at
|
|
165
|
+
least once, and `replace` is at least once after its first file, since only the first file of
|
|
166
|
+
the load recreates the table and a retried later file appends twice.
|
|
167
|
+
|
|
168
|
+
The destination declares `loader_parallelism_strategy="table-sequential"`, and the `replace`
|
|
169
|
+
bookkeeping depends on it. Do not override it with `LOAD__PARALLELISM_STRATEGY=parallel`: two
|
|
170
|
+
files of one replace load would both recreate the table and silently lose rows.
|
|
171
|
+
|
|
172
|
+
One caveat discovered the hard way: the target schema is created on demand, so a typo in
|
|
173
|
+
`dataset_name` does not fail, it lands data in a new schema. The catalog, by contrast,
|
|
174
|
+
must exist.
|
|
175
|
+
|
|
176
|
+
## Incremental state on ephemeral runners
|
|
177
|
+
|
|
178
|
+
[Custom destinations cannot restore pipeline state](https://dlthub.com/docs/dlt-ecosystem/destinations/destination),
|
|
179
|
+
so incremental cursors live only in dlt's own state under `pipelines_dir`. On an ephemeral runner
|
|
180
|
+
that directory is gone on the next run, and every load starts from scratch.
|
|
181
|
+
|
|
182
|
+
Either persist `pipelines_dir` between runs, or bootstrap the cursor from the destination itself
|
|
183
|
+
before extracting:
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
import json
|
|
187
|
+
import requests
|
|
188
|
+
|
|
189
|
+
response = requests.post(
|
|
190
|
+
"https://api.altertable.ai/query",
|
|
191
|
+
json={"statement": f'SELECT max(lastmodifieddate) FROM "{catalog}"."{schema}"."{table_name}"'},
|
|
192
|
+
auth=(username, password),
|
|
193
|
+
timeout=(10, 300),
|
|
194
|
+
)
|
|
195
|
+
response.raise_for_status()
|
|
196
|
+
rows = [json.loads(line) for line in response.text.splitlines()]
|
|
197
|
+
if any(isinstance(row, dict) and "error" in row for row in rows):
|
|
198
|
+
raise RuntimeError(rows)
|
|
199
|
+
since = rows[2][0]
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
The response streams one JSON line per row after two metadata lines, so the first row sits at
|
|
203
|
+
index 2. A failed query arrives as an `{"error": ...}` line inside the stream, not as a special
|
|
204
|
+
row, so check for it before trusting the value. An empty table gives a `NULL` max, which simply
|
|
205
|
+
means start from the beginning.
|
|
206
|
+
|
|
207
|
+
## Develop
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
uv run --locked pytest
|
|
211
|
+
uv run --locked ruff check .
|
|
212
|
+
uv run --locked ruff format --check .
|
|
213
|
+
uvx ty check src
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
The test suite mocks the HTTP API and needs no server. For a live check, run
|
|
217
|
+
[altertable-mock](https://github.com/altertable-ai/altertable-mock) and point a pipeline at its
|
|
218
|
+
Lakehouse REST port:
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
docker run -d -p 15100:15000 \
|
|
222
|
+
-e ALTERTABLE_MOCK_LAKEHOUSE_PORT=15000 -e ALTERTABLE_MOCK_USERS="dlt-demo:lk_demo" \
|
|
223
|
+
ghcr.io/altertable-ai/altertable-mock:latest
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
## Resources
|
|
227
|
+
|
|
228
|
+
- [dlt custom destination docs](https://dlthub.com/docs/dlt-ecosystem/destinations/destination)
|
|
229
|
+
- [dlt merge loading](https://dlthub.com/docs/general-usage/merge-loading)
|
|
230
|
+
- [Altertable](https://altertable.ai)
|
|
231
|
+
|
|
232
|
+
## License
|
|
233
|
+
|
|
234
|
+
Apache 2.0, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# dlt-altertable
|
|
2
|
+
|
|
3
|
+
[](https://github.com/altertable-ai/dlt-altertable/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/dlt-altertable/)
|
|
5
|
+
[](https://www.python.org)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
A [dlt](https://dlthub.com) destination that loads into the [Altertable](https://altertable.ai)
|
|
9
|
+
lakehouse through the HTTP Lakehouse API. Each dlt load job is one parquet file, posted verbatim
|
|
10
|
+
to `/upload` or `/upsert`. An append or replace file written before dlt evolved the load's schema
|
|
11
|
+
is padded with typed `NULL` columns first, because those uploads must match the table column for
|
|
12
|
+
column. Merge files always post as they are, so columns a file omits keep their stored values.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
uv add dlt-altertable
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Supported: Python 3.12 to 3.14, `dlt >= 1.19`. The only other dependencies are `pyarrow`, `requests`, and `urllib3`.
|
|
21
|
+
|
|
22
|
+
## Use
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
import dlt
|
|
26
|
+
from dlt_altertable import altertable
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dlt.resource(
|
|
30
|
+
name="contacts",
|
|
31
|
+
write_disposition="merge",
|
|
32
|
+
primary_key="id",
|
|
33
|
+
columns={"lastmodifieddate": {"dedup_sort": "desc"}},
|
|
34
|
+
)
|
|
35
|
+
def contacts():
|
|
36
|
+
yield [
|
|
37
|
+
{"id": 1, "email": "ada@example.com", "lastmodifieddate": 100},
|
|
38
|
+
{"id": 2, "email": "grace@example.com", "lastmodifieddate": 100},
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
pipeline = dlt.pipeline(pipeline_name="crm", destination=altertable)
|
|
43
|
+
pipeline.run(contacts())
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Configure the connection in `.dlt/secrets.toml`:
|
|
47
|
+
|
|
48
|
+
```toml
|
|
49
|
+
[destination.altertable]
|
|
50
|
+
host = "api.altertable.ai"
|
|
51
|
+
catalog = "lakehouse"
|
|
52
|
+
dataset_name = "crm"
|
|
53
|
+
username = "..."
|
|
54
|
+
password = "..."
|
|
55
|
+
# port = 443, tls = true and compute_size = "XS" (for schema queries) are the defaults
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Every setting can also come from dlt's environment variables, which override the toml file
|
|
59
|
+
(`DESTINATION__ALTERTABLE__HOST`, `DESTINATION__ALTERTABLE__PASSWORD`, and so on), or be passed
|
|
60
|
+
directly: `altertable(host=..., catalog=..., dataset_name=...)`.
|
|
61
|
+
|
|
62
|
+
No configuration is needed in an environment that already exports the `ALTERTABLE_HOST`,
|
|
63
|
+
`ALTERTABLE_PORT`, `ALTERTABLE_TLS`, `ALTERTABLE_USERNAME`, `ALTERTABLE_PASSWORD`,
|
|
64
|
+
`ALTERTABLE_CATALOG` and `ALTERTABLE_SCHEMA` variables. The host must be the HTTP API host
|
|
65
|
+
(`api.…`), not the Flight SQL endpoint.
|
|
66
|
+
|
|
67
|
+
Two notes on naming:
|
|
68
|
+
|
|
69
|
+
- The pipeline's `dataset_name` is not used. dlt does not route it to custom destinations, so the
|
|
70
|
+
target schema is the destination's own `dataset_name` setting.
|
|
71
|
+
- To point several pipelines at different backends, name each configuration:
|
|
72
|
+
`altertable(destination_name="altertable_staging")` reads `[destination.altertable_staging]`.
|
|
73
|
+
|
|
74
|
+
## Write dispositions
|
|
75
|
+
|
|
76
|
+
| dlt write disposition | HTTP call | Notes |
|
|
77
|
+
| --------------------- | ---------------------------------------- | ---------------------------------------------------- |
|
|
78
|
+
| `append` | `POST /upload?mode=append` | The destination creates or evolves the table first. |
|
|
79
|
+
| `replace` | `mode=overwrite`, then `mode=append` | The first file of each load recreates the table. |
|
|
80
|
+
| `merge` | `POST /upsert?primary_key=…&cursor_field=…` | Server-side upsert on the `primary_key`. |
|
|
81
|
+
|
|
82
|
+
Merge always runs as a server-side upsert on the `primary_key`, dlt's `upsert` merge strategy.
|
|
83
|
+
A resource that does not name a strategy is accepted and upserted the same way. Configurations
|
|
84
|
+
the upsert cannot honor fail the load with a terminal error instead of loading under different
|
|
85
|
+
semantics: an explicit `delete-insert` or `scd2` strategy, a `merge_key`, a `hard_delete`
|
|
86
|
+
column, a missing `primary_key`, or an ascending `dedup_sort`.
|
|
87
|
+
|
|
88
|
+
A merge that sends a subset of columns updates only those columns on matched rows; omitted
|
|
89
|
+
columns keep their current values in the lakehouse.
|
|
90
|
+
|
|
91
|
+
### Picking the winning row
|
|
92
|
+
|
|
93
|
+
When two rows collide on the primary key, Altertable keeps the one with the highest value of the
|
|
94
|
+
column marked with dlt's standard [`dedup_sort` hint](https://dlthub.com/docs/general-usage/merge-loading):
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
@dlt.resource(
|
|
98
|
+
write_disposition="merge",
|
|
99
|
+
primary_key="id",
|
|
100
|
+
columns={"lastmodifieddate": {"dedup_sort": "desc"}},
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Altertable arbitrates against existing table rows as well as within the batch, a superset of
|
|
105
|
+
dlt's batch-only deduplication. Without the hint, which row wins is up to the server.
|
|
106
|
+
|
|
107
|
+
## dlt system columns and tables
|
|
108
|
+
|
|
109
|
+
Like dlt's SQL destinations, this destination loads dlt's lineage columns: every row carries
|
|
110
|
+
`_dlt_id` and `_dlt_load_id`, making it traceable to the load that produced it. The dataset also
|
|
111
|
+
gains a `_dlt_pipeline_state` table. dlt maintains `_dlt_loads` and `_dlt_version` only inside
|
|
112
|
+
SQL destinations, so those tables do not appear here.
|
|
113
|
+
|
|
114
|
+
## Schema evolution
|
|
115
|
+
|
|
116
|
+
The destination owns the target table's schema. Before each load it syncs the table through
|
|
117
|
+
`POST /query`: a missing table is created with typed DDL derived from dlt's schema, and when
|
|
118
|
+
dlt's schema evolution adds a column, the destination issues `ALTER TABLE ... ADD COLUMN`, so
|
|
119
|
+
existing tables follow the source. Removed columns stay in the table and keep their values.
|
|
120
|
+
Columns that only ever contained `NULL` are dropped by dlt at normalize time with a warning,
|
|
121
|
+
before they reach the destination.
|
|
122
|
+
|
|
123
|
+
Nested data does not become child tables: the destination sets `max_table_nesting=0`, dlt's
|
|
124
|
+
default for custom destinations, so lists and objects land as JSON strings in the parent table.
|
|
125
|
+
|
|
126
|
+
## Atomicity and retries
|
|
127
|
+
|
|
128
|
+
Each parquet file is one HTTP POST, applied atomically by the server: a file either lands fully
|
|
129
|
+
or not at all. A load split across several files is not atomic as a whole, and the first file of
|
|
130
|
+
a `replace` load recreates the table.
|
|
131
|
+
|
|
132
|
+
Failures map onto dlt's retry contract: errors a retry cannot fix, such as bad credentials or
|
|
133
|
+
an invalid request, fail the job immediately with a terminal error, while server errors,
|
|
134
|
+
capacity timeouts and connection failures are retried by dlt until the fifth attempt fails
|
|
135
|
+
(`load.raise_on_max_retries`). Errors streamed mid-response by `/query` retry as well, which
|
|
136
|
+
is safe because every statement the destination issues is `IF NOT EXISTS`-idempotent. The upload
|
|
137
|
+
read timeout is one hour, because the server answers only once the file is fully ingested. Do
|
|
138
|
+
not lower it: a request aborted client side can still complete on the server, which turns dlt's
|
|
139
|
+
retry into duplicate appended rows. `merge` tables are idempotent under retry, `append` is at
|
|
140
|
+
least once, and `replace` is at least once after its first file, since only the first file of
|
|
141
|
+
the load recreates the table and a retried later file appends twice.
|
|
142
|
+
|
|
143
|
+
The destination declares `loader_parallelism_strategy="table-sequential"`, and the `replace`
|
|
144
|
+
bookkeeping depends on it. Do not override it with `LOAD__PARALLELISM_STRATEGY=parallel`: two
|
|
145
|
+
files of one replace load would both recreate the table and silently lose rows.
|
|
146
|
+
|
|
147
|
+
One caveat discovered the hard way: the target schema is created on demand, so a typo in
|
|
148
|
+
`dataset_name` does not fail, it lands data in a new schema. The catalog, by contrast,
|
|
149
|
+
must exist.
|
|
150
|
+
|
|
151
|
+
## Incremental state on ephemeral runners
|
|
152
|
+
|
|
153
|
+
[Custom destinations cannot restore pipeline state](https://dlthub.com/docs/dlt-ecosystem/destinations/destination),
|
|
154
|
+
so incremental cursors live only in dlt's own state under `pipelines_dir`. On an ephemeral runner
|
|
155
|
+
that directory is gone on the next run, and every load starts from scratch.
|
|
156
|
+
|
|
157
|
+
Either persist `pipelines_dir` between runs, or bootstrap the cursor from the destination itself
|
|
158
|
+
before extracting:
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
import json
|
|
162
|
+
import requests
|
|
163
|
+
|
|
164
|
+
response = requests.post(
|
|
165
|
+
"https://api.altertable.ai/query",
|
|
166
|
+
json={"statement": f'SELECT max(lastmodifieddate) FROM "{catalog}"."{schema}"."{table_name}"'},
|
|
167
|
+
auth=(username, password),
|
|
168
|
+
timeout=(10, 300),
|
|
169
|
+
)
|
|
170
|
+
response.raise_for_status()
|
|
171
|
+
rows = [json.loads(line) for line in response.text.splitlines()]
|
|
172
|
+
if any(isinstance(row, dict) and "error" in row for row in rows):
|
|
173
|
+
raise RuntimeError(rows)
|
|
174
|
+
since = rows[2][0]
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
The response streams one JSON line per row after two metadata lines, so the first row sits at
|
|
178
|
+
index 2. A failed query arrives as an `{"error": ...}` line inside the stream, not as a special
|
|
179
|
+
row, so check for it before trusting the value. An empty table gives a `NULL` max, which simply
|
|
180
|
+
means start from the beginning.
|
|
181
|
+
|
|
182
|
+
## Develop
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
uv run --locked pytest
|
|
186
|
+
uv run --locked ruff check .
|
|
187
|
+
uv run --locked ruff format --check .
|
|
188
|
+
uvx ty check src
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
The test suite mocks the HTTP API and needs no server. For a live check, run
|
|
192
|
+
[altertable-mock](https://github.com/altertable-ai/altertable-mock) and point a pipeline at its
|
|
193
|
+
Lakehouse REST port:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
docker run -d -p 15100:15000 \
|
|
197
|
+
-e ALTERTABLE_MOCK_LAKEHOUSE_PORT=15000 -e ALTERTABLE_MOCK_USERS="dlt-demo:lk_demo" \
|
|
198
|
+
ghcr.io/altertable-ai/altertable-mock:latest
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## Resources
|
|
202
|
+
|
|
203
|
+
- [dlt custom destination docs](https://dlthub.com/docs/dlt-ecosystem/destinations/destination)
|
|
204
|
+
- [dlt merge loading](https://dlthub.com/docs/general-usage/merge-loading)
|
|
205
|
+
- [Altertable](https://altertable.ai)
|
|
206
|
+
|
|
207
|
+
## License
|
|
208
|
+
|
|
209
|
+
Apache 2.0, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "dlt-altertable"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "dlt destination that loads into the Altertable lakehouse through its HTTP API"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
keywords = [
|
|
9
|
+
"dlt",
|
|
10
|
+
"altertable",
|
|
11
|
+
"lakehouse",
|
|
12
|
+
"parquet",
|
|
13
|
+
]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Topic :: Database",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
]
|
|
22
|
+
requires-python = ">=3.12"
|
|
23
|
+
dependencies = [
|
|
24
|
+
"dlt[parquet]~=1.19",
|
|
25
|
+
"pyarrow>=15.0.0",
|
|
26
|
+
"requests>=2.26",
|
|
27
|
+
"urllib3>=2",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[[project.authors]]
|
|
31
|
+
name = "Altertable"
|
|
32
|
+
email = "hello@altertable.ai"
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://altertable.ai"
|
|
36
|
+
Repository = "https://github.com/altertable-ai/dlt-altertable"
|
|
37
|
+
Changelog = "https://github.com/altertable-ai/dlt-altertable/blob/main/CHANGELOG.md"
|
|
38
|
+
|
|
39
|
+
[dependency-groups]
|
|
40
|
+
dev = [
|
|
41
|
+
"pytest~=8.4",
|
|
42
|
+
"ruff~=0.14",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
[build-system]
|
|
46
|
+
requires = ["uv_build>=0.11.29,<0.12.0"]
|
|
47
|
+
build-backend = "uv_build"
|
|
48
|
+
|
|
49
|
+
[tool.ruff]
|
|
50
|
+
line-length = 100
|
|
51
|
+
target-version = "py312"
|
|
52
|
+
|
|
53
|
+
[tool.ruff.lint]
|
|
54
|
+
select = [
|
|
55
|
+
"E",
|
|
56
|
+
"F",
|
|
57
|
+
"I",
|
|
58
|
+
"UP",
|
|
59
|
+
"B",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
[tool.pytest.ini_options]
|
|
63
|
+
testpaths = ["tests"]
|
|
64
|
+
addopts = [
|
|
65
|
+
"-v",
|
|
66
|
+
"--tb=short",
|
|
67
|
+
"--strict-markers",
|
|
68
|
+
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "dlt-altertable"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "dlt destination that loads into the Altertable lakehouse through its HTTP API"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [{ name = "Altertable", email = "hello@altertable.ai" }]
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
keywords = ["dlt", "altertable", "lakehouse", "parquet"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 4 - Beta",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Topic :: Database",
|
|
14
|
+
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Programming Language :: Python :: 3.13",
|
|
16
|
+
"Programming Language :: Python :: 3.14",
|
|
17
|
+
]
|
|
18
|
+
requires-python = ">=3.12"
|
|
19
|
+
|
|
20
|
+
dependencies = [
|
|
21
|
+
"dlt[parquet]~=1.19",
|
|
22
|
+
"pyarrow>=15.0.0",
|
|
23
|
+
"requests>=2.26",
|
|
24
|
+
"urllib3>=2",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://altertable.ai"
|
|
29
|
+
Repository = "https://github.com/altertable-ai/dlt-altertable"
|
|
30
|
+
Changelog = "https://github.com/altertable-ai/dlt-altertable/blob/main/CHANGELOG.md"
|
|
31
|
+
|
|
32
|
+
[dependency-groups]
|
|
33
|
+
dev = ["pytest~=8.4", "ruff~=0.14"]
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["uv_build>=0.11.29,<0.12.0"]
|
|
37
|
+
build-backend = "uv_build"
|
|
38
|
+
|
|
39
|
+
[tool.ruff]
|
|
40
|
+
line-length = 100
|
|
41
|
+
target-version = "py312"
|
|
42
|
+
|
|
43
|
+
[tool.ruff.lint]
|
|
44
|
+
select = ["E", "F", "I", "UP", "B"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|
|
48
|
+
addopts = ["-v", "--tb=short", "--strict-markers"]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
from dlt.common.destination.exceptions import DestinationTerminalException
|
|
7
|
+
from requests.adapters import HTTPAdapter
|
|
8
|
+
|
|
9
|
+
from dlt_altertable.configuration import AltertableClientConfiguration
|
|
10
|
+
|
|
11
|
+
UPLOAD_TIMEOUT = (30, 3600)
|
|
12
|
+
QUERY_TIMEOUT = (10, 300)
|
|
13
|
+
UPLOAD_WRITE_BLOCK_BYTES = 1 << 20
|
|
14
|
+
LOADER_WORKERS = 20
|
|
15
|
+
TERMINAL_STATUSES = {
|
|
16
|
+
HTTPStatus.BAD_REQUEST,
|
|
17
|
+
HTTPStatus.UNAUTHORIZED,
|
|
18
|
+
HTTPStatus.PAYMENT_REQUIRED,
|
|
19
|
+
HTTPStatus.FORBIDDEN,
|
|
20
|
+
HTTPStatus.NOT_FOUND,
|
|
21
|
+
HTTPStatus.METHOD_NOT_ALLOWED,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class LargeBlockAdapter(HTTPAdapter):
|
|
26
|
+
"""A load job posts a whole parquet file in one stream, and urllib3's default blocksize is
|
|
27
|
+
sized for ordinary requests, not for a file-sized body."""
|
|
28
|
+
|
|
29
|
+
def init_poolmanager(self, *args: Any, **kwargs: Any) -> None:
|
|
30
|
+
kwargs["blocksize"] = UPLOAD_WRITE_BLOCK_BYTES
|
|
31
|
+
super().init_poolmanager(*args, **kwargs)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
session = requests.Session()
|
|
35
|
+
_adapter = LargeBlockAdapter(pool_maxsize=LOADER_WORKERS)
|
|
36
|
+
session.mount("http://", _adapter)
|
|
37
|
+
session.mount("https://", _adapter)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def raise_for_failure(response: requests.Response, action: str) -> None:
|
|
41
|
+
if response.status_code == HTTPStatus.OK:
|
|
42
|
+
return
|
|
43
|
+
detail = f"{action} failed with HTTP {response.status_code}: {response.text.strip()[:2000]}"
|
|
44
|
+
if response.status_code in TERMINAL_STATUSES:
|
|
45
|
+
raise DestinationTerminalException(detail)
|
|
46
|
+
raise RuntimeError(detail)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def execute_sql(config: AltertableClientConfiguration, statement: str) -> list[list]:
|
|
50
|
+
response = session.post(
|
|
51
|
+
f"{config.base_url}/query",
|
|
52
|
+
json={"statement": statement, "ephemeral": True, "compute_size": config.compute_size},
|
|
53
|
+
auth=config.basic_auth,
|
|
54
|
+
timeout=QUERY_TIMEOUT,
|
|
55
|
+
)
|
|
56
|
+
raise_for_failure(response, f"query {statement!r}")
|
|
57
|
+
payload = [json.loads(line) for line in response.text.splitlines() if line.strip()]
|
|
58
|
+
for entry in payload:
|
|
59
|
+
if isinstance(entry, dict) and "error" in entry:
|
|
60
|
+
raise RuntimeError(f"query {statement!r} failed mid-stream: {entry['error']}")
|
|
61
|
+
return payload[2:]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def post_parquet(
|
|
65
|
+
config: AltertableClientConfiguration,
|
|
66
|
+
endpoint: str,
|
|
67
|
+
params: dict[str, str],
|
|
68
|
+
parquet_file_path: str,
|
|
69
|
+
action: str,
|
|
70
|
+
) -> None:
|
|
71
|
+
with open(parquet_file_path, "rb") as parquet_file:
|
|
72
|
+
response = session.post(
|
|
73
|
+
f"{config.base_url}/{endpoint}",
|
|
74
|
+
params=params,
|
|
75
|
+
data=parquet_file,
|
|
76
|
+
auth=config.basic_auth,
|
|
77
|
+
headers={"Content-Type": "application/parquet"},
|
|
78
|
+
timeout=UPLOAD_TIMEOUT,
|
|
79
|
+
)
|
|
80
|
+
raise_for_failure(response, action)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import cast
|
|
3
|
+
|
|
4
|
+
from dlt.common.configuration import ConfigurationValueError, configspec
|
|
5
|
+
from dlt.common.typing import TSecretStrValue
|
|
6
|
+
from dlt.destinations.impl.destination.configuration import CustomDestinationClientConfiguration
|
|
7
|
+
|
|
8
|
+
ENV_FALLBACKS = {
|
|
9
|
+
"host": "ALTERTABLE_HOST",
|
|
10
|
+
"catalog": "ALTERTABLE_CATALOG",
|
|
11
|
+
"dataset_name": "ALTERTABLE_SCHEMA",
|
|
12
|
+
"username": "ALTERTABLE_USERNAME",
|
|
13
|
+
"password": "ALTERTABLE_PASSWORD",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@configspec
|
|
18
|
+
class AltertableClientConfiguration(CustomDestinationClientConfiguration):
|
|
19
|
+
"""Falls back to the `ALTERTABLE_*` environment variables after dlt's own providers,
|
|
20
|
+
so a preconfigured environment needs no explicit destination configuration."""
|
|
21
|
+
|
|
22
|
+
host: str | None = None
|
|
23
|
+
catalog: str | None = None
|
|
24
|
+
dataset_name: str | None = None
|
|
25
|
+
username: str | None = None
|
|
26
|
+
password: TSecretStrValue | None = None
|
|
27
|
+
port: int | None = None
|
|
28
|
+
tls: bool | None = None
|
|
29
|
+
compute_size: str | None = None
|
|
30
|
+
|
|
31
|
+
def on_resolved(self) -> None:
|
|
32
|
+
for parameter, env_var in ENV_FALLBACKS.items():
|
|
33
|
+
value = getattr(self, parameter) or os.environ.get(env_var)
|
|
34
|
+
if not value:
|
|
35
|
+
raise ConfigurationValueError(
|
|
36
|
+
f"{parameter} is not configured: pass {parameter}= to altertable(), set "
|
|
37
|
+
f"destination.altertable.{parameter} in .dlt/secrets.toml, or export "
|
|
38
|
+
f"{env_var}."
|
|
39
|
+
)
|
|
40
|
+
setattr(self, parameter, value)
|
|
41
|
+
if self.port is None:
|
|
42
|
+
self.port = int(os.environ.get("ALTERTABLE_PORT", "443"))
|
|
43
|
+
if self.tls is None:
|
|
44
|
+
self.tls = os.environ.get("ALTERTABLE_TLS", "true").lower() != "false"
|
|
45
|
+
if self.compute_size is None:
|
|
46
|
+
self.compute_size = os.environ.get("ALTERTABLE_COMPUTE_SIZE", "XS")
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def base_url(self) -> str:
|
|
50
|
+
return f"{'https' if self.tls else 'http'}://{self.host}:{self.port}"
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def basic_auth(self) -> tuple[str, str]:
|
|
54
|
+
return cast(tuple[str, str], (self.username, self.password))
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from typing import cast
|
|
2
|
+
|
|
3
|
+
import dlt
|
|
4
|
+
from dlt.common.destination.exceptions import DestinationTerminalException
|
|
5
|
+
from dlt.common.schema import TTableSchema
|
|
6
|
+
from dlt.common.schema.utils import (
|
|
7
|
+
get_columns_names_with_prop,
|
|
8
|
+
get_dedup_sort_tuple,
|
|
9
|
+
has_column_with_prop,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
from dlt_altertable.api import post_parquet
|
|
13
|
+
from dlt_altertable.configuration import AltertableClientConfiguration
|
|
14
|
+
from dlt_altertable.table_schema import aligned_parquet, create_or_evolve_table
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def primary_key_columns(table: TTableSchema) -> list[str]:
|
|
18
|
+
return get_columns_names_with_prop(table, "primary_key")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def unsupported_merge_configuration(table: TTableSchema) -> str | None:
|
|
22
|
+
strategy = table.get("x-merge-strategy")
|
|
23
|
+
if strategy not in (None, "upsert"):
|
|
24
|
+
return f"merge strategy {strategy!r}"
|
|
25
|
+
if has_column_with_prop(table, "merge_key"):
|
|
26
|
+
return "merge_key"
|
|
27
|
+
if has_column_with_prop(table, "hard_delete"):
|
|
28
|
+
return "the hard_delete column hint"
|
|
29
|
+
dedup_sort = get_dedup_sort_tuple(table)
|
|
30
|
+
if dedup_sort and dedup_sort[1] != "desc":
|
|
31
|
+
return f"dedup_sort {dedup_sort[1]!r} (the server keeps the highest value, use 'desc')"
|
|
32
|
+
if not primary_key_columns(table):
|
|
33
|
+
return "merge without a primary_key"
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def upsert_params(table: TTableSchema) -> dict[str, str] | None:
|
|
38
|
+
if table.get("write_disposition") != "merge":
|
|
39
|
+
return None
|
|
40
|
+
if unsupported := unsupported_merge_configuration(table):
|
|
41
|
+
raise DestinationTerminalException(
|
|
42
|
+
f"Table {table['name']}: {unsupported} is not supported by the Altertable "
|
|
43
|
+
"destination, which runs merge as a server-side upsert on the primary_key."
|
|
44
|
+
)
|
|
45
|
+
dedup_sort = get_dedup_sort_tuple(table)
|
|
46
|
+
cursor = dedup_sort[0] if dedup_sort else None
|
|
47
|
+
key_columns = [*primary_key_columns(table), *([cursor] if cursor else [])]
|
|
48
|
+
if invalid := [column for column in key_columns if "," in column]:
|
|
49
|
+
raise DestinationTerminalException(
|
|
50
|
+
f"Table {table['name']}: column names {invalid} contain a comma, which the "
|
|
51
|
+
"comma-separated primary_key and cursor_field parameters cannot express."
|
|
52
|
+
)
|
|
53
|
+
params = {"primary_key": ",".join(primary_key_columns(table))}
|
|
54
|
+
if cursor:
|
|
55
|
+
params["cursor_field"] = cursor
|
|
56
|
+
return params
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def upload_mode(table: TTableSchema, table_already_replaced: bool) -> str:
|
|
60
|
+
if table.get("write_disposition") == "replace" and not table_already_replaced:
|
|
61
|
+
return "overwrite"
|
|
62
|
+
return "append"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def replaced_tables() -> list[str]:
|
|
66
|
+
return dlt.current.destination_state().setdefault("replaced_tables", [])
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def evolved_tables() -> list[str]:
|
|
70
|
+
return dlt.current.destination_state().setdefault("evolved_tables", [])
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# batch_size=0 hands each load job a file path, the one branch of dlt's `TDataItems | str` argument.
|
|
74
|
+
@dlt.destination( # ty: ignore[invalid-argument-type]
|
|
75
|
+
name="altertable",
|
|
76
|
+
naming_convention="direct",
|
|
77
|
+
loader_file_format="parquet",
|
|
78
|
+
batch_size=0,
|
|
79
|
+
skip_dlt_columns_and_tables=False,
|
|
80
|
+
max_table_nesting=0,
|
|
81
|
+
loader_parallelism_strategy="table-sequential",
|
|
82
|
+
spec=AltertableClientConfiguration,
|
|
83
|
+
)
|
|
84
|
+
def altertable(
|
|
85
|
+
parquet_file_path: str,
|
|
86
|
+
table: TTableSchema,
|
|
87
|
+
config: AltertableClientConfiguration = dlt.config.value,
|
|
88
|
+
) -> None:
|
|
89
|
+
upsert = upsert_params(table)
|
|
90
|
+
table_name = cast(str, table["name"])
|
|
91
|
+
|
|
92
|
+
already_replaced = replaced_tables()
|
|
93
|
+
already_evolved = evolved_tables()
|
|
94
|
+
mode = upload_mode(table, table_name in already_replaced)
|
|
95
|
+
|
|
96
|
+
if mode != "overwrite" and table_name not in already_evolved:
|
|
97
|
+
if create_or_evolve_table(config, table):
|
|
98
|
+
already_evolved.append(table_name)
|
|
99
|
+
|
|
100
|
+
params = {
|
|
101
|
+
"catalog": cast(str, config.catalog),
|
|
102
|
+
"schema": cast(str, config.dataset_name),
|
|
103
|
+
"table": table_name,
|
|
104
|
+
}
|
|
105
|
+
action = f"loading {config.catalog}.{config.dataset_name}.{table_name}"
|
|
106
|
+
if upsert is not None:
|
|
107
|
+
post_parquet(config, "upsert", params | upsert, parquet_file_path, action)
|
|
108
|
+
else:
|
|
109
|
+
params["mode"] = mode
|
|
110
|
+
with aligned_parquet(parquet_file_path, table) as upload_path:
|
|
111
|
+
post_parquet(config, "upload", params, upload_path, action)
|
|
112
|
+
|
|
113
|
+
if mode == "overwrite":
|
|
114
|
+
already_replaced.append(table_name)
|
|
File without changes
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tempfile
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from typing import cast
|
|
6
|
+
|
|
7
|
+
import pyarrow.parquet as pq
|
|
8
|
+
from dlt.common import logger
|
|
9
|
+
from dlt.common.data_writers.escape import escape_duckdb_literal, escape_postgres_identifier
|
|
10
|
+
from dlt.common.destination.capabilities import DestinationCapabilitiesContext
|
|
11
|
+
from dlt.common.exceptions import TerminalValueError
|
|
12
|
+
from dlt.common.libs.pyarrow import normalize_py_arrow_item
|
|
13
|
+
from dlt.common.normalizers.naming.direct import NamingConvention
|
|
14
|
+
from dlt.common.schema import TTableSchema
|
|
15
|
+
from dlt.common.schema.typing import TColumnSchema
|
|
16
|
+
|
|
17
|
+
from dlt_altertable.api import execute_sql
|
|
18
|
+
from dlt_altertable.configuration import AltertableClientConfiguration
|
|
19
|
+
|
|
20
|
+
SQL_TYPES = {
|
|
21
|
+
"text": "VARCHAR",
|
|
22
|
+
"bigint": "BIGINT",
|
|
23
|
+
"double": "DOUBLE",
|
|
24
|
+
"bool": "BOOLEAN",
|
|
25
|
+
"timestamp": "TIMESTAMP WITH TIME ZONE",
|
|
26
|
+
"date": "DATE",
|
|
27
|
+
"time": "TIME",
|
|
28
|
+
"json": "VARCHAR",
|
|
29
|
+
"binary": "BLOB",
|
|
30
|
+
"decimal": "DECIMAL(38,9)",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def sql_type(column: TColumnSchema) -> str:
|
|
35
|
+
if column["data_type"] == "wei":
|
|
36
|
+
raise TerminalValueError(
|
|
37
|
+
f"Column {column['name']} has type wei, which needs 78 digits while DuckDB "
|
|
38
|
+
"decimals stop at 38."
|
|
39
|
+
)
|
|
40
|
+
if column["data_type"] == "decimal" and (precision := column.get("precision")) is not None:
|
|
41
|
+
return f"DECIMAL({precision},{column.get('scale', 0)})"
|
|
42
|
+
if column["data_type"] == "timestamp" and column.get("timezone") is False:
|
|
43
|
+
return "TIMESTAMP"
|
|
44
|
+
return SQL_TYPES[cast(str, column["data_type"])]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def qualified_table_name(config: AltertableClientConfiguration, table_name: str) -> str:
|
|
48
|
+
return ".".join(
|
|
49
|
+
escape_postgres_identifier(part)
|
|
50
|
+
for part in cast(tuple[str, str, str], (config.catalog, config.dataset_name, table_name))
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def create_table(config: AltertableClientConfiguration, table: TTableSchema) -> None:
|
|
55
|
+
table_name = cast(str, table["name"])
|
|
56
|
+
columns = ", ".join(
|
|
57
|
+
f"{escape_postgres_identifier(name)} {sql_type(column)}"
|
|
58
|
+
for name, column in table["columns"].items()
|
|
59
|
+
)
|
|
60
|
+
execute_sql(
|
|
61
|
+
config,
|
|
62
|
+
"CREATE SCHEMA IF NOT EXISTS "
|
|
63
|
+
f"{escape_postgres_identifier(cast(str, config.catalog))}"
|
|
64
|
+
f".{escape_postgres_identifier(cast(str, config.dataset_name))}",
|
|
65
|
+
)
|
|
66
|
+
execute_sql(
|
|
67
|
+
config,
|
|
68
|
+
f"CREATE TABLE IF NOT EXISTS {qualified_table_name(config, table_name)} ({columns})",
|
|
69
|
+
)
|
|
70
|
+
logger.info(
|
|
71
|
+
f"Created table {config.catalog}.{config.dataset_name}.{table_name} "
|
|
72
|
+
f"with {len(table['columns'])} columns"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def create_or_evolve_table(config: AltertableClientConfiguration, table: TTableSchema) -> bool:
|
|
77
|
+
"""Creating the table from dlt's typed schema keeps column types and later evolution
|
|
78
|
+
deliberate instead of whatever the server would infer from the first file. A table left by
|
|
79
|
+
an earlier load must also gain the columns that dlt's schema evolution added since.
|
|
80
|
+
|
|
81
|
+
Returns whether the lookup found an existing table, the only answer worth caching for the
|
|
82
|
+
rest of the load: a CREATE is never read back to confirm what the table now holds."""
|
|
83
|
+
table_name = cast(str, table["name"])
|
|
84
|
+
rows = execute_sql(
|
|
85
|
+
config,
|
|
86
|
+
"SELECT column_name FROM information_schema.columns "
|
|
87
|
+
f"WHERE table_catalog = {escape_duckdb_literal(config.catalog)} "
|
|
88
|
+
f"AND table_schema = {escape_duckdb_literal(config.dataset_name)} "
|
|
89
|
+
f"AND table_name = {escape_duckdb_literal(table_name)}",
|
|
90
|
+
)
|
|
91
|
+
existing = {row[0] for row in rows}
|
|
92
|
+
if not existing:
|
|
93
|
+
create_table(config, table)
|
|
94
|
+
return False
|
|
95
|
+
for name, column in table["columns"].items():
|
|
96
|
+
if name not in existing:
|
|
97
|
+
execute_sql(
|
|
98
|
+
config,
|
|
99
|
+
f"ALTER TABLE {qualified_table_name(config, table_name)} "
|
|
100
|
+
f"ADD COLUMN IF NOT EXISTS {escape_postgres_identifier(name)} {sql_type(column)}",
|
|
101
|
+
)
|
|
102
|
+
logger.info(
|
|
103
|
+
f"Added column {name} to {config.catalog}.{config.dataset_name}.{table_name}"
|
|
104
|
+
)
|
|
105
|
+
return True
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@contextmanager
|
|
109
|
+
def aligned_parquet(parquet_file_path: str, table: TTableSchema) -> Iterator[str]:
|
|
110
|
+
"""dlt can evolve a load's schema between files, leaving an earlier file narrower than the
|
|
111
|
+
table the load builds, while an append or replace upload must match the table column for
|
|
112
|
+
column. A file that falls short is padded with typed NULL columns into a temporary copy.
|
|
113
|
+
Merge files never come through here, so columns a merge file omits keep their stored values."""
|
|
114
|
+
if pq.read_schema(parquet_file_path).names == list(table["columns"]):
|
|
115
|
+
yield parquet_file_path
|
|
116
|
+
return
|
|
117
|
+
aligned = normalize_py_arrow_item(
|
|
118
|
+
pq.read_table(parquet_file_path),
|
|
119
|
+
table["columns"],
|
|
120
|
+
NamingConvention(),
|
|
121
|
+
DestinationCapabilitiesContext.generic_capabilities(),
|
|
122
|
+
)
|
|
123
|
+
with tempfile.TemporaryDirectory() as aligned_dir:
|
|
124
|
+
aligned_path = os.path.join(aligned_dir, "aligned.parquet")
|
|
125
|
+
pq.write_table(aligned, aligned_path)
|
|
126
|
+
yield aligned_path
|