Skip to main content

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

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.example for 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/) with python scripts/sync_template.py (use --check in CI to detect drift).


Database Connection

Connection resolution priority (first non-null wins):

  1. Explicit database_connection_string argument to import_data()
  2. DB_CONN environment variable
  3. Hydra config directory (database_config_path / CONFIG_PATH env 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 an observations: list where each observation carries exactly one nested result: (1:1). The observed property (element_name) lives on the observation. The observation type field is deprecated/ignored. Depth bounds live on profile_elements (a PROFILE feature of interest), not on the sample; a profile element can own an observation or be the parent of a SAMPLE. Soil horizons/layers are modeled with profile_elements (a PROFILE FOI carrying depth bounds + designation) with observations attached, following the chain FOI > Profile > Observation(v2) > Result(v2) (or FOI > Profile > Sample > [FOI/Profile/Sample relations] > Observation(v2) > Result(v2)). The former root keys results: / 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/*

Metadata

Release files for soil-etl 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for soil-etl 0.3.1
File Size Uploaded Provenance Actions
soil_etl-0.3.1.tar.gz 333.3 kB Without provenance Details for soil_etl-0.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for soil-etl 0.3.1
File Interpreter ABI Platform Actions
soil_etl-0.3.1-py3-none-any.whl Python 3 none any Details for soil_etl-0.3.1-py3-none-any.whl

Total release size: 817.4 kB

Release files / soil_etl-0.3.1.tar.gz

Download URL soil_etl-0.3.1.tar.gz
Size 333.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b20c0cc31a8ead55a97753d3fe7a0f78eb6237185e5693e9025b19dfc690835c
BLAKE2b-256 checksum
How to use checksums
e44be9107f9ddf3ff55e66c8d180325f19cd6927dfc08e2930970029fefbf596
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.1-py3-none-any.whl

Download URL soil_etl-0.3.1-py3-none-any.whl
Size 484.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bc68996736126351145b2e6778b5f27546fa18cc4b3b005549ce5b395a24ca81
BLAKE2b-256 checksum
How to use checksums
838bc8407a1bdc7e76edef726f6fafa58a198a15763a2bd8fd604372b2b518cf
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.1

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page