ab-analysis-kit 0.0.1.dev0__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.
- ab_analysis_kit-0.0.1.dev0.dist-info/METADATA +126 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/RECORD +122 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/WHEEL +5 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/entry_points.txt +2 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/licenses/LICENSE +21 -0
- ab_analysis_kit-0.0.1.dev0.dist-info/top_level.txt +1 -0
- abkit/__init__.py +40 -0
- abkit/cli/__init__.py +1 -0
- abkit/cli/_output.py +111 -0
- abkit/cli/commands/__init__.py +1 -0
- abkit/cli/commands/_context.py +83 -0
- abkit/cli/commands/clean.py +133 -0
- abkit/cli/commands/explore.py +208 -0
- abkit/cli/commands/init.py +427 -0
- abkit/cli/commands/run.py +282 -0
- abkit/cli/commands/unlock.py +59 -0
- abkit/cli/commands/validate.py +264 -0
- abkit/cli/main.py +279 -0
- abkit/compute/__init__.py +5 -0
- abkit/compute/recompute_backend.py +140 -0
- abkit/config/__init__.py +51 -0
- abkit/config/discovery.py +168 -0
- abkit/config/experiment_config.py +511 -0
- abkit/config/method_config.py +80 -0
- abkit/config/metric_config.py +214 -0
- abkit/config/profile.py +301 -0
- abkit/config/project_config.py +244 -0
- abkit/config/validator.py +393 -0
- abkit/core/__init__.py +26 -0
- abkit/core/interval.py +148 -0
- abkit/core/models.py +121 -0
- abkit/core/period_planner.py +206 -0
- abkit/database/__init__.py +51 -0
- abkit/database/_sql_manager.py +432 -0
- abkit/database/clickhouse_manager.py +495 -0
- abkit/database/internal_tables/__init__.py +6 -0
- abkit/database/internal_tables/_aa_runs.py +53 -0
- abkit/database/internal_tables/_base.py +71 -0
- abkit/database/internal_tables/_experiments.py +82 -0
- abkit/database/internal_tables/_exposures.py +163 -0
- abkit/database/internal_tables/_maintenance.py +72 -0
- abkit/database/internal_tables/_results.py +231 -0
- abkit/database/internal_tables/_schema.py +23 -0
- abkit/database/internal_tables/_tasks.py +237 -0
- abkit/database/internal_tables/_unit_state.py +148 -0
- abkit/database/internal_tables/manager.py +30 -0
- abkit/database/manager.py +450 -0
- abkit/database/mysql_manager.py +175 -0
- abkit/database/postgres_manager.py +145 -0
- abkit/database/tables.py +326 -0
- abkit/loaders/__init__.py +28 -0
- abkit/loaders/exposure_loader.py +121 -0
- abkit/loaders/metric_loader.py +251 -0
- abkit/loaders/query_template.py +167 -0
- abkit/loaders/templates/abkit_assignment.jinja +62 -0
- abkit/pipeline/__init__.py +37 -0
- abkit/pipeline/_types.py +52 -0
- abkit/pipeline/analyze.py +223 -0
- abkit/pipeline/driver.py +477 -0
- abkit/pipeline/enrich.py +137 -0
- abkit/pipeline/readout.py +779 -0
- abkit/reporting/__init__.py +19 -0
- abkit/reporting/assets/report.js +138 -0
- abkit/reporting/builder.py +484 -0
- abkit/reporting/calibration.py +182 -0
- abkit/reporting/html_report.py +109 -0
- abkit/stats/__init__.py +94 -0
- abkit/stats/accumulate.py +82 -0
- abkit/stats/base.py +347 -0
- abkit/stats/bootstrap/__init__.py +69 -0
- abkit/stats/bootstrap/applier.py +81 -0
- abkit/stats/bootstrap/bootstrap.py +311 -0
- abkit/stats/bootstrap/ci.py +72 -0
- abkit/stats/bootstrap/engine.py +383 -0
- abkit/stats/bootstrap/paired_bootstrap.py +57 -0
- abkit/stats/bootstrap/paired_post_normed_bootstrap.py +81 -0
- abkit/stats/bootstrap/poisson_bootstrap.py +112 -0
- abkit/stats/bootstrap/post_normed_bootstrap.py +102 -0
- abkit/stats/correction.py +88 -0
- abkit/stats/effects.py +141 -0
- abkit/stats/exceptions.py +31 -0
- abkit/stats/factory.py +26 -0
- abkit/stats/parametric/__init__.py +10 -0
- abkit/stats/parametric/cuped_ttest.py +183 -0
- abkit/stats/parametric/paired_cuped_ttest.py +125 -0
- abkit/stats/parametric/paired_ttest.py +136 -0
- abkit/stats/parametric/ratio_delta.py +113 -0
- abkit/stats/parametric/ttest.py +105 -0
- abkit/stats/parametric/ztest.py +134 -0
- abkit/stats/power.py +278 -0
- abkit/stats/registry.py +111 -0
- abkit/stats/result.py +84 -0
- abkit/stats/rng.py +39 -0
- abkit/stats/samples.py +531 -0
- abkit/stats/sequential/__init__.py +18 -0
- abkit/stats/sequential/apply.py +37 -0
- abkit/stats/sequential/confidence_sequence.py +96 -0
- abkit/stats/sequential/mixture.py +70 -0
- abkit/stats/srm.py +221 -0
- abkit/tuning/__init__.py +59 -0
- abkit/tuning/assets/explore.js +173 -0
- abkit/tuning/config_writer.py +409 -0
- abkit/tuning/html.py +88 -0
- abkit/tuning/payload.py +122 -0
- abkit/tuning/recompute.py +1039 -0
- abkit/tuning/server.py +882 -0
- abkit/tuning/session.py +233 -0
- abkit/utils/__init__.py +27 -0
- abkit/utils/datetime_utils.py +97 -0
- abkit/utils/env_interpolation.py +50 -0
- abkit/utils/json_utils.py +38 -0
- abkit/validate/__init__.py +36 -0
- abkit/validate/_types.py +35 -0
- abkit/validate/inject.py +75 -0
- abkit/validate/load.py +160 -0
- abkit/validate/panel.py +59 -0
- abkit/validate/persistence.py +59 -0
- abkit/validate/resample.py +94 -0
- abkit/validate/result.py +60 -0
- abkit/validate/run_id.py +45 -0
- abkit/validate/runner.py +389 -0
- abkit/validate/scoring.py +544 -0
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Metric configuration — the reusable library item (declarative-config.md §3).
|
|
2
|
+
|
|
3
|
+
A metric is referenced by experiments by name; its SQL must return ONE ROW PER
|
|
4
|
+
UNIT with additive aggregate columns over the cumulative window (the loader
|
|
5
|
+
guards this). The ``type`` + ``columns`` role mapping tells the loader how to
|
|
6
|
+
build stats-core containers (``Sample``/``Fraction``/``RatioSample`` or
|
|
7
|
+
sufficient statistics).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Literal
|
|
14
|
+
|
|
15
|
+
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
16
|
+
|
|
17
|
+
from abkit.database.tables import MAX_METRIC_NAME_LENGTH
|
|
18
|
+
|
|
19
|
+
MetricType = Literal["fraction", "sample", "ratio"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MetricColumnsConfig(BaseModel):
|
|
23
|
+
"""Column-role mapping from the metric SQL's result set.
|
|
24
|
+
|
|
25
|
+
Role requirements by metric type (validated on the parent):
|
|
26
|
+
- ``sample``: requires ``value``; optional ``covariate`` (CUPED)
|
|
27
|
+
- ``fraction``: requires ``count`` and ``nobs``
|
|
28
|
+
- ``ratio``: requires ``numerator`` and ``denominator``
|
|
29
|
+
- ``variant`` is always required; ``stratum`` is always optional
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
variant: str = Field(..., description="Arm label column (from the cohort macro)")
|
|
33
|
+
value: str | None = Field(default=None, description="Per-unit value (type=sample)")
|
|
34
|
+
covariate: str | None = Field(default=None, description="CUPED covariate (type=sample)")
|
|
35
|
+
count: str | None = Field(default=None, description="Successes (type=fraction)")
|
|
36
|
+
nobs: str | None = Field(default=None, description="Trials (type=fraction)")
|
|
37
|
+
numerator: str | None = Field(default=None, description="Numerator (type=ratio)")
|
|
38
|
+
denominator: str | None = Field(default=None, description="Denominator (type=ratio)")
|
|
39
|
+
stratum: str | None = Field(default=None, description="Stratification key (optional)")
|
|
40
|
+
|
|
41
|
+
def role_map(self) -> dict[str, str]:
|
|
42
|
+
"""The set roles as ``{role: column}`` (drives ``column_set_id``)."""
|
|
43
|
+
return {role: col for role, col in self.model_dump().items() if col is not None}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
#: which roles each metric type requires / permits (beyond variant/stratum)
|
|
47
|
+
_TYPE_ROLES: dict[str, tuple[set[str], set[str]]] = {
|
|
48
|
+
# type: (required, optional)
|
|
49
|
+
"sample": ({"value"}, {"covariate"}),
|
|
50
|
+
"fraction": ({"count", "nobs"}, set()),
|
|
51
|
+
"ratio": ({"numerator", "denominator"}, set()),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class MetricConfig(BaseModel):
|
|
56
|
+
"""
|
|
57
|
+
Configuration for a single reusable metric.
|
|
58
|
+
|
|
59
|
+
Loaded from YAML files in the ``metrics/`` directory.
|
|
60
|
+
|
|
61
|
+
Example YAML:
|
|
62
|
+
```yaml
|
|
63
|
+
name: arpu
|
|
64
|
+
description: "Average revenue per user"
|
|
65
|
+
type: sample
|
|
66
|
+
unit_key: user_id
|
|
67
|
+
tags: [revenue, guardrail]
|
|
68
|
+
columns:
|
|
69
|
+
variant: group
|
|
70
|
+
value: gross_usd
|
|
71
|
+
covariate: prev_gross_usd
|
|
72
|
+
stratum: country
|
|
73
|
+
query_file: sql/arpu.sql
|
|
74
|
+
```
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
model_config = ConfigDict(populate_by_name=True)
|
|
78
|
+
|
|
79
|
+
name: str = Field(..., description="Metric name (globally unique; DB key)")
|
|
80
|
+
description: str | None = Field(default=None, description="Optional description")
|
|
81
|
+
type: MetricType = Field(..., description="fraction | sample | ratio")
|
|
82
|
+
unit_key: str | None = Field(
|
|
83
|
+
default=None,
|
|
84
|
+
description="Analysis unit key; must match (or be inherited from) the experiment",
|
|
85
|
+
)
|
|
86
|
+
tags: list[str] | None = Field(
|
|
87
|
+
default=None, description="Optional tags for selection (tag: selectors)"
|
|
88
|
+
)
|
|
89
|
+
columns: MetricColumnsConfig = Field(..., description="Column-role mapping")
|
|
90
|
+
# the YAML spelling is `sql:` (declarative-config.md §3); `query` kept for symmetry
|
|
91
|
+
query: str | None = Field(
|
|
92
|
+
default=None,
|
|
93
|
+
validation_alias=AliasChoices("sql", "query"),
|
|
94
|
+
description="Inline SQL query",
|
|
95
|
+
)
|
|
96
|
+
query_file: Path | None = Field(default=None, description="Path to SQL file")
|
|
97
|
+
# A/A false-positive budget the validate matrix colours THIS metric against; overrides
|
|
98
|
+
# the project default (declarative-config.md §8; resolve_fpr_budget metric arm, D12).
|
|
99
|
+
aa_fpr_budget: float | None = Field(
|
|
100
|
+
default=None,
|
|
101
|
+
description="Per-metric A/A false-positive budget (fraction in (0, 1]); "
|
|
102
|
+
"overrides project statistics.aa_fpr_budget for this metric",
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
@field_validator("name")
|
|
106
|
+
@classmethod
|
|
107
|
+
def validate_name(cls, v: str) -> str:
|
|
108
|
+
"""Metric name: non-empty, storage-safe charset, fits the PK budget."""
|
|
109
|
+
if not v:
|
|
110
|
+
raise ValueError("Metric name cannot be empty")
|
|
111
|
+
if not all(c.isalnum() or c in ("_", "-") for c in v):
|
|
112
|
+
raise ValueError(
|
|
113
|
+
"Metric name can only contain alphanumeric characters, underscores, and dashes"
|
|
114
|
+
)
|
|
115
|
+
if len(v) > MAX_METRIC_NAME_LENGTH:
|
|
116
|
+
raise ValueError(
|
|
117
|
+
f"Metric name is longer than {MAX_METRIC_NAME_LENGTH} characters "
|
|
118
|
+
"(the storage key budget)"
|
|
119
|
+
)
|
|
120
|
+
return v
|
|
121
|
+
|
|
122
|
+
@field_validator("aa_fpr_budget")
|
|
123
|
+
@classmethod
|
|
124
|
+
def validate_aa_fpr_budget(cls, v: float | None) -> float | None:
|
|
125
|
+
"""A fraction in (0, 1] (mirrors project statistics.aa_fpr_budget)."""
|
|
126
|
+
if v is not None and not 0.0 < v <= 1.0:
|
|
127
|
+
raise ValueError(f"aa_fpr_budget must be a fraction in (0, 1], got {v}")
|
|
128
|
+
return v
|
|
129
|
+
|
|
130
|
+
@field_validator("tags")
|
|
131
|
+
@classmethod
|
|
132
|
+
def validate_tags(cls, v: list[str] | None) -> list[str] | None:
|
|
133
|
+
"""Validate tags field."""
|
|
134
|
+
if v is None:
|
|
135
|
+
return v
|
|
136
|
+
if not v:
|
|
137
|
+
raise ValueError("tags list cannot be empty (use null instead)")
|
|
138
|
+
if len(v) != len(set(v)):
|
|
139
|
+
raise ValueError("Duplicate tags not allowed")
|
|
140
|
+
for tag in v:
|
|
141
|
+
if not tag:
|
|
142
|
+
raise ValueError("Empty tag not allowed")
|
|
143
|
+
if not all(c.isalnum() or c in ("_", "-") for c in tag):
|
|
144
|
+
raise ValueError(
|
|
145
|
+
f"Invalid tag '{tag}': only alphanumeric characters, "
|
|
146
|
+
f"underscores, and dashes allowed"
|
|
147
|
+
)
|
|
148
|
+
return v
|
|
149
|
+
|
|
150
|
+
@model_validator(mode="after")
|
|
151
|
+
def validate_query_source(self) -> MetricConfig:
|
|
152
|
+
"""Exactly one of query / query_file."""
|
|
153
|
+
if self.query is None and self.query_file is None:
|
|
154
|
+
raise ValueError("Either 'query' or 'query_file' must be specified")
|
|
155
|
+
if self.query is not None and self.query_file is not None:
|
|
156
|
+
raise ValueError("Only one of 'query' or 'query_file' can be specified, not both")
|
|
157
|
+
return self
|
|
158
|
+
|
|
159
|
+
@model_validator(mode="after")
|
|
160
|
+
def validate_columns_match_type(self) -> MetricConfig:
|
|
161
|
+
"""Enforce the role-set ↔ type matrix (declarative-config §3)."""
|
|
162
|
+
required, optional = _TYPE_ROLES[self.type]
|
|
163
|
+
roles = self.columns.role_map()
|
|
164
|
+
present = set(roles) - {"variant", "stratum"}
|
|
165
|
+
|
|
166
|
+
missing = required - present
|
|
167
|
+
if missing:
|
|
168
|
+
raise ValueError(f"metric type '{self.type}' requires column roles {sorted(missing)}")
|
|
169
|
+
allowed = required | optional
|
|
170
|
+
forbidden = present - allowed
|
|
171
|
+
if forbidden:
|
|
172
|
+
raise ValueError(
|
|
173
|
+
f"metric type '{self.type}' does not accept column roles "
|
|
174
|
+
f"{sorted(forbidden)} (allowed: {sorted(allowed)})"
|
|
175
|
+
)
|
|
176
|
+
return self
|
|
177
|
+
|
|
178
|
+
def get_query_text(self, project_root: Path | None = None) -> str:
|
|
179
|
+
"""Get SQL query text (from inline query or file)."""
|
|
180
|
+
if self.query is not None:
|
|
181
|
+
return self.query
|
|
182
|
+
|
|
183
|
+
if project_root is not None:
|
|
184
|
+
query_path = project_root / self.query_file
|
|
185
|
+
else:
|
|
186
|
+
query_path = self.query_file
|
|
187
|
+
|
|
188
|
+
if not query_path.exists():
|
|
189
|
+
raise FileNotFoundError(f"Query file not found: {query_path}")
|
|
190
|
+
|
|
191
|
+
with open(query_path) as f:
|
|
192
|
+
return f.read()
|
|
193
|
+
|
|
194
|
+
@classmethod
|
|
195
|
+
def from_yaml_file(cls, path: Path) -> MetricConfig:
|
|
196
|
+
"""Load metric configuration from a YAML file.
|
|
197
|
+
|
|
198
|
+
Supports both flat and nested (``metric: {...}``) structures.
|
|
199
|
+
"""
|
|
200
|
+
import yaml
|
|
201
|
+
|
|
202
|
+
if not path.exists():
|
|
203
|
+
raise FileNotFoundError(f"Metric config file not found: {path}")
|
|
204
|
+
|
|
205
|
+
with open(path) as f:
|
|
206
|
+
data = yaml.safe_load(f)
|
|
207
|
+
|
|
208
|
+
if not data:
|
|
209
|
+
raise ValueError(f"Empty metric config file: {path}")
|
|
210
|
+
|
|
211
|
+
if "metric" in data and isinstance(data["metric"], dict):
|
|
212
|
+
data = data["metric"]
|
|
213
|
+
|
|
214
|
+
return cls.model_validate(data)
|
abkit/config/profile.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Profile configuration for abkit.
|
|
3
|
+
|
|
4
|
+
Manages database connections and locations (similar to dbt profiles).
|
|
5
|
+
Database manager imports are lazy so parsing configs never requires a DB
|
|
6
|
+
driver (``abk run --steps validate`` touches no database).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
# imported lazily inside create_manager(); annotation-only here
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
|
|
14
|
+
import yaml
|
|
15
|
+
from pydantic import BaseModel, Field, field_validator
|
|
16
|
+
|
|
17
|
+
from abkit.utils.env_interpolation import interpolate_env_vars
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
20
|
+
from abkit.database.manager import BaseDatabaseManager
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ProfileConfig(BaseModel):
|
|
24
|
+
"""
|
|
25
|
+
Single profile configuration.
|
|
26
|
+
|
|
27
|
+
Defines connection parameters and database locations for a specific
|
|
28
|
+
environment (dev, prod, etc.).
|
|
29
|
+
|
|
30
|
+
Attributes:
|
|
31
|
+
type: Database type ("clickhouse", "postgres", "mysql")
|
|
32
|
+
host: Database host
|
|
33
|
+
port: Database port
|
|
34
|
+
user: Database user
|
|
35
|
+
password: Database password
|
|
36
|
+
internal_database: Database/schema for internal tables
|
|
37
|
+
internal_schema: Schema for internal tables (PostgreSQL only)
|
|
38
|
+
data_database: Database for user data tables
|
|
39
|
+
data_schema: Schema for user data (PostgreSQL only)
|
|
40
|
+
settings: Additional database-specific settings
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
type: str = Field(..., description="Database type")
|
|
44
|
+
host: str = Field(default="localhost", description="Database host")
|
|
45
|
+
port: int = Field(..., description="Database port")
|
|
46
|
+
user: str = Field(default="default", description="Database user")
|
|
47
|
+
password: str = Field(default="", description="Database password")
|
|
48
|
+
|
|
49
|
+
# Connection-target database. Required for PostgreSQL (the database to
|
|
50
|
+
# connect to, inside which internal_schema/data_schema live); optional for
|
|
51
|
+
# MySQL; unused for ClickHouse.
|
|
52
|
+
database: str | None = Field(
|
|
53
|
+
default=None, description="Database to connect to (PostgreSQL/MySQL)"
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
# Internal location for _ab_* tables
|
|
57
|
+
internal_database: str | None = Field(
|
|
58
|
+
default=None, description="Database for internal tables (ClickHouse/MySQL)"
|
|
59
|
+
)
|
|
60
|
+
internal_schema: str | None = Field(
|
|
61
|
+
default=None, description="Schema for internal tables (PostgreSQL)"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
# Data location for user tables
|
|
65
|
+
data_database: str | None = Field(
|
|
66
|
+
default=None, description="Database for user data tables (ClickHouse/MySQL)"
|
|
67
|
+
)
|
|
68
|
+
data_schema: str | None = Field(default=None, description="Schema for user data (PostgreSQL)")
|
|
69
|
+
|
|
70
|
+
settings: dict[str, Any] = Field(
|
|
71
|
+
default_factory=dict, description="Additional database settings"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
@field_validator("type")
|
|
75
|
+
@classmethod
|
|
76
|
+
def validate_type(cls, v: str) -> str:
|
|
77
|
+
"""Validate database type."""
|
|
78
|
+
allowed_types = {"clickhouse", "postgres", "mysql"}
|
|
79
|
+
if v not in allowed_types:
|
|
80
|
+
raise ValueError(
|
|
81
|
+
f"Invalid database type: {v}. Allowed types: {', '.join(sorted(allowed_types))}"
|
|
82
|
+
)
|
|
83
|
+
return v
|
|
84
|
+
|
|
85
|
+
@field_validator("port")
|
|
86
|
+
@classmethod
|
|
87
|
+
def validate_port(cls, v: int) -> int:
|
|
88
|
+
"""Validate port number."""
|
|
89
|
+
if not (1 <= v <= 65535):
|
|
90
|
+
raise ValueError(f"Port must be between 1 and 65535, got {v}")
|
|
91
|
+
return v
|
|
92
|
+
|
|
93
|
+
def get_internal_location(self) -> str:
|
|
94
|
+
"""
|
|
95
|
+
Get internal location (database or schema).
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
Internal database/schema name
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
ValueError: If location not configured
|
|
102
|
+
"""
|
|
103
|
+
if self.type == "clickhouse":
|
|
104
|
+
if not self.internal_database:
|
|
105
|
+
raise ValueError("internal_database must be set for ClickHouse")
|
|
106
|
+
return self.internal_database
|
|
107
|
+
elif self.type == "postgres":
|
|
108
|
+
if not self.internal_schema:
|
|
109
|
+
raise ValueError("internal_schema must be set for PostgreSQL")
|
|
110
|
+
return self.internal_schema
|
|
111
|
+
elif self.type == "mysql":
|
|
112
|
+
if not self.internal_database:
|
|
113
|
+
raise ValueError("internal_database must be set for MySQL")
|
|
114
|
+
return self.internal_database
|
|
115
|
+
else:
|
|
116
|
+
raise ValueError(f"Unsupported database type: {self.type}")
|
|
117
|
+
|
|
118
|
+
def get_data_location(self) -> str:
|
|
119
|
+
"""
|
|
120
|
+
Get data location (database or schema).
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
Data database/schema name
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
ValueError: If location not configured
|
|
127
|
+
"""
|
|
128
|
+
if self.type == "clickhouse":
|
|
129
|
+
if not self.data_database:
|
|
130
|
+
raise ValueError("data_database must be set for ClickHouse")
|
|
131
|
+
return self.data_database
|
|
132
|
+
elif self.type == "postgres":
|
|
133
|
+
if not self.data_schema:
|
|
134
|
+
raise ValueError("data_schema must be set for PostgreSQL")
|
|
135
|
+
return self.data_schema
|
|
136
|
+
elif self.type == "mysql":
|
|
137
|
+
if not self.data_database:
|
|
138
|
+
raise ValueError("data_database must be set for MySQL")
|
|
139
|
+
return self.data_database
|
|
140
|
+
else:
|
|
141
|
+
raise ValueError(f"Unsupported database type: {self.type}")
|
|
142
|
+
|
|
143
|
+
def create_manager(self) -> "BaseDatabaseManager":
|
|
144
|
+
"""
|
|
145
|
+
Create database manager from profile configuration.
|
|
146
|
+
|
|
147
|
+
Imports the backend lazily so config parsing never requires a driver.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
Database manager instance
|
|
151
|
+
|
|
152
|
+
Raises:
|
|
153
|
+
ValueError: If the database type is unsupported, or required
|
|
154
|
+
connection fields (e.g. PostgreSQL ``database``) are missing
|
|
155
|
+
ImportError: If the backend's driver is not installed
|
|
156
|
+
"""
|
|
157
|
+
if self.type == "clickhouse":
|
|
158
|
+
from abkit.database.clickhouse_manager import ClickHouseDatabaseManager
|
|
159
|
+
|
|
160
|
+
return ClickHouseDatabaseManager(
|
|
161
|
+
host=self.host,
|
|
162
|
+
port=self.port,
|
|
163
|
+
user=self.user,
|
|
164
|
+
password=self.password,
|
|
165
|
+
internal_database=self.get_internal_location(),
|
|
166
|
+
data_database=self.get_data_location(),
|
|
167
|
+
settings=self.settings,
|
|
168
|
+
)
|
|
169
|
+
elif self.type == "postgres":
|
|
170
|
+
if not self.database:
|
|
171
|
+
raise ValueError(
|
|
172
|
+
"PostgreSQL profiles must set 'database' (the database to "
|
|
173
|
+
"connect to, inside which internal_schema/data_schema live)"
|
|
174
|
+
)
|
|
175
|
+
from abkit.database.postgres_manager import PostgresDatabaseManager
|
|
176
|
+
|
|
177
|
+
return PostgresDatabaseManager(
|
|
178
|
+
host=self.host,
|
|
179
|
+
port=self.port,
|
|
180
|
+
user=self.user,
|
|
181
|
+
password=self.password,
|
|
182
|
+
database=self.database,
|
|
183
|
+
internal_schema=self.get_internal_location(),
|
|
184
|
+
data_schema=self.get_data_location(),
|
|
185
|
+
settings=self.settings,
|
|
186
|
+
)
|
|
187
|
+
elif self.type == "mysql":
|
|
188
|
+
from abkit.database.mysql_manager import MySQLDatabaseManager
|
|
189
|
+
|
|
190
|
+
return MySQLDatabaseManager(
|
|
191
|
+
host=self.host,
|
|
192
|
+
port=self.port,
|
|
193
|
+
user=self.user,
|
|
194
|
+
password=self.password,
|
|
195
|
+
database=self.database,
|
|
196
|
+
internal_database=self.get_internal_location(),
|
|
197
|
+
data_database=self.get_data_location(),
|
|
198
|
+
settings=self.settings,
|
|
199
|
+
)
|
|
200
|
+
else:
|
|
201
|
+
raise ValueError(f"Unsupported database type: {self.type}")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class ProfilesConfig(BaseModel):
|
|
205
|
+
"""
|
|
206
|
+
Container for multiple profile configurations.
|
|
207
|
+
|
|
208
|
+
Loaded from profiles.yml file.
|
|
209
|
+
|
|
210
|
+
Attributes:
|
|
211
|
+
profiles: Dictionary mapping profile names to configurations
|
|
212
|
+
default_profile: Name of default profile to use
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
profiles: dict[str, ProfileConfig]
|
|
216
|
+
default_profile: str | None = None
|
|
217
|
+
|
|
218
|
+
@field_validator("default_profile")
|
|
219
|
+
@classmethod
|
|
220
|
+
def validate_default_profile(cls, v: str | None, info) -> str | None:
|
|
221
|
+
"""Validate default profile exists."""
|
|
222
|
+
if v is not None:
|
|
223
|
+
profiles = info.data.get("profiles", {})
|
|
224
|
+
if v not in profiles:
|
|
225
|
+
raise ValueError(
|
|
226
|
+
f"default_profile '{v}' not found in profiles. "
|
|
227
|
+
f"Available profiles: {', '.join(profiles.keys())}"
|
|
228
|
+
)
|
|
229
|
+
return v
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def from_yaml(cls, path: Path) -> "ProfilesConfig":
|
|
233
|
+
"""
|
|
234
|
+
Load profiles from YAML file.
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
path: Path to profiles.yml
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
ProfilesConfig instance
|
|
241
|
+
|
|
242
|
+
Raises:
|
|
243
|
+
FileNotFoundError: If file doesn't exist
|
|
244
|
+
ValueError: If YAML is invalid
|
|
245
|
+
"""
|
|
246
|
+
if not path.exists():
|
|
247
|
+
raise FileNotFoundError(f"Profiles file not found: {path}")
|
|
248
|
+
|
|
249
|
+
with open(path) as f:
|
|
250
|
+
data = yaml.safe_load(f)
|
|
251
|
+
|
|
252
|
+
if not data:
|
|
253
|
+
raise ValueError("Profiles file is empty")
|
|
254
|
+
|
|
255
|
+
# Resolve ${VAR} / {{ env_var('VAR') }} placeholders before validation
|
|
256
|
+
# so that secrets (DB passwords) are not stored in YAML.
|
|
257
|
+
data = interpolate_env_vars(data)
|
|
258
|
+
|
|
259
|
+
return cls.model_validate(data)
|
|
260
|
+
|
|
261
|
+
def get_profile(self, name: str | None = None) -> ProfileConfig:
|
|
262
|
+
"""
|
|
263
|
+
Get profile configuration by name.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
name: Profile name (if None, use default_profile)
|
|
267
|
+
|
|
268
|
+
Returns:
|
|
269
|
+
ProfileConfig instance
|
|
270
|
+
|
|
271
|
+
Raises:
|
|
272
|
+
ValueError: If profile not found or no default set
|
|
273
|
+
"""
|
|
274
|
+
if name is None:
|
|
275
|
+
if self.default_profile is None:
|
|
276
|
+
raise ValueError(
|
|
277
|
+
"No profile name specified and no default_profile set. "
|
|
278
|
+
f"Available profiles: {', '.join(self.profiles.keys())}"
|
|
279
|
+
)
|
|
280
|
+
name = self.default_profile
|
|
281
|
+
|
|
282
|
+
if name not in self.profiles:
|
|
283
|
+
raise ValueError(
|
|
284
|
+
f"Profile '{name}' not found. "
|
|
285
|
+
f"Available profiles: {', '.join(self.profiles.keys())}"
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
return self.profiles[name]
|
|
289
|
+
|
|
290
|
+
def create_manager(self, profile_name: str | None = None) -> "BaseDatabaseManager":
|
|
291
|
+
"""
|
|
292
|
+
Create database manager for a profile.
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
profile_name: Profile name (if None, use default)
|
|
296
|
+
|
|
297
|
+
Returns:
|
|
298
|
+
Database manager instance
|
|
299
|
+
"""
|
|
300
|
+
profile = self.get_profile(profile_name)
|
|
301
|
+
return profile.create_manager()
|