Pipeline¶
The Pipeline class is the main entry point for building and running ETL pipelines.
Overview¶
from pycharter import Pipeline, HTTPExtractor, FileLoader, Rename
# Build with pipe operator
pipeline = (
Pipeline(HTTPExtractor(url="https://api.example.com/data"))
| Rename({"old": "new"})
| FileLoader(path="output.json")
)
# Run
result = await pipeline.run()
API Reference¶
Pipeline
¶
Pipeline(
extractor: Extractor | None = None,
transformers: list[Transformer] | None = None,
loader: Loader | None = None,
context: PipelineContext | None = None,
name: str | None = None,
transform_config: (
dict[str, Any] | list[dict[str, Any]] | None
) = None,
extract_validation_config: dict[str, Any] | None = None,
load_validation_config: dict[str, Any] | None = None,
quality_checks_config: (
list[dict[str, Any]] | None
) = None,
settings: dict[str, Any] | None = None,
base_dir: Path | None = None,
extract_config_raw: dict[str, Any] | None = None,
load_config_raw: dict[str, Any] | None = None,
)
ETL Pipeline with | operator for chaining transformers.
Programmatic usage
pipeline = ( ... Pipeline(HTTPExtractor(url="...")) ... | Rename({"old": "new"}) ... | PostgresLoader(...) ... ) result = await pipeline.run()
Config-driven usage (variables and settings are first-class in all methods): >>> # From explicit files (extract, load, transform, variables, settings) >>> pipeline = Pipeline.from_config_files( ... "configs/extract.yaml", "configs/load.yaml", ... variables={"API_KEY": "secret"} ... ) >>> >>> # From directory (extract.yaml, load.yaml, optional transform/settings/variables.yaml) >>> pipeline = Pipeline.from_config_dir("pipelines/users/") >>> >>> # From single file (all sections in one YAML) >>> pipeline = Pipeline.from_config_file("pipelines/users/pipeline.yaml") >>> >>> result = await pipeline.run()
Async execution
run() is async. From a script use asyncio.run(): asyncio.run(pipeline.run()) From an async context (FastAPI, Jupyter) await directly: result = await pipeline.run() See pycharter/etl_generator/ASYNC_AND_EXECUTION.md for details.
Source code in src/pycharter/etl_generator/pipeline.py
__or__
¶
Chain transformer or set loader using | operator.
Source code in src/pycharter/etl_generator/pipeline.py
run
async
¶
run(
dry_run: bool = False,
error_context: ErrorContext | None = None,
**params: Any
) -> PipelineResult
Run the ETL pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dry_run
|
bool
|
If True, extract and transform but do not load. |
False
|
error_context
|
ErrorContext | None
|
Optional error context for handling failures. If not set, uses the default from get_error_context(). In STRICT mode, extraction or load failures raise. In LENIENT/COLLECT mode, errors are logged and appended to result.errors. |
None
|
**params
|
Any
|
Passed to extractor.extract() and loader.load(). |
{}
|
Returns:
| Type | Description |
|---|---|
PipelineResult
|
PipelineResult with counts and any errors. |
Source code in src/pycharter/etl_generator/pipeline.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
from_config_dir
classmethod
¶
from_config_dir(
directory: str | Path,
variables: str | Path | dict[str, str] | None = None,
settings: str | Path | dict[str, Any] | None = None,
*,
validate: bool = True,
name: str | None = None,
load_defaults: dict[str, Any] | None = None,
base_dir: Path | None = None
) -> "Pipeline"
Create pipeline from a directory (extract.yaml, load.yaml, etc.).
Config at same level: directory supplies extract, load, transform, variables, settings. Optional variables/settings args override or supplement directory files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Path to directory with extract.yaml, load.yaml, etc. |
required |
variables
|
str | Path | dict[str, str] | None
|
Optional path or dict; merged with directory variables.yaml (caller wins). |
None
|
settings
|
str | Path | dict[str, Any] | None
|
Optional path or dict; merged with directory settings.yaml (caller wins). |
None
|
validate
|
bool
|
If True, validate configs. |
True
|
name
|
str | None
|
Optional pipeline name (default: directory name). |
None
|
load_defaults
|
dict[str, Any] | None
|
Merged under load config (load wins). |
None
|
base_dir
|
Path | None
|
Base for relative paths (default: directory). |
None
|
Source code in src/pycharter/etl_generator/pipeline.py
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 | |
from_config_files
classmethod
¶
from_config_files(
extract: str | Path | dict[str, Any],
load: str | Path | dict[str, Any],
transform: (
str
| Path
| dict[str, Any]
| list[dict[str, Any]]
| None
) = None,
variables: str | Path | dict[str, str] | None = None,
settings: str | Path | dict[str, Any] | None = None,
*,
validate: bool = True,
name: str | None = None,
load_defaults: dict[str, Any] | None = None,
base_dir: Path | None = None
) -> "Pipeline"
Create pipeline from explicit file paths or dictionaries.
Config inputs (same level): extract, load, transform, variables, settings. Each can be a path or dict; variables are used to resolve ${VAR} in others.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extract
|
str | Path | dict[str, Any]
|
Path or dict for extract config. |
required |
load
|
str | Path | dict[str, Any]
|
Path or dict for load config. |
required |
transform
|
str | Path | dict[str, Any] | list[dict[str, Any]] | None
|
Optional path or dict/list for transform config. |
None
|
variables
|
str | Path | dict[str, str] | None
|
Optional path or dict for ${VAR} substitution. |
None
|
settings
|
str | Path | dict[str, Any] | None
|
Optional path or dict for shared settings (DLQ, metadata_store, etc.). |
None
|
validate
|
bool
|
If True, validate configs against schemas. |
True
|
name
|
str | None
|
Optional pipeline name. |
None
|
load_defaults
|
dict[str, Any] | None
|
Merged under load config (load wins). |
None
|
base_dir
|
Path | None
|
Base for relative paths; default from extract path when possible. |
None
|
Source code in src/pycharter/etl_generator/pipeline.py
from_config_file
classmethod
¶
from_config_file(
path: str | Path,
*,
variables: dict[str, str] | None = None,
validate: bool = True,
name: str | None = None,
load_defaults: dict[str, Any] | None = None,
base_dir: Path | None = None
) -> "Pipeline"
Create pipeline from a single config file (extract, load, transform, variables, settings as keys).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to pipeline YAML. |
required |
variables
|
dict[str, str] | None
|
Optional overlay; merged with file variables (caller wins). |
None
|
validate
|
bool
|
If True, validate config. |
True
|
name
|
str | None
|
Override name from file. |
None
|
load_defaults
|
dict[str, Any] | None
|
Merged under load config (load wins). |
None
|
base_dir
|
Path | None
|
Base for relative paths (default: path.parent). |
None
|
Source code in src/pycharter/etl_generator/pipeline.py
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 | |
Factory Methods¶
from_config_dir¶
Load pipeline from a directory containing extract.yaml, transform.yaml, and load.yaml:
from_config_files¶
Load from explicit file paths:
pipeline = Pipeline.from_config_files(
extract="configs/extract.yaml",
transform="configs/transform.yaml", # Optional
load="configs/load.yaml",
variables={"API_KEY": "secret"}
)
from_config_file¶
Load from a single combined config file:
PipelineResult¶
PipelineResult
dataclass
¶
PipelineResult(
success: bool = True,
rows_extracted: int = 0,
rows_transformed: int = 0,
rows_loaded: int = 0,
rows_failed: int = 0,
rows_quarantined_extract: int = 0,
rows_quarantined_load: int = 0,
validation_errors_extract: list[str] = list(),
validation_errors_load: list[str] = list(),
start_time: datetime | None = None,
end_time: datetime | None = None,
duration_seconds: float | None = None,
batches_processed: int = 0,
batch_results: list[BatchResult] = list(),
errors: list[str] = list(),
pipeline_name: str | None = None,
run_id: str | None = None,
quality_report: Any = None,
lineage_events: list[dict[str, Any]] = list(),
)
Complete result from running an ETL pipeline.
Examples¶
Basic Pipeline¶
import asyncio
from pycharter import Pipeline, FileExtractor, FileLoader
pipeline = (
Pipeline(FileExtractor(path="input.json"))
| FileLoader(path="output.json")
)
result = asyncio.run(pipeline.run())
print(f"Loaded {result.rows_loaded} rows")
With Transformations¶
from pycharter import Pipeline, HTTPExtractor, PostgresLoader, Rename, Filter, AddField
pipeline = (
Pipeline(HTTPExtractor(url="https://api.example.com/users"))
| Rename({"userName": "user_name"})
| Filter(lambda r: r.get("active"))
| AddField("processed_at", "now()")
| PostgresLoader(connection_string="...", table="users")
)
Error Handling¶
from pycharter.shared.errors import ErrorMode, ErrorContext
# Collect errors instead of raising
result = await pipeline.run(
error_context=ErrorContext(mode=ErrorMode.COLLECT)
)
if result.errors:
for error in result.errors:
print(f"Error: {error}")
With Variables¶
pipeline = Pipeline.from_config_dir(
"pipelines/users/",
variables={
"API_KEY": os.environ["API_KEY"],
"OUTPUT_PATH": "/data/output.json"
}
)
Message Queue Acknowledgment¶
When a pipeline uses a messaging extractor (Kafka, RabbitMQ, SQS), the pipeline automatically acknowledges each batch after loading:
from pycharter.etl_generator.extractors import KafkaExtractor
pipeline = (
Pipeline(KafkaExtractor(topics=["orders"], consumer_group="etl"))
| Rename({"orderId": "order_id"})
| PostgresLoader(connection_string="...", table="orders")
)
# Pipeline calls extractor.acknowledge() after each batch load
result = await pipeline.run()
# Don't forget to close the consumer
await pipeline.extractor.close()
The pipeline determines success from the LoadResult:
| Scenario | Acknowledge call |
|---|---|
| Load succeeds | acknowledge(batch_index, success=True) |
| Load fails | acknowledge(batch_index, success=False) |
| Dry run | acknowledge(batch_index, success=True) |
| No loader set | acknowledge(batch_index, success=True) |
If acknowledge() raises an exception, it is logged as a warning and the pipeline continues.
Incremental Extraction¶
Track a watermark field across runs so only new/updated records are extracted:
type: database
query: "SELECT * FROM events WHERE updated_at > '${watermark}'"
connection_string: "${DATABASE_URL}"
incremental:
enabled: true
watermark_field: updated_at
initial_value: "2024-01-01"
The pipeline persists the highest watermark value on success and injects it into the next run.
Testing Utilities¶
PyCharter provides mock classes and assertion helpers for testing pipelines without real I/O:
from pycharter import MockExtractor, MockLoader, PipelineTestHarness
# Mock extractor yields fixture data
extractor = MockExtractor(data=[
[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
])
# Mock loader captures what was loaded
loader = MockLoader()
pipeline = Pipeline(extractor) | Rename({"name": "full_name"}) | loader
result = await pipeline.run()
# Assert on captured data
from pycharter import assert_record_count, assert_fields_present
assert_record_count(loader.loaded_data, 2)
assert_fields_present(loader.loaded_data, ["id", "full_name"])