SOIL - Structured Observation Ingestion Library
Version: 0.3.0 · Python: ≥ 3.10 · PyPI:
soil-etl
SQL-first ETL package for importing Canadian forestry soil datasets into the ForSITE PostGIS database model, built on the OGC Observations, Measurements & Samples specification. DuckDB performs reproducible preprocessing in saved SQL; Parquet carries validated relational data to the importer. Existing flat-table/YAML pipelines remain supported.
Acknowledgements
| Project Partners |
|---|
This project was developed through joint funding provided by Agriculture and Agri-Food Canada (AAFC) under
the CSBO program and Natural Resources Canada (NRCan) for
the ForSITE-Soil degradation project.
The code developed as part of this project includes contributions from:
Installation
pip install soil-etl
DuckDB reads CSV/Parquet directly, XLSX through its excel extension and GPKG/SHP through
spatial. Extensions must be provisioned explicitly; legacy XLS needs an optional adapter.
The pandas Excel adapter is available with pip install "soil-etl[excel]".
Excel is never an export unless explicitly requested. Error reports and enabled diagnostic exports default
to Parquet, including for Excel inputs. See standardization and migration.
The current nrcan-etl-toolbox dependency still installs openpyxl transitively.
The SQL-first prepared pipeline loads sources natively in
DuckDB and prepares relational Parquet entities with executable geometry, enum, unit and
lineage contracts before staging. Generated project agents follow this preprocessing workflow;
existing flat-Parquet/YAML imports remain supported.
import_prepared_bundle reuses the YAML path's metadata/association resolution and transactional
tmp-table persistence, with an offline dry-run default and no external tmp-to-final transfer.
Or with Poetry:
poetry add soil-etl
Quick Start
SQL-first pipeline (recommended)
Create a project with soil-etl start-project my-soil-imports, install its dependencies and
run the following agent prompts one at a time:
| Stage | Prompt | Output |
|---|---|---|
| 1 | /1-create-data-dictionary |
Evidence-based source dictionary |
| 2 | /2-interpret-soil-source |
Scientific interpretation and human-reviewed decisions |
| 3 | /3-load-sources |
Raw DuckDB loading SQL, checks and checkpoint |
| 4 | /4-standardize-source |
Approved standardization SQL, checks and checkpoint |
| 5 | /5-prepare-data |
Relational preparation SQL and validated Parquet bundle |
| 6 | /6-build-import-runner |
Reviewed metadata, import runner and offline dry run |
Sources -> DuckDB raw -> standardized -> prepared -> Parquet bundle
|
import_prepared_bundle(dry_run=True)
|
Explicitly authorized real import
|
ForSITE metadata + staging -> tmp_data_import
Each stage stops at its review gate. Version the SQL and orchestrator, not source data or
generated artifacts. Loading/standardization checkpoints are project-local prefix-run records;
stage 5 replays the full sequence with run_prepared_pipeline before publishing a new bundle
directory and manifest.json. The full-pipeline API does not support incomplete phase schemas.
The saved sequence is 01_load_raw.sql, 02_standardize.sql, 03_prepare_locations.sql,
04_prepare_features.sql, 05_prepare_relationships.sql, 06_prepare_observations.sql,
07_prepare_results.sql and 08_validate.sql, plus phase-specific checks.
Preparation enforces POINTZ/EPSG:3979 with documented Z/vertical reference, enum keys,
property/unit/method contracts, lineage and exactly one result per observation.
Missing scientific evidence blocks the relevant gate; agents never approve their own decisions.
Adapt pipelines/prepare_example_dataset.py and pipelines/import_prepared_example.py
in the generated project. The importer accepts the same ProjectDataMeta graph as the YAML
path: projects/subprojects, partners, datasets, stewards and associations.
Its default dry run is offline; real imports are atomic and stop at tmp_data_import.
External tmp-to-final transfer functions are never invoked.
See the workflow and review gates, prepared pipeline API and project template.
Flat-table/YAML pipeline (compatibility)
from pathlib import Path
from soil_etl.yaml_mapper import YamlDatasetMapper
mapper = YamlDatasetMapper(
config_path=Path("my_config.yaml"),
data_file_path=Path("data.parquet"),
)
metrics = mapper.import_data(
dry_run=True,
database_connection_string="postgresql+psycopg2://user:password@host:5432/database",
)
print(metrics)
Flat-table pipelines use YamlDatasetMapper; relational bundles use import_prepared_bundle
without a YAML mapping. Do not pass a bundle directory to the YAML mapper or repeat DuckDB
transformations in bindings. The generated project provides /build-yaml-runner-compatibility
for an existing validated flat Parquet table.
Canonical imports
from soil_etl.yaml_mapper import YamlDatasetMapper
from soil_etl.bindings import Binding, FromColumn
from soil_etl.db import ImportationInterface
Boilerplate - Scaffolding for the new project
The fastest way to start a new import project is to create a ready-to-use project from the packaged template. It creates a complete, self-contained project:
- saved DuckDB loading, standardization, preparation and validation SQL;
- preparation/import runners and flat-table/YAML compatibility examples;
- Hydra DB configuration and an
.env.examplefor later authorized writes; - agents, six ordered prompts, skills and embedded knowledge under
.github/, with entrypoints for Copilot, OpenCode and Claude Code.
From the command line
# Scaffold into a new subfolder
soil-etl start-project my-soil-imports
# ...or into the current directory
soil-etl start-project
# Options
soil-etl start-project my-soil-imports --dest ./projects --overwrite
Equivalent module invocation:
python -m soil_etl start-project my-soil-imports
From Python
import soil_etl
soil_etl.start_project("my-soil-imports") # into a new subfolder
soil_etl.start_project() # into the current directory
soil_etl.start_project(name="my-soil-imports", overwrite=True)
Generated project layout
my-soil-imports/
+-- pyproject.toml # depends on soil-etl
+-- .env.example # env vars (DB_CONN, etc.)
+-- .gitignore
+-- AGENTS.md # agent rules for any tool (Copilot, OpenCode, Claude Code)
+-- CLAUDE.md # Claude Code entry point (imports AGENTS.md)
+-- opencode.json, .opencode/ # OpenCode adapter
+-- configs/
| +-- configs.yaml # Hydra root (selects db: local)
| +-- db/
| | +-- base_con.yaml
| | +-- local.yaml
+-- data/
| +-- <project>/ # sources, phase checkpoints, Parquet bundles - not tracked
+-- pipelines/
| +-- <project>/ # dataset dictionary, interpretation and adapted runners/SQL
| +-- prepare_example_dataset.py # full saved-SQL preparation scaffold
| +-- import_prepared_example.py # metadata graph and offline prepared import
| +-- sql/prepared_example/ # ordered 01-08 SQL scaffold
| +-- import_example_dataset.py # flat-table/YAML compatibility runner
| +-- example_dataset.yaml # compatibility YAML config
+-- .github/ # Copilot agent + embedded knowledge
+-- agents/ # soil-etl-pipeline agent, specialists, read-only reviewers
+-- prompts/ # ordered stages /1- to /6-, compatibility and review utilities
+-- instructions/ # file-scoped workflow and safety rules
+-- knowledge/ # workflow, prepared contracts, DB model, enums, YAML reference
+-- skills/ # workflow skills (dictionary, interpretation, standardization)
Next steps after boilerplate exec.:
cd my-soil-imports
poetry install # installs soil-etl
poetry run python pipelines\prepare_example_dataset.py --help
Start with /1-create-data-dictionary; adapt the example's scientific assumptions only
from reviewed evidence. Preprocessing and offline dry runs need no ForSITE credentials.
Configure .env only for a later explicitly authorized real import.
Maintainers: the editable source of the template lives in
project-template/at the repo root and is synced into the packaged copy (src/soil_etl/_project_template/) withpython scripts/sync_template.py(use--checkin CI to detect drift).
Database Connection
Connection resolution priority (first non-null wins):
- Explicit
database_connection_stringargument toimport_data() DB_CONNenvironment variable- Hydra config directory (
database_config_path/CONFIG_PATHenv var)
# Option 1 - direct connection string
mapper.import_data(
database_connection_string="postgresql+psycopg2://user:password@host:5432/database",
database_engine_kwargs={"pool_size": 10, "pool_pre_ping": True},
)
# Option 2 - Hydra config files
mapper.import_data(
database_config_path="configs",
database_config_name="configs.yaml",
)
# Option 3 - environment variables
import os
os.environ["DB_CONN"] = "postgresql+psycopg2://user:password@host:5432/database"
mapper.import_data()
Environment variables recognized:
| Variable | Description |
|---|---|
DB_CONN |
Full SQLAlchemy connection string |
DB_USER |
Database username (used alongside Hydra config) |
DB_PASSWORD |
Database password (used alongside Hydra config) |
CONFIG_PATH |
Hydra config directory path |
IMPORT_BATCH_SIZE |
Override batch size for this run (positive integer) |
EXPORT_RETREATED_DATAFRAME |
Export transformed DataFrame to *_retreated.parquet (1/true/yes) |
import_data() Signature
mapper.import_data(
error_file_path=Path("errors.parquet"), # defaults to <dataset_title>_ERROR.parquet
dry_run=False, # True: extract + validate only, no DB writes
database_connection_string="postgresql+...",
database_config_path="configs",
database_config_name="configs.yaml",
database_engine_kwargs={"pool_size": 10},
) -> ImportRunMetrics
Returns an ImportRunMetrics dataclass:
@dataclass(frozen=True)
class ImportRunMetrics:
rows_processed: int
error_rows: int
generic_results: int
feature_relationships: int
sample_information: int
batches: int
batch_size: int
dry_run: bool
extract_seconds: float
persist_seconds: float
total_seconds: float
YAML Configuration
For flat-table compatibility imports, YAML defines standardized-table reading parameters, project metadata, feature of interest hierarchy, observations and results. SQL-first relational bundles do not require this mapping.
Reference files (packaged):
| File | Purpose |
|---|---|
src/soil_etl/yaml_mapper/dummy_config_file.yaml |
Fully-documented boilerplate with all options |
src/soil_etl/yaml_mapper/template.yaml |
Real-world example with YAML anchors |
src/soil_etl/yaml_mapper/examples/on_master.yaml |
Province-specific example |
examples/configs/example_config.yaml |
Additional annotated example |
For full documentation of the YAML format, see docs/README_yaml_format_en.md.
Top-level sections
source: # standardized-table reading parameters
format: parquet
export_retreated_dataframe: false
import_batch_size: 1000 # Rows per DB batch (default: 5000)
project: # Project metadata (strategy, name, abbrev, province, type...)
partners: # Partner organizations
stewards: # Data steward contacts
feature_relationships: # Optional parent-child FOI hierarchies (e.g. ProfileElement -> Sample)
sample_information: # Optional sample metadata (type and dimensions)
profile_elements: # Soil horizons/layers: depth bounds + designation on a PROFILE feature
observations: # v2: each observation carries one nested result (1:1)
v2 data model: the pipeline targets
om_observation_v2/om_result_v2/profile_element. Declare anobservations:list where each observation carries exactly one nestedresult:(1:1). The observed property (element_name) lives on the observation. The observationtypefield is deprecated/ignored. Depth bounds live onprofile_elements(aPROFILEfeature of interest), not on the sample; a profile element can own an observation or be the parent of aSAMPLE. Soil horizons/layers are modeled withprofile_elements(aPROFILEFOI carrying depth bounds + designation) with observations attached, following the chainFOI > Profile > Observation(v2) > Result(v2)(orFOI > Profile > Sample > [FOI/Profile/Sample relations] > Observation(v2) > Result(v2)). The former root keysresults:/horizon_results:have been removed (rejected at load time). See docs/README_yaml_format_en.md.
Python Subclass (advanced)
When YAML alone cannot express the required logic, subclass YamlDatasetMapper and override properties:
from pathlib import Path
from soil_etl.yaml_mapper import YamlDatasetMapper
from soil_etl.model_bindings import FeatureOfInterestBinding
class MyMapper(YamlDatasetMapper):
@property
def _feature_of_interest(self) -> FeatureOfInterestBinding:
# custom logic here
...
mapper = MyMapper(
config_path=Path("my_config.yaml"),
data_file_path=Path("data.parquet"),
)
mapper.import_data(database_connection_string="postgresql+psycopg2://...")
See examples/subclass_runner.py for a complete example.
Development
pip install poetry
poetry install --with dev,test
poetry run pytest tests
Tests use testcontainers with postgis/postgis:17-3.4 - Docker must be running.
Linting & formatting
poetry run black src tests
poetry run ruff check src tests
poetry run isort src tests
Build & Publish
python -m build
twine check dist/*
twine upload dist/*
Links
- Repository: gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl
- Issues: soil-etl/issues
- YAML format reference: docs/README_yaml_format_en.md
- Testing guide: docs/testing.md
- Project template: project-template/README.md
- SQL-first workflow: six stages and review gates
- Prepared pipeline API: docs/PREPARED_PIPELINE.md
Metadata
Release files for soil-etl 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| soil_etl-0.3.0.tar.gz | 333.3 kB | Without provenance | Details for soil_etl-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| soil_etl-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for soil_etl-0.3.0-py3-none-any.whl |
Total release size: 817.5 kB
Release files / soil_etl-0.3.0.tar.gz
| Download URL | soil_etl-0.3.0.tar.gz |
|---|---|
| Size | 333.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
edac848aa054a46cdbe2d2ecd39500cdf5466990fa99be82d83a4363f8f979e4
|
|
BLAKE2b-256 checksum How to use checksums |
48ad3fb4ff6ce76d0d3f958a9f05352f9e7d17094431c663a0776c4ab0af99bf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Release files / soil_etl-0.3.0-py3-none-any.whl
| Download URL | soil_etl-0.3.0-py3-none-any.whl |
|---|---|
| Size | 484.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
27221b37550e77b1a47c55a6548351c86d961a87c8b3985e8aa9070123fa9db0
|
|
BLAKE2b-256 checksum How to use checksums |
eadbd4bd841aab9e856aa43ceab6808f7d48f7933dedbe653f3ca0888bbe0a67
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Security for soil-etl 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.