odcr 0.2.0__py3-none-any.whl

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.
odcr/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ """odcr - Open Data Contract Runtime.
2
+
3
+ Enforce ODCS data contracts at ingestion, reconcile source and target,
4
+ and trace every batch from ingestion to consumption. Results and history
5
+ are stored in meta tables inside the platform the data lives in.
6
+ """
7
+
8
+ __version__ = "0.2.0"
9
+
10
+ from .contract import Contract, load_contract # noqa: E402
11
+ from .observe import checkpoint, trace # noqa: E402
12
+ from .reconcile import ReconResult, load_reconciliation, run_reconciliation # noqa: E402
13
+ from .repository import ContractRepository # noqa: E402
14
+ from .runner import RunResult, run_contract # noqa: E402
15
+
16
+ __all__ = [
17
+ "__version__",
18
+ "Contract",
19
+ "load_contract",
20
+ "RunResult",
21
+ "run_contract",
22
+ "ReconResult",
23
+ "load_reconciliation",
24
+ "run_reconciliation",
25
+ "checkpoint",
26
+ "trace",
27
+ "ContractRepository",
28
+ ]
odcr/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,173 @@
1
+ """Adapter registry: every supported platform, its install extra, connection template and test status.
2
+
3
+ `odcr adapters` prints this table; `odcr init --adapter <name>` uses the connection templates.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ from .base import Adapter, UnsupportedCheck, type_matches
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class AdapterInfo:
17
+ name: str
18
+ title: str
19
+ cls: str # "module:Class" inside odcr.adapters
20
+ category: str # embedded | on-premise | cloud | document
21
+ clouds: str
22
+ extra: str | None # pip extra: pip install "odcr[<extra>]"; None = no extra needed
23
+ driver: str # import name of the driver
24
+ tested: str # "ci" = end-to-end in CI on every push; "credentials" = end-to-end when credentials are set
25
+ description: str
26
+ connection: dict[str, Any]
27
+ aliases: tuple[str, ...] = ()
28
+ notes: list[str] = field(default_factory=list)
29
+ where_example: str = "load_id = '{batch_id}'"
30
+
31
+
32
+ ADAPTERS: dict[str, AdapterInfo] = {a.name: a for a in [
33
+ AdapterInfo("duckdb", "DuckDB", "duckdb:DuckDBAdapter", "embedded", "local, MotherDuck", "duckdb", "duckdb",
34
+ "ci", "Embedded analytics database; also checks Parquet/CSV/JSON files directly.",
35
+ {"type": "duckdb", "path": "${DUCKDB_PATH:-odcr.duckdb}"},
36
+ notes=["Check files before loading: physicalName: \"read_parquet('landing/orders/*.parquet')\""]),
37
+ AdapterInfo("files", "Files: ADLS, S3, GCS, local", "files:FilesAdapter", "embedded",
38
+ "local, network shares, Azure ADLS Gen2/Blob, AWS S3, GCP GCS, MinIO", "files", "duckdb", "ci",
39
+ "Checks Parquet, CSV and JSON files where they land, before loading (DuckDB engine).",
40
+ {"type": "files", "storage": "${ODCR_STORAGE:-local}", "account_name": "${AZURE_STORAGE_ACCOUNT:-}",
41
+ "meta_path": "${ODCR_META_PATH:-odcr_meta.duckdb}"},
42
+ aliases=("adls", "azure-storage", "s3", "gcs", "landing", "parquet", "csv"),
43
+ notes=["physicalName is a path or glob: abfss://container@account.dfs.core.windows.net/orders/*.parquet",
44
+ "Authentication: credential chain (Managed Identity, az login, AWS profile) by default; "
45
+ "service principal or keys via environment variables."],
46
+ where_example="load_id = '{batch_id}'"),
47
+ AdapterInfo("sqlite", "SQLite", "sqlite:SQLiteAdapter", "embedded", "local", None, "sqlite3", "ci",
48
+ "Built into Python; ideal for trying odcr and for unit tests.",
49
+ {"type": "sqlite", "path": "${SQLITE_PATH:-odcr.sqlite}"},
50
+ notes=["No schemas: meta tables are prefixed (odcr_meta_validation_runs, ...)."]),
51
+ AdapterInfo("postgres", "PostgreSQL", "postgres:PostgresAdapter", "on-premise",
52
+ "on-premise, AWS RDS/Aurora, Azure, GCP Cloud SQL/AlloyDB", "postgres", "psycopg", "ci",
53
+ "PostgreSQL and PostgreSQL-compatible databases.",
54
+ {"type": "postgres", "host": "${PGHOST:-localhost}", "port": "${PGPORT:-5432}",
55
+ "database": "${PGDATABASE:-postgres}", "user": "${PGUSER:-postgres}", "password": "${PGPASSWORD:-}"},
56
+ aliases=("postgresql", "aurora-postgres", "azure-postgres", "cloudsql-postgres", "alloydb",
57
+ "supabase", "neon")),
58
+ AdapterInfo("mysql", "MySQL / MariaDB", "mysql:MySQLAdapter", "on-premise",
59
+ "on-premise, AWS RDS/Aurora, Azure, GCP Cloud SQL", "mysql", "pymysql", "ci",
60
+ "MySQL, MariaDB and MySQL-compatible databases.",
61
+ {"type": "mysql", "host": "${MYSQL_HOST:-localhost}", "port": "${MYSQL_PORT:-3306}",
62
+ "database": "${MYSQL_DATABASE:-odcr}", "user": "${MYSQL_USER:-root}",
63
+ "password": "${MYSQL_PASSWORD:-}"},
64
+ aliases=("mariadb", "aurora-mysql", "azure-mysql", "cloudsql-mysql", "tidb")),
65
+ AdapterInfo("sqlserver", "SQL Server / Azure SQL", "sqlserver:SQLServerAdapter", "on-premise",
66
+ "on-premise, Azure SQL Database, Azure SQL Managed Instance, AWS RDS", "sqlserver", "pyodbc", "ci",
67
+ "Microsoft SQL Server and Azure SQL. Clients: pyodbc (ODBC Driver 18, Entra ID) or pytds.",
68
+ {"type": "sqlserver", "host": "${MSSQL_HOST:-localhost}", "port": "${MSSQL_PORT:-1433}",
69
+ "database": "${MSSQL_DATABASE:-master}", "user": "${MSSQL_USER:-sa}",
70
+ "password": "${MSSQL_PASSWORD:-}", "client": "pyodbc", "encrypt": "yes"},
71
+ aliases=("mssql", "azuresql", "azure-sql", "sql-managed-instance"),
72
+ notes=["Entra ID: set authentication: ActiveDirectoryMsi (or ActiveDirectoryInteractive) and "
73
+ "leave user/password empty.", "No ODBC driver available? Set client: pytds.",
74
+ "TLS is on and the server certificate is verified (encrypt: yes). For a private CA, install "
75
+ "it in the OS trust store; trust_server_certificate: true is for local development only."]),
76
+ AdapterInfo("synapse", "Azure Synapse Analytics", "sqlserver:SynapseAdapter", "cloud", "Azure", "sqlserver",
77
+ "pyodbc", "credentials", "Dedicated SQL pools; meta tables are created as HEAP tables.",
78
+ {"type": "synapse", "host": "${SYNAPSE_HOST}", "port": 1433, "database": "${SYNAPSE_DATABASE}",
79
+ "authentication": "ActiveDirectoryInteractive", "user": "${SYNAPSE_USER:-}"}),
80
+ AdapterInfo("fabric", "Microsoft Fabric Warehouse", "sqlserver:FabricWarehouseAdapter", "cloud", "Azure",
81
+ "sqlserver", "pyodbc", "credentials", "Fabric Warehouse and SQL analytics endpoints.",
82
+ {"type": "fabric", "host": "${FABRIC_SQL_ENDPOINT}", "port": 1433, "database": "${FABRIC_WAREHOUSE}",
83
+ "authentication": "ActiveDirectoryInteractive", "user": "${FABRIC_USER:-}"}),
84
+ AdapterInfo("oracle", "Oracle Database", "oracle:OracleAdapter", "on-premise",
85
+ "on-premise, Oracle Cloud (Autonomous), AWS RDS", "oracle", "oracledb", "ci",
86
+ "Oracle Database 19c+ (thin mode, no Oracle Client needed).",
87
+ {"type": "oracle", "host": "${ORACLE_HOST:-localhost}", "port": "${ORACLE_PORT:-1521}",
88
+ "service_name": "${ORACLE_SERVICE:-FREEPDB1}", "user": "${ORACLE_USER}",
89
+ "password": "${ORACLE_PASSWORD}"},
90
+ notes=["Meta tables are created in the current schema with the prefix odcr_meta_."]),
91
+ AdapterInfo("db2", "IBM Db2", "db2:Db2Adapter", "on-premise", "on-premise, IBM Cloud", "db2", "ibm_db",
92
+ "credentials", "IBM Db2 LUW, Db2 on Cloud and Db2 Warehouse.",
93
+ {"type": "db2", "host": "${DB2_HOST:-localhost}", "port": "${DB2_PORT:-50000}",
94
+ "database": "${DB2_DATABASE}", "user": "${DB2_USER}", "password": "${DB2_PASSWORD}"}),
95
+ AdapterInfo("trino", "Trino / Starburst / Presto", "trino:TrinoAdapter", "on-premise",
96
+ "on-premise, Starburst Galaxy, AWS EMR", "trino", "trino", "ci",
97
+ "Query engine over Hive, Iceberg, Delta Lake, Kafka and more.",
98
+ {"type": "trino", "host": "${TRINO_HOST:-localhost}", "port": "${TRINO_PORT:-8080}",
99
+ "user": "${TRINO_USER:-odcr}", "catalog": "${TRINO_CATALOG:-hive}", "schema": "${TRINO_SCHEMA:-default}"},
100
+ aliases=("starburst", "presto")),
101
+ AdapterInfo("snowflake", "Snowflake", "snowflake:SnowflakeAdapter", "cloud", "AWS, Azure, GCP", "snowflake",
102
+ "snowflake.connector", "credentials", "Snowflake data cloud (password, key-pair, OAuth, SSO).",
103
+ {"type": "snowflake", "account": "${SNOWFLAKE_ACCOUNT}", "user": "${SNOWFLAKE_USER}",
104
+ "password": "${SNOWFLAKE_PASSWORD:-}", "private_key_file": "${SNOWFLAKE_PRIVATE_KEY_FILE:-}",
105
+ "warehouse": "${SNOWFLAKE_WAREHOUSE}", "database": "${SNOWFLAKE_DATABASE}",
106
+ "schema": "${SNOWFLAKE_SCHEMA:-PUBLIC}", "role": "${SNOWFLAKE_ROLE:-}"}),
107
+ AdapterInfo("databricks", "Databricks", "databricks:DatabricksAdapter", "cloud", "Azure, AWS, GCP",
108
+ "databricks", "databricks.sql", "credentials",
109
+ "Databricks SQL warehouses and clusters; Unity Catalog and hive_metastore; Delta meta tables.",
110
+ {"type": "databricks", "host": "${DATABRICKS_HOST}", "http_path": "${DATABRICKS_HTTP_PATH}",
111
+ "access_token": "${DATABRICKS_TOKEN}", "catalog": "${DATABRICKS_CATALOG:-main}",
112
+ "schema": "${DATABRICKS_SCHEMA:-default}"},
113
+ aliases=("azure-databricks", "aws-databricks", "gcp-databricks")),
114
+ AdapterInfo("bigquery", "Google BigQuery", "bigquery:BigQueryAdapter", "cloud", "GCP", "bigquery",
115
+ "google.cloud.bigquery", "credentials", "BigQuery with Application Default Credentials or a key file.",
116
+ {"type": "bigquery", "project": "${GCP_PROJECT}", "dataset": "${BIGQUERY_DATASET}",
117
+ "location": "${BIGQUERY_LOCATION:-EU}", "credentials_path": "${GOOGLE_APPLICATION_CREDENTIALS:-}"}),
118
+ AdapterInfo("redshift", "Amazon Redshift", "redshift:RedshiftAdapter", "cloud", "AWS", "redshift",
119
+ "redshift_connector", "credentials", "Redshift provisioned and Serverless (password or IAM).",
120
+ {"type": "redshift", "host": "${REDSHIFT_HOST}", "port": 5439, "database": "${REDSHIFT_DATABASE:-dev}",
121
+ "user": "${REDSHIFT_USER}", "password": "${REDSHIFT_PASSWORD}"}),
122
+ AdapterInfo("athena", "Amazon Athena", "athena:AthenaAdapter", "cloud", "AWS", "athena", "pyathena",
123
+ "credentials", "Athena over the Glue Data Catalog; Iceberg meta tables in S3.",
124
+ {"type": "athena", "region_name": "${AWS_REGION:-eu-north-1}",
125
+ "s3_staging_dir": "${ATHENA_S3_STAGING_DIR}", "schema": "${ATHENA_DATABASE:-default}",
126
+ "work_group": "${ATHENA_WORKGROUP:-primary}", "meta_location": "${ATHENA_META_LOCATION}"}),
127
+ AdapterInfo("mongodb", "MongoDB", "mongodb:MongoDBAdapter", "document",
128
+ "on-premise, MongoDB Atlas, Amazon DocumentDB, Azure Cosmos DB for MongoDB", "mongodb", "pymongo", "ci",
129
+ "Collections as objects; JSON batch filters; custom rules with engine: mongodb.",
130
+ {"type": "mongodb", "uri": "${MONGODB_URI:-mongodb://localhost:27017}",
131
+ "database": "${MONGODB_DATABASE:-odcr}"},
132
+ aliases=("documentdb", "cosmos-mongo", "atlas"), where_example='{"load_id": "{batch_id}"}'),
133
+ AdapterInfo("cosmosdb", "Azure Cosmos DB (NoSQL)", "cosmosdb:CosmosDBAdapter", "document", "Azure", "cosmosdb",
134
+ "azure.cosmos", "credentials", "Containers as objects; Cosmos SQL conditions; key or Entra ID auth.",
135
+ {"type": "cosmosdb", "endpoint": "${COSMOS_ENDPOINT}", "key": "${COSMOS_KEY:-}",
136
+ "database": "${COSMOS_DATABASE:-odcr}"},
137
+ aliases=("cosmos",), where_example="c.load_id = '{batch_id}'"),
138
+ ]}
139
+
140
+ _ALIASES = {alias: info.name for info in ADAPTERS.values() for alias in info.aliases}
141
+
142
+
143
+ def resolve(name: str) -> AdapterInfo:
144
+ key = str(name).lower()
145
+ key = _ALIASES.get(key, key)
146
+ if key not in ADAPTERS:
147
+ raise ValueError(f"Unsupported adapter '{name}'. Run `odcr adapters` to list them "
148
+ f"({', '.join(sorted(ADAPTERS))}).")
149
+ return ADAPTERS[key]
150
+
151
+
152
+ def adapter_class(name: str) -> type[Adapter]:
153
+ info = resolve(name)
154
+ module, cls = info.cls.split(":")
155
+ return getattr(importlib.import_module(f"odcr.adapters.{module}"), cls)
156
+
157
+
158
+ def driver_installed(info: AdapterInfo) -> bool:
159
+ try:
160
+ importlib.import_module(info.driver)
161
+ return True
162
+ except Exception: # noqa: BLE001
163
+ return False
164
+
165
+
166
+ def get_adapter(options: dict[str, Any]) -> Adapter:
167
+ opts = dict(options)
168
+ kind = str(opts.pop("type", ""))
169
+ return adapter_class(kind)(**opts)
170
+
171
+
172
+ __all__ = ["Adapter", "AdapterInfo", "ADAPTERS", "UnsupportedCheck", "adapter_class", "driver_installed",
173
+ "get_adapter", "resolve", "type_matches"]
@@ -0,0 +1,53 @@
1
+ """Amazon Athena adapter (PyAthena). Checks run on any Athena table (Glue Data Catalog).
2
+
3
+ Meta tables are Apache Iceberg tables and need an S3 location: set `meta_location: s3://bucket/odcr_meta/`
4
+ on the connection, or store meta tables elsewhere with `meta: {connection: <other connection>}`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from .base import Adapter
12
+
13
+
14
+ class AthenaAdapter(Adapter):
15
+ dialect = "athena"
16
+ driver = "pyathena"
17
+ paramstyle = "inline"
18
+ multi_row_insert = True
19
+
20
+ def _connect(self) -> Any:
21
+ try:
22
+ from pyathena import connect
23
+ except ImportError as exc: # pragma: no cover
24
+ raise ImportError("Athena support needs: pip install 'odcr[athena]'") from exc
25
+ o = self.options
26
+ kwargs = {k: o[k] for k in ("s3_staging_dir", "region_name", "work_group", "catalog_name", "profile_name")
27
+ if o.get(k)}
28
+ kwargs["schema_name"] = o.get("schema", "default")
29
+ return connect(**kwargs)
30
+
31
+ def current_schema(self) -> str | None:
32
+ return self.options.get("schema", "default")
33
+
34
+ def meta_ensure(self, schema: str) -> None:
35
+ if schema in self._meta_ready:
36
+ return
37
+ from ..meta import TABLES
38
+
39
+ location = str(self.options.get("meta_location", "")).rstrip("/")
40
+ if not location:
41
+ raise ValueError("Athena meta tables need 'meta_location: s3://bucket/prefix' on the connection, "
42
+ "or set meta.connection to store results on another platform")
43
+ types = {"id": "string", "name": "string", "short": "string", "text": "string", "ts": "timestamp",
44
+ "int": "bigint", "num": "double"}
45
+ self.execute(f"CREATE DATABASE IF NOT EXISTS `{schema}`")
46
+ for table, cols in TABLES.items():
47
+ cols_sql = ", ".join(f"`{c}` {types[t]}" for c, t in cols)
48
+ self.execute(f"CREATE TABLE IF NOT EXISTS `{schema}`.`{table}` ({cols_sql}) "
49
+ f"LOCATION '{location}/{table}/' TBLPROPERTIES ('table_type'='ICEBERG')")
50
+ self._meta_ready.add(schema)
51
+
52
+ def sample_types(self) -> dict[str, str]:
53
+ return {"integer": "INT", "string": "STRING", "decimal": "DECIMAL(12,2)", "date": "DATE"}