Skip to main content

sqldim

SQL-first dimensional modelling for Python — star schemas, graph traversals, and a full data-quality stack in one library.

sqldim lets you define Kimball-style dimensions and facts once, then use them as:

  • Relational tables — BI-ready star schemas with surrogate keys, SCD versioning, and grain validation.
  • Graph structures — project any star schema as a vertex/edge graph and traverse it via Recursive CTEs.
  • Contract-governed pipeline layers — enforce schema, freshness, value ranges, and row-count SLAs at every Bronze→Silver→Gold boundary.

No row-by-row Python loops. No separate graph database. No third-party orchestrator required.


Why sqldim?

Pain point How sqldim solves it
Slow SCD processing Vectorized change detection via Narwhals across Polars, Pandas, and DuckDB
Manual load ordering Topological dependency resolution — dimensions always load before facts
Graph requires separate DB Dual-paradigm: dim → vertex, fact → edge, traversed with Recursive CTEs
Messy incremental loads Purpose-built lazy loaders stay in DuckDB until materialization
Ad-hoc data quality Schema contracts, freshness rules, and quality gates at every layer boundary
Complex multi-CTE queries Question Algebra with semiring optimisation — minimum-CTE SQL emission
Scattered observability OTel-compatible tracing + P1–P4 alert routing built in

Installation

# Core (SQLModel, DuckDB, Narwhals included)
pip install sqldim

# Streaming sources (Kafka + Kinesis + CDC)
pip install "sqldim[streaming]"

# Individual extras
pip install "sqldim[kafka]"       # Kafka & CDC (confluent-kafka + Polars)
pip install "sqldim[kinesis]"     # Kinesis (boto3 + Polars)
pip install "sqldim[cdc]"         # Change Data Capture via Debezium/Kafka
pip install "sqldim[otel]"        # OpenTelemetry exporter
pip install "sqldim[lineage]"     # OpenLineage data lineage bus

Requires Python 3.11+.


Quick Start

import asyncio
from sqlmodel import create_engine
from sqldim import (
    DimensionModel, FactModel, SCD2Mixin,
    DimensionalLoader, AsyncDimensionalSession,
)

# 1. Define a slowly-changing dimension (SCD Type 2)
class User(DimensionModel, SCD2Mixin, table=True):
    __tablename__ = "dim_user"
    __natural_key__ = ["email"]
    email: str
    name: str
    plan_tier: str   # "free" → "pro" creates a new SCD2 row automatically

# 2. Define a transaction fact
class Order(FactModel, table=True):
    __tablename__ = "fact_order"
    __natural_key__ = ["order_id"]
    order_id: str
    user_email: str   # resolved to User surrogate key automatically
    amount: float
    ordered_at: str

# 3. Load — topological order resolved automatically
engine = create_engine("duckdb:///my_dw.duckdb")

async def main():
    async with AsyncDimensionalSession(engine) as session:
        loader = DimensionalLoader(session, models=[User, Order])

        loader.register(User, source=[
            {"email": "alice@example.com", "name": "Alice", "plan_tier": "free"},
            {"email": "bob@example.com",   "name": "Bob",   "plan_tier": "pro"},
        ])
        loader.register(Order, source=[
            {"order_id": "ORD-1", "user_email": "alice@example.com",
             "amount": 29.99, "ordered_at": "2026-01-15"},
            {"order_id": "ORD-2", "user_email": "bob@example.com",
             "amount": 49.99, "ordered_at": "2026-01-16"},
        ], key_map={"user_email": (User, "email")})

        await loader.run()

asyncio.run(main())

User gets full SCD Type 2 tracking (valid_from, valid_to, is_current). Order has its foreign key resolved to User's surrogate key. Dimensions always load first — no manual ordering required.


Feature Overview

SCD Engine

  • SCD Types 1, 2, 3, and 6 — pick the right strategy per attribute, or mix strategies in a single model (Hybrid SCD)
  • Vectorized change detection via NarwhalsSCDProcessor — no Python loops over rows
  • DimensionalLoader resolves surrogate-key lookups across dimension boundaries via SKResolver
  • Seven lazy loaders stay in DuckDB memory until you explicitly materialize:
Loader Use case
LazyTransactionLoader Transaction-grain incremental loads
LazySnapshotLoader Periodic snapshots (e.g. daily balance)
LazyAccumulatingLoader Accumulating snapshots (pipeline stages)
LazyCumulativeLoader Running totals / watermarks
LazyBitmaskLoader L7/L28/L90 activity flags in 32-bit integers
LazyArrayMetricLoader Array-encoded metric histories
LazyEdgeProjectionLoader Graph edge projection into fact tables

Dimensional Graph Model (DGM)

A complete typed query algebra that unifies dimensional analysis and graph traversal:

Single-query layer — DGMQuery

A three-band query model maps directly to the SQL evaluation pipeline:

Q = B1 (context / WHERE)  ∘  B2? (aggregation / HAVING)  ∘  B3? (window / QUALIFY)
from sqldim.core.query.dgm import DGMQuery, PropRef, AggRef, VerbHop, ScalarPred

q = (
    DGMQuery()
    .anchor("sale_fact", "s")
    .path_join(VerbHop("s", "placed", "c",
                       table="customer_dim",
                       on="c.customer_id = s.customer_id"))
    .where(ScalarPred(PropRef("s", "year"), "=", 2024))
    .group_by("c.region")
    .agg(total_rev="SUM(s.revenue)", n="COUNT(*)")
    .having(ScalarPred(AggRef("n"), ">=", 3))
)
print(q.to_sql())

Question Algebra — QuestionAlgebra

Compose multiple DGMQuery instances into a CTE chain using five operators — UNION, INTERSECT, EXCEPT, WITH, and JOIN:

from sqldim.core.query.dgm import QuestionAlgebra, ComposeOp, DGMPredicateBDD, BDDManager

alg = QuestionAlgebra()
alg.add("retail",  DGMQuery().anchor("sale_fact", "s").where(retail_pred))
alg.add("premium", DGMQuery().anchor("sale_fact", "s").where(premium_pred))
alg.compose("retail", ComposeOp.UNION, "premium", name="all_sales")

# Minimise: eliminate redundant CTEs via semiring laws
bdd = DGMPredicateBDD(BDDManager())
minimal = alg.minimize(bdd)
print(minimal.to_sql(final="all_sales"))

Query optimisation pipeline

Step Function What it does
Semiring minimisation alg.minimize(bdd) Eliminates Q ∪ Q, Q ∩ Q, absorbed/subsumed CTEs
Common Sub-expression Elimination apply_cse(alg, bdd) Shares identical WHERE predicates into __cse_* CTEs

The minimiser is a tight lower bound: the resulting CTE count equals the minimum number of CTEs needed to represent the same query family.

Graph operations — TraversalEngine

  • Project any star schema as a directed graph (dim → vertex, fact → edge)
  • TraversalEngine executes multi-hop path queries via Recursive CTEs
  • VerbHop, BridgeHop, PathPred, Compose for declarative path navigation

Sources

Source Class
Parquet file ParquetSource / ParquetStreamSource
CSV file CSVSource / CSVStreamSource
DuckDB table / query DuckDBSource
PostgreSQL PostgreSQLSource
Delta Lake DeltaSource
Arbitrary SQL SQLSource
Kafka KafkaSource
Kinesis KinesisSource
CDC (Debezium) DebeziumSource
dlt pipelines DltSource

Sinks

Sink Class
DuckDB (in-process) DuckDBSink
MotherDuck (cloud DuckDB) MotherDuckSink
PostgreSQL PostgreSQLSink
Parquet ParquetSink
Delta Lake DeltaLakeSink
Apache Iceberg IcebergSink

Data Quality & Governance

  • Data contracts — DataContract + ContractEngine enforce schema, null rates, value ranges, SCD2 invariants, freshness, and row-count deltas (spec)
  • Quality gates — QualityGate / GateResult block medallion-layer promotion on contract breach
  • SLA tracking — SLASpec + ContractVersion for schema evolution with ChangeKind diff reporting

Medallion Architecture

Bronze  →  Silver  →  Gold
              ↑           ↑
          QualityGate  QualityGate
  • MedallionRegistry registers models per Layer (BRONZE / SILVER / GOLD)
  • SilverBuildOrder resolves topological load order across all layers automatically
  • Quality gates at both Bronze→Silver and Silver→Gold boundaries

Observability & Notifications

  • OTelCollector — OTel-compatible start_span + record_metric at every pipeline stage ([otel] extra)
  • NotificationRouter — P1–P4 severity routing to Slack, PagerDuty, Jira, Email, or webhooks (spec)
  • Data lineage emission via [lineage] extra (OpenLineage-compatible events)

Other Capabilities

Feature Details
Semantic time-travel Fluent AS OF join resolution via the semantic layer (guide)
Bitmask retention L7/L28/L90 activity flags packed in 32-bit integers (guide)
CLI sqldim command for schema inspection, migration, and contract validation (reference)
Config SqldimConfig for memory limits, spill thresholds, and batch sizes (reference)

Documentation

Tutorials & Guides

Topic Link
Getting started Tutorial
Lazy loaders (DuckDB-first) Guide
Vectorized ETL deep-dive Guide
Semantic layer & time-travel Guide
Big data scaling Guide

Patterns

Topic Link
Dual-paradigm (relational + graph) Pattern
Hybrid SCD (mixed strategies) Pattern

Features

Topic Link
Dimensional Graph Model (DGM) Spec
Data contracts & governance Spec
Medallion layers Spec
Observability (OTel) Spec
Notifications & alerting Spec
Feature dependency graph Diagram

Reference

Topic Link
Full API surface Reference
Dimensions & model base classes Reference
Fact types (Kimball) Reference
Dimensional loader Reference
SCD processors Reference
Schema graph Reference
Sinks Reference
Sources Reference
Session Reference
CLI Reference
Config Reference
Lineage Reference
Exceptions Reference
Example datasets Reference

Architecture

Topic Link
System overview Overview
SCD engine design Design
Schema evolution policy Design
Graph analytics roadmap Roadmap
Recursive hierarchy dimensions Design
Late-arriving dimensions Design
Physical partitioning & bucketing Design
Analytical indexing strategy Design
Benchmark suite Design

Contributing

We welcome contributions! See CONTRIBUTING.md for setup instructions, coding standards, and the PR workflow.

License

This project is developed by Bruno L. Netto.

Metadata

Release files for sqldim 2.0.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 sqldim 2.0.1
File Size Uploaded Provenance Actions
sqldim-2.0.1.tar.gz 1.3 MB Without provenance Details for sqldim-2.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sqldim 2.0.1
File Interpreter ABI Platform Actions
sqldim-2.0.1-py3-none-any.whl Python 3 none any Details for sqldim-2.0.1-py3-none-any.whl

Total release size: 2.0 MB

Release files / sqldim-2.0.1.tar.gz

Download URL sqldim-2.0.1.tar.gz
Size 1.3 MB
Tags Source
SHA-256 checksum
How to use checksums
3e115352f2e4610b7c0dffb1715b83a5e411e4d3c7420bc8735fc774c859ec4b
BLAKE2b-256 checksum
How to use checksums
045cd3c2b022b241f06966376ba5afc480ca3b8a9668668599704f8c17e3116b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / sqldim-2.0.1-py3-none-any.whl

Download URL sqldim-2.0.1-py3-none-any.whl
Size 736.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c93981e0f33b2c1f5ee1e7c1c03df08030473cde10a46c00b48cd2836aada046
BLAKE2b-256 checksum
How to use checksums
3ba317378b2a61482a8e21c6badb7083856acfe1038938f7619f16e71e64ca2b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for sqldim 2.0.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