diffdb-core 0.1.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.
- diffdb/__init__.py +179 -0
- diffdb/concurrency/__init__.py +10 -0
- diffdb/concurrency/pool.py +88 -0
- diffdb/concurrency/stream.py +111 -0
- diffdb/core/__init__.py +38 -0
- diffdb/core/differ.py +136 -0
- diffdb/core/hash_differ.py +390 -0
- diffdb/core/segment.py +323 -0
- diffdb/core/sql.py +81 -0
- diffdb/core/summary.py +179 -0
- diffdb/databases/__init__.py +59 -0
- diffdb/databases/_connect.py +210 -0
- diffdb/databases/base.py +266 -0
- diffdb/databases/bigquery.py +54 -0
- diffdb/databases/clickhouse.py +35 -0
- diffdb/databases/databricks.py +40 -0
- diffdb/databases/dialects/_base.yaml +182 -0
- diffdb/databases/dialects/bigquery.yaml +39 -0
- diffdb/databases/dialects/clickhouse.yaml +42 -0
- diffdb/databases/dialects/databricks.yaml +36 -0
- diffdb/databases/dialects/duckdb.yaml +48 -0
- diffdb/databases/dialects/mysql.yaml +45 -0
- diffdb/databases/dialects/oracle.yaml +44 -0
- diffdb/databases/dialects/postgresql.yaml +44 -0
- diffdb/databases/dialects/presto.yaml +37 -0
- diffdb/databases/dialects/redshift.yaml +11 -0
- diffdb/databases/dialects/snowflake.yaml +55 -0
- diffdb/databases/dialects/trino.yaml +5 -0
- diffdb/databases/dialects/vertica.yaml +39 -0
- diffdb/databases/duckdb.py +40 -0
- diffdb/databases/mysql.py +38 -0
- diffdb/databases/oracle.py +99 -0
- diffdb/databases/postgresql.py +34 -0
- diffdb/databases/presto.py +41 -0
- diffdb/databases/redshift.py +12 -0
- diffdb/databases/snowflake.py +55 -0
- diffdb/databases/trino.py +41 -0
- diffdb/databases/vertica.py +43 -0
- diffdb/databases/yaml_dialect.py +428 -0
- diffdb/geometry/__init__.py +42 -0
- diffdb/geometry/arithmetic.py +141 -0
- diffdb/geometry/bisection.py +100 -0
- diffdb/geometry/vector.py +42 -0
- diffdb/telemetry/__init__.py +11 -0
- diffdb/telemetry/info_tree.py +52 -0
- diffdb/telemetry/query_tracker.py +53 -0
- diffdb/types.py +302 -0
- diffdb/utils.py +121 -0
- diffdb_core-0.1.0.dist-info/METADATA +315 -0
- diffdb_core-0.1.0.dist-info/RECORD +53 -0
- diffdb_core-0.1.0.dist-info/WHEEL +5 -0
- diffdb_core-0.1.0.dist-info/licenses/LICENSE.md +87 -0
- diffdb_core-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
# diffdb/databases/yaml_dialect.py
|
|
2
|
+
"""Declarative YAML-based SQL Dialect loader for diffdb.
|
|
3
|
+
|
|
4
|
+
Enables configuring database datatypes, value normalization, checksum formulas,
|
|
5
|
+
and SQL syntax using human-readable YAML files instead of Python class hierarchies.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
import string
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
from uuid import UUID
|
|
15
|
+
|
|
16
|
+
import yaml
|
|
17
|
+
|
|
18
|
+
from ..types import (
|
|
19
|
+
TYPE_REGISTRY,
|
|
20
|
+
Boolean,
|
|
21
|
+
ColType,
|
|
22
|
+
ColType_UUID,
|
|
23
|
+
DbTime,
|
|
24
|
+
FractionalType,
|
|
25
|
+
StringType,
|
|
26
|
+
TemporalType,
|
|
27
|
+
UnknownColType,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# md5_as_int keeps the last 15 hex digits (60 bits) of the MD5, so a sum() of them never overflows 64 bits
|
|
31
|
+
CHECKSUM_HEXDIGITS = 15
|
|
32
|
+
CHECKSUM_MASK = 2 ** (CHECKSUM_HEXDIGITS * 4) - 1
|
|
33
|
+
|
|
34
|
+
# Type classes that dialect YAML may reference by name. This is the live registry from
|
|
35
|
+
# diffdb/types.py, so types registered with @register_type are picked up automatically.
|
|
36
|
+
TYPE_NAME_TO_CLASS: dict[str, type[ColType]] = TYPE_REGISTRY
|
|
37
|
+
|
|
38
|
+
# norm_keys handled by a dedicated normalize_<key>() method; any other registered norm_key is
|
|
39
|
+
# normalized with the YAML template `normalization.<norm_key>` ({value}, {precision}).
|
|
40
|
+
DEDICATED_NORM_KEYS = frozenset({"timestamp", "number", "uuid", "boolean", "string"})
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def template_norm_keys() -> set[str]:
|
|
44
|
+
"""norm_keys of registered types that are normalized purely from a YAML template."""
|
|
45
|
+
return {c.norm_key for c in TYPE_REGISTRY.values() if c.norm_key and c.norm_key not in DEDICATED_NORM_KEYS}
|
|
46
|
+
|
|
47
|
+
DIALECTS_DIR = Path(__file__).parent / "dialects"
|
|
48
|
+
|
|
49
|
+
# NAME(args) SUFFIX -- a suffix is only allowed after the parentheses, so multi-word names such as
|
|
50
|
+
# 'double precision' stay whole while 'TIMESTAMP(3) WITH TIME ZONE' splits into name/args/suffix.
|
|
51
|
+
_TYPE_NAME_RE = re.compile(
|
|
52
|
+
r"^\s*(?P<name>[A-Za-z_][\w ]*?)\s*(?:\((?P<args>[^()]*)\)\s*(?P<suffix>[A-Za-z_][\w ]*?)?)?\s*$"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# type_classes value: "Class" or "Class(args)", where args are defaults used when the type name has none
|
|
57
|
+
_CLASS_SPEC_RE = re.compile(r"^\s*(?P<cls>\w+)\s*(?:\((?P<args>[^()]*)\))?\s*$")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _parse_class_spec(spec) -> tuple[type[ColType] | None, tuple]:
|
|
61
|
+
"""'Float(53)' -> (Float, (53,)); unknown class -> (None, ())."""
|
|
62
|
+
m = _CLASS_SPEC_RE.match(spec) if isinstance(spec, str) else None
|
|
63
|
+
if not m:
|
|
64
|
+
return None, ()
|
|
65
|
+
args = tuple(_leading_int(a) for a in m["args"].split(",")) if m["args"] else ()
|
|
66
|
+
return TYPE_NAME_TO_CLASS.get(m["cls"]), args
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _type_key(type_name: str) -> str:
|
|
70
|
+
"""Normalize a type name for lookup: lower case, single spaces."""
|
|
71
|
+
return " ".join(type_name.lower().split())
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _leading_int(arg: str) -> int | None:
|
|
75
|
+
"""'12' -> 12, '100 BYTE' -> 100, '*' -> None."""
|
|
76
|
+
m = re.match(r"\s*(\d+)", arg)
|
|
77
|
+
return int(m.group(1)) if m else None
|
|
78
|
+
|
|
79
|
+
# --- YAML schema: allowed keys and the placeholders each template may reference ---
|
|
80
|
+
TOP_LEVEL_KEYS = {
|
|
81
|
+
"name", "extends", "abstract", "hash_charset",
|
|
82
|
+
"syntax", "capabilities", "type_classes", "type_regexps", "normalization",
|
|
83
|
+
}
|
|
84
|
+
SYNTAX_PLACEHOLDERS: dict[str, set[str] | None] = {
|
|
85
|
+
# None = plain value (not a .format() template)
|
|
86
|
+
"quote_char": None, "concat": None,
|
|
87
|
+
"set_timezone_to_utc": None, "float_precision_offset": None,
|
|
88
|
+
"to_string": {"value"},
|
|
89
|
+
"coalesce": {"value", "default"},
|
|
90
|
+
"timestamp_literal": {"iso", "iso_space"},
|
|
91
|
+
}
|
|
92
|
+
CAPABILITY_KEYS = {"rounds_on_prec_loss"}
|
|
93
|
+
TIMESTAMP_TEMPLATES = (
|
|
94
|
+
"timestamp_rounded",
|
|
95
|
+
"timestamp_zero_precision",
|
|
96
|
+
"timestamp_six_precision",
|
|
97
|
+
"timestamp_precision",
|
|
98
|
+
"timestamp_unrounded",
|
|
99
|
+
)
|
|
100
|
+
NORMALIZATION_PLACEHOLDERS: dict[str, set[str]] = {
|
|
101
|
+
"md5_as_int": {"s", "CHECKSUM_MASK"},
|
|
102
|
+
"hash_charset_wrap": {"s", "charset"},
|
|
103
|
+
"number": {"value", "precision", "format_str"},
|
|
104
|
+
"boolean": {"value"},
|
|
105
|
+
"uuid": {"value"},
|
|
106
|
+
**{k: {"value", "precision"} for k in TIMESTAMP_TEMPLATES},
|
|
107
|
+
}
|
|
108
|
+
REQUIRED_NORMALIZATION = ("md5_as_int", "number", "boolean", "uuid")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class DialectConfigError(ValueError):
|
|
112
|
+
"""Raised when a dialect YAML is malformed."""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _placeholders(template: str) -> set[str]:
|
|
116
|
+
return {field for _, field, _, _ in string.Formatter().parse(template) if field}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def validate_dialect_config(config: dict[str, Any]) -> None:
|
|
120
|
+
"""Validate a merged dialect config; raise DialectConfigError listing every problem found."""
|
|
121
|
+
name = config.get("name", "Unknown")
|
|
122
|
+
errors: list[str] = []
|
|
123
|
+
|
|
124
|
+
def check_section_keys(section: str, allowed) -> dict:
|
|
125
|
+
value = config.get(section) or {}
|
|
126
|
+
if not isinstance(value, dict):
|
|
127
|
+
errors.append(f"`{section}` must be a mapping")
|
|
128
|
+
return {}
|
|
129
|
+
if allowed is not None:
|
|
130
|
+
errors.extend(f"unknown key `{section}.{k}`" for k in value if k not in allowed)
|
|
131
|
+
return value
|
|
132
|
+
|
|
133
|
+
def check_template(path: str, tmpl, allowed: set[str]) -> None:
|
|
134
|
+
if tmpl is None:
|
|
135
|
+
return
|
|
136
|
+
if not isinstance(tmpl, str):
|
|
137
|
+
errors.append(f"`{path}` must be a string")
|
|
138
|
+
return
|
|
139
|
+
try:
|
|
140
|
+
unknown = _placeholders(tmpl) - allowed
|
|
141
|
+
except ValueError as e:
|
|
142
|
+
errors.append(f"`{path}` is not a valid template: {e}")
|
|
143
|
+
return
|
|
144
|
+
if unknown:
|
|
145
|
+
errors.append(f"`{path}` uses unknown placeholder(s) {sorted(unknown)}; allowed: {sorted(allowed)}")
|
|
146
|
+
|
|
147
|
+
errors.extend(f"unknown top-level key `{k}`" for k in config if k not in TOP_LEVEL_KEYS)
|
|
148
|
+
|
|
149
|
+
for key, tmpl in check_section_keys("syntax", SYNTAX_PLACEHOLDERS).items():
|
|
150
|
+
allowed = SYNTAX_PLACEHOLDERS.get(key)
|
|
151
|
+
if allowed is not None:
|
|
152
|
+
check_template(f"syntax.{key}", tmpl, allowed)
|
|
153
|
+
|
|
154
|
+
check_section_keys("capabilities", CAPABILITY_KEYS)
|
|
155
|
+
|
|
156
|
+
for type_name, cls_spec in check_section_keys("type_classes", None).items():
|
|
157
|
+
if _parse_class_spec(cls_spec)[0] is None:
|
|
158
|
+
errors.append(f"`type_classes.{type_name}`: unknown type class `{cls_spec}`; known: {sorted(TYPE_NAME_TO_CLASS)}")
|
|
159
|
+
for pattern, regex_cfg in check_section_keys("type_regexps", None).items():
|
|
160
|
+
if not isinstance(regex_cfg, dict) or regex_cfg.get("type") not in TYPE_NAME_TO_CLASS:
|
|
161
|
+
errors.append(f"`type_regexps['{pattern}']`: unknown or missing type class")
|
|
162
|
+
continue
|
|
163
|
+
try:
|
|
164
|
+
re.compile(pattern)
|
|
165
|
+
except re.error as e:
|
|
166
|
+
errors.append(f"`type_regexps['{pattern}']`: invalid regex: {e}")
|
|
167
|
+
|
|
168
|
+
norm_placeholders = {**NORMALIZATION_PLACEHOLDERS, **{k: {"value", "precision"} for k in template_norm_keys()}}
|
|
169
|
+
normalization = check_section_keys("normalization", norm_placeholders)
|
|
170
|
+
for key, tmpl in normalization.items():
|
|
171
|
+
if key in norm_placeholders:
|
|
172
|
+
check_template(f"normalization.{key}", tmpl, norm_placeholders[key])
|
|
173
|
+
if not config.get("abstract"):
|
|
174
|
+
errors.extend(f"missing required template `normalization.{k}`" for k in REQUIRED_NORMALIZATION if k not in normalization)
|
|
175
|
+
if not any(k in normalization for k in TIMESTAMP_TEMPLATES):
|
|
176
|
+
errors.append(f"missing a timestamp template (one of {list(TIMESTAMP_TEMPLATES)})")
|
|
177
|
+
|
|
178
|
+
if errors:
|
|
179
|
+
raise DialectConfigError(f"Invalid dialect config `{name}`:\n - " + "\n - ".join(errors))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def deep_merge(base: dict, override: dict) -> dict:
|
|
183
|
+
"""Recursively merges override dictionary into base dictionary."""
|
|
184
|
+
result = copy.deepcopy(base)
|
|
185
|
+
for k, v in override.items():
|
|
186
|
+
if k in result and isinstance(result[k], dict) and isinstance(v, dict):
|
|
187
|
+
result[k] = deep_merge(result[k], v)
|
|
188
|
+
else:
|
|
189
|
+
result[k] = copy.deepcopy(v)
|
|
190
|
+
return result
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class YamlDialect:
|
|
194
|
+
"""Dialect fully driven by a declarative YAML configuration."""
|
|
195
|
+
|
|
196
|
+
def __init__(self, config: dict[str, Any]):
|
|
197
|
+
validate_dialect_config(config)
|
|
198
|
+
self.raw_config = config
|
|
199
|
+
self.name: str = config.get("name", "Unknown")
|
|
200
|
+
self.abstract: bool = bool(config.get("abstract", False))
|
|
201
|
+
|
|
202
|
+
# Syntax configuration
|
|
203
|
+
syntax = config.get("syntax", {})
|
|
204
|
+
self.syntax_config = syntax
|
|
205
|
+
self.quote_char: str = syntax.get("quote_char", '"')
|
|
206
|
+
self.concat_op: str = syntax.get("concat", " || ")
|
|
207
|
+
self.to_string_tmpl: str = syntax.get("to_string", "cast({value} as varchar)")
|
|
208
|
+
self.coalesce_tmpl: str = syntax.get("coalesce", "coalesce({value}, {default})")
|
|
209
|
+
self.hash_charset: str | None = config.get("hash_charset")
|
|
210
|
+
self.set_timezone_sql: str | None = syntax.get("set_timezone_to_utc")
|
|
211
|
+
self.timestamp_literal_tmpl: str = syntax.get("timestamp_literal", "'{iso}'")
|
|
212
|
+
self.float_precision_offset: int = int(syntax.get("float_precision_offset", 0))
|
|
213
|
+
|
|
214
|
+
# Capabilities
|
|
215
|
+
caps = config.get("capabilities", {})
|
|
216
|
+
self.ROUNDS_ON_PREC_LOSS: bool = bool(caps.get("rounds_on_prec_loss", True))
|
|
217
|
+
|
|
218
|
+
# Normalization configuration
|
|
219
|
+
self.norm_templates: dict[str, str] = config.get("normalization", {})
|
|
220
|
+
|
|
221
|
+
# Type mapping configuration: native type name (case/whitespace-normalized) -> (ColType class, default args)
|
|
222
|
+
self.TYPE_CLASSES: dict[str, tuple[type[ColType], tuple]] = {
|
|
223
|
+
_type_key(type_name): _parse_class_spec(cls_spec) for type_name, cls_spec in config.get("type_classes", {}).items()
|
|
224
|
+
}
|
|
225
|
+
self._parsed_types: dict[str, ColType] = {} # parse_type() cache
|
|
226
|
+
|
|
227
|
+
# Type regexes
|
|
228
|
+
self.type_regexps: list[tuple[re.Pattern, type[ColType], dict]] = []
|
|
229
|
+
for pattern_str, regex_cfg in config.get("type_regexps", {}).items():
|
|
230
|
+
target_class = TYPE_NAME_TO_CLASS.get(regex_cfg.get("type"))
|
|
231
|
+
if target_class:
|
|
232
|
+
self.type_regexps.append((re.compile(pattern_str, re.IGNORECASE), target_class, regex_cfg))
|
|
233
|
+
|
|
234
|
+
@classmethod
|
|
235
|
+
def load(cls, name_or_path: str | Path) -> "YamlDialect":
|
|
236
|
+
"""Loads a YamlDialect by name (e.g. 'oracle') or absolute/relative file path."""
|
|
237
|
+
path = Path(name_or_path)
|
|
238
|
+
if not path.is_file():
|
|
239
|
+
if not str(name_or_path).endswith(".yaml"):
|
|
240
|
+
path = DIALECTS_DIR / f"{name_or_path}.yaml"
|
|
241
|
+
else:
|
|
242
|
+
path = DIALECTS_DIR / name_or_path
|
|
243
|
+
|
|
244
|
+
if not path.exists():
|
|
245
|
+
raise FileNotFoundError(f"Dialect YAML configuration not found: {path}")
|
|
246
|
+
|
|
247
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
248
|
+
cfg = yaml.safe_load(f) or {}
|
|
249
|
+
|
|
250
|
+
# type_classes lookups ignore case and spacing, so merge on the normalized name: a child's `DATE`
|
|
251
|
+
# must replace its parent's `date` instead of sitting next to it
|
|
252
|
+
if isinstance(cfg.get("type_classes"), dict):
|
|
253
|
+
cfg["type_classes"] = {_type_key(str(k)): v for k, v in cfg["type_classes"].items()}
|
|
254
|
+
|
|
255
|
+
# Handle inheritance (extends). `abstract` describes this file only and is never inherited.
|
|
256
|
+
if cfg.get("extends"):
|
|
257
|
+
is_abstract = bool(cfg.get("abstract", False))
|
|
258
|
+
base_dialect = cls.load(cfg["extends"])
|
|
259
|
+
cfg = deep_merge(base_dialect.raw_config, cfg)
|
|
260
|
+
cfg["abstract"] = is_abstract
|
|
261
|
+
|
|
262
|
+
return cls(cfg)
|
|
263
|
+
|
|
264
|
+
def quote(self, s: str) -> str:
|
|
265
|
+
return f"{self.quote_char}{s}{self.quote_char}"
|
|
266
|
+
|
|
267
|
+
def to_string(self, s: str) -> str:
|
|
268
|
+
return self.to_string_tmpl.format(value=s)
|
|
269
|
+
|
|
270
|
+
def concat(self, items: list[str]) -> str:
|
|
271
|
+
assert len(items) > 1, items
|
|
272
|
+
if self.concat_op.strip() == "concat":
|
|
273
|
+
joined = ", ".join(items)
|
|
274
|
+
return f"concat({joined})"
|
|
275
|
+
joined = f" {self.concat_op} ".join(items)
|
|
276
|
+
return f"({joined})"
|
|
277
|
+
|
|
278
|
+
def timestamp_value(self, t: DbTime) -> str:
|
|
279
|
+
return self.timestamp_literal_tmpl.format(iso=t.isoformat(), iso_space=t.isoformat(" "))
|
|
280
|
+
|
|
281
|
+
def uuid_value(self, u: UUID) -> str:
|
|
282
|
+
return f"'{u}'"
|
|
283
|
+
|
|
284
|
+
def set_timezone_to_utc(self) -> str:
|
|
285
|
+
if self.set_timezone_sql:
|
|
286
|
+
return self.set_timezone_sql
|
|
287
|
+
raise NotImplementedError(f"Database '{self.name}' does not allow setting timezone.")
|
|
288
|
+
|
|
289
|
+
# --- Type Parsing ---
|
|
290
|
+
|
|
291
|
+
def _convert_db_precision_to_digits(self, p: int) -> int:
|
|
292
|
+
digits = math.floor(math.log10(2**p))
|
|
293
|
+
return digits + self.float_precision_offset
|
|
294
|
+
|
|
295
|
+
def parse_type(self, type_str: str) -> ColType:
|
|
296
|
+
"""Turn a native type name into a diffdb ColType, e.g. 'NUMBER(12,2)' -> Decimal(precision=2).
|
|
297
|
+
|
|
298
|
+
1. `type_regexps` are tried on the full name, in file order (first match wins).
|
|
299
|
+
2. Otherwise the name is split as NAME(args) SUFFIX, e.g. 'TIMESTAMP(3) WITH TIME ZONE',
|
|
300
|
+
'character varying(100)', 'double precision'. "NAME SUFFIX" is looked up in `type_classes`
|
|
301
|
+
(case- and whitespace-insensitive) and the class builds itself from the integer args.
|
|
302
|
+
Returns UnknownColType for names that are not mapped (TableSegment rejects those).
|
|
303
|
+
"""
|
|
304
|
+
cached = self._parsed_types.get(type_str)
|
|
305
|
+
if cached is None:
|
|
306
|
+
cached = self._parsed_types[type_str] = self._parse_type(type_str)
|
|
307
|
+
return cached
|
|
308
|
+
|
|
309
|
+
def _parse_type(self, type_str: str) -> ColType:
|
|
310
|
+
for pattern, cls, cfg in self.type_regexps:
|
|
311
|
+
m = pattern.search(type_str)
|
|
312
|
+
if m:
|
|
313
|
+
if cfg.get("has_precision") and m.groups():
|
|
314
|
+
return cls(precision=int(m.group(1)), rounds=self.ROUNDS_ON_PREC_LOSS)
|
|
315
|
+
if cfg.get("has_scale") and len(m.groups()) >= 2:
|
|
316
|
+
return cls(precision=int(m.group(2)))
|
|
317
|
+
return cls()
|
|
318
|
+
|
|
319
|
+
m = _TYPE_NAME_RE.match(type_str)
|
|
320
|
+
if not m:
|
|
321
|
+
return UnknownColType(type_str)
|
|
322
|
+
cls, default_args = self.TYPE_CLASSES.get(_type_key(f"{m['name']} {m['suffix'] or ''}"), (None, ()))
|
|
323
|
+
if cls is None:
|
|
324
|
+
return UnknownColType(type_str)
|
|
325
|
+
args = tuple(_leading_int(a) for a in m["args"].split(",")) if m["args"] else default_args
|
|
326
|
+
coltype = cls.from_type_args(self, args)
|
|
327
|
+
return coltype if coltype is not None else UnknownColType(type_str)
|
|
328
|
+
|
|
329
|
+
# --- Normalization and MD5 ---
|
|
330
|
+
|
|
331
|
+
def coalesce(self, value: str, default: str = "'<null>'") -> str:
|
|
332
|
+
return self.coalesce_tmpl.format(value=value, default=default)
|
|
333
|
+
|
|
334
|
+
def md5_as_int(self, s: str) -> str:
|
|
335
|
+
tmpl = self.norm_templates.get("md5_as_int")
|
|
336
|
+
if not tmpl:
|
|
337
|
+
raise NotImplementedError(f"md5_as_int not configured for dialect {self.name}")
|
|
338
|
+
hash_charset = self.hash_charset
|
|
339
|
+
if hash_charset:
|
|
340
|
+
wrap = self.norm_templates.get("hash_charset_wrap")
|
|
341
|
+
if not wrap:
|
|
342
|
+
raise NotImplementedError(
|
|
343
|
+
f"hash_charset={hash_charset!r} is set but dialect {self.name} has no `normalization.hash_charset_wrap`"
|
|
344
|
+
)
|
|
345
|
+
s = wrap.format(s=s, charset=hash_charset)
|
|
346
|
+
return tmpl.format(s=s, CHECKSUM_MASK=CHECKSUM_MASK)
|
|
347
|
+
|
|
348
|
+
def normalize_value_by_type(self, value: str, coltype: ColType) -> str:
|
|
349
|
+
"""SQL that renders `value` as the canonical string that is compared and hashed.
|
|
350
|
+
|
|
351
|
+
Dispatches on `coltype.norm_key` (see the type registry in diffdb/types.py):
|
|
352
|
+
|
|
353
|
+
"timestamp" -> normalize_timestamp() (TemporalType)
|
|
354
|
+
"number" -> normalize_number() (FractionalType)
|
|
355
|
+
"uuid" -> normalize_uuid() (ColType_UUID)
|
|
356
|
+
"boolean" -> normalize_boolean() (Boolean)
|
|
357
|
+
"string" -> normalize_string() (StringType)
|
|
358
|
+
other key -> normalize_by_template() (types added without a dedicated method)
|
|
359
|
+
None -> to_string() (Integer, unknown types)
|
|
360
|
+
"""
|
|
361
|
+
norm_key = coltype.norm_key
|
|
362
|
+
if norm_key is None:
|
|
363
|
+
return self.to_string(value)
|
|
364
|
+
method = getattr(self, f"normalize_{norm_key}", None)
|
|
365
|
+
if method is not None:
|
|
366
|
+
return method(value, coltype)
|
|
367
|
+
return self.normalize_by_template(norm_key, value, coltype)
|
|
368
|
+
|
|
369
|
+
def normalize_timestamp(self, value: str, coltype: TemporalType) -> str:
|
|
370
|
+
"""'YYYY-MM-DD HH:MI:SS.FFFFFF', cut (or rounded, if coltype.rounds) to coltype.precision digits."""
|
|
371
|
+
precision = getattr(coltype, "precision", 6)
|
|
372
|
+
rounds = getattr(coltype, "rounds", False)
|
|
373
|
+
|
|
374
|
+
if rounds and "timestamp_rounded" in self.norm_templates:
|
|
375
|
+
return self.norm_templates["timestamp_rounded"].format(value=value, precision=precision)
|
|
376
|
+
|
|
377
|
+
if precision == 0 and "timestamp_zero_precision" in self.norm_templates:
|
|
378
|
+
return self.norm_templates["timestamp_zero_precision"].format(value=value, precision=precision)
|
|
379
|
+
|
|
380
|
+
if precision == 6 and "timestamp_six_precision" in self.norm_templates:
|
|
381
|
+
return self.norm_templates["timestamp_six_precision"].format(value=value, precision=precision)
|
|
382
|
+
|
|
383
|
+
if "timestamp_precision" in self.norm_templates:
|
|
384
|
+
return self.norm_templates["timestamp_precision"].format(value=value, precision=precision)
|
|
385
|
+
|
|
386
|
+
if "timestamp_unrounded" in self.norm_templates:
|
|
387
|
+
return self.norm_templates["timestamp_unrounded"].format(value=value, precision=precision)
|
|
388
|
+
|
|
389
|
+
return self.to_string(value)
|
|
390
|
+
|
|
391
|
+
def normalize_number(self, value: str, coltype: FractionalType) -> str:
|
|
392
|
+
"""'I.P': at least one integer digit, exactly coltype.precision fractional digits, no dot if 0."""
|
|
393
|
+
precision = getattr(coltype, "precision", 0)
|
|
394
|
+
if precision is None:
|
|
395
|
+
precision = 0 # unscaled Decimal; HashDiffer warns about these before hashing
|
|
396
|
+
tmpl = self.norm_templates.get("number")
|
|
397
|
+
if tmpl:
|
|
398
|
+
format_str = ""
|
|
399
|
+
if "format_str" in _placeholders(tmpl):
|
|
400
|
+
# Oracle-style FM number mask: up to 38 digits with `precision` fractional digits
|
|
401
|
+
format_str = "FM" + "9" * (38 - precision)
|
|
402
|
+
if precision:
|
|
403
|
+
format_str += "0." + "9" * (precision - 1) + "0"
|
|
404
|
+
return tmpl.format(value=value, precision=precision, format_str=format_str)
|
|
405
|
+
return self.to_string(value)
|
|
406
|
+
|
|
407
|
+
def normalize_boolean(self, value: str, _coltype: Boolean) -> str:
|
|
408
|
+
"""'1' / '0'."""
|
|
409
|
+
tmpl = self.norm_templates.get("boolean")
|
|
410
|
+
if tmpl:
|
|
411
|
+
return tmpl.format(value=value)
|
|
412
|
+
return self.to_string(f"cast({value} as int)")
|
|
413
|
+
|
|
414
|
+
def normalize_uuid(self, value: str, coltype: ColType_UUID) -> str:
|
|
415
|
+
tmpl = self.norm_templates.get("uuid")
|
|
416
|
+
if tmpl:
|
|
417
|
+
return tmpl.format(value=value)
|
|
418
|
+
return f"CAST(TRIM({value}) AS VARCHAR(36))"
|
|
419
|
+
|
|
420
|
+
def normalize_string(self, value: str, _coltype: StringType) -> str:
|
|
421
|
+
"""Strings are hashed as-is."""
|
|
422
|
+
return value
|
|
423
|
+
|
|
424
|
+
def normalize_by_template(self, norm_key: str, value: str, coltype: ColType) -> str:
|
|
425
|
+
tmpl = self.norm_templates.get(norm_key)
|
|
426
|
+
if not tmpl:
|
|
427
|
+
raise NotImplementedError(f"Dialect {self.name} has no `normalization.{norm_key}` template for type {coltype}")
|
|
428
|
+
return tmpl.format(value=value, precision=getattr(coltype, "precision", None))
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Geometry and space partitioning utilities for diffdb.
|
|
2
|
+
"""
|
|
3
|
+
|
|
4
|
+
from .arithmetic import (
|
|
5
|
+
ArithAlphanumeric,
|
|
6
|
+
ArithString,
|
|
7
|
+
ArithUUID,
|
|
8
|
+
alphanums,
|
|
9
|
+
alphanums_to_numbers,
|
|
10
|
+
alphanumToNumber,
|
|
11
|
+
justify_alphanums,
|
|
12
|
+
numberToAlphanum,
|
|
13
|
+
split_space,
|
|
14
|
+
)
|
|
15
|
+
from .bisection import (
|
|
16
|
+
create_mesh_from_points,
|
|
17
|
+
int_product,
|
|
18
|
+
split_compound_key_space,
|
|
19
|
+
split_datetime_range,
|
|
20
|
+
split_decimal_range,
|
|
21
|
+
split_key_space,
|
|
22
|
+
)
|
|
23
|
+
from .vector import Vector
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"ArithAlphanumeric",
|
|
27
|
+
"ArithString",
|
|
28
|
+
"ArithUUID",
|
|
29
|
+
"Vector",
|
|
30
|
+
"alphanumToNumber",
|
|
31
|
+
"alphanums",
|
|
32
|
+
"alphanums_to_numbers",
|
|
33
|
+
"create_mesh_from_points",
|
|
34
|
+
"int_product",
|
|
35
|
+
"justify_alphanums",
|
|
36
|
+
"numberToAlphanum",
|
|
37
|
+
"split_compound_key_space",
|
|
38
|
+
"split_datetime_range",
|
|
39
|
+
"split_decimal_range",
|
|
40
|
+
"split_key_space",
|
|
41
|
+
"split_space",
|
|
42
|
+
]
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Arithmetic abstractions for strings, UUIDs, and alphanumerics to enable space slicing.
|
|
2
|
+
"""
|
|
3
|
+
|
|
4
|
+
import string
|
|
5
|
+
from abc import ABC
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
alphanums = " -." + string.digits + string.ascii_uppercase + "_" + string.ascii_lowercase
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def split_space(start: int, end: int, count: int) -> list[int]:
|
|
12
|
+
"""Split an integer range into count evenly-spaced interior checkpoints."""
|
|
13
|
+
size = end - start
|
|
14
|
+
assert count <= size, (count, size)
|
|
15
|
+
return list(range(start, end, (size + 1) // (count + 1)))[1 : count + 1]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ArithString(ABC):
|
|
19
|
+
@classmethod
|
|
20
|
+
def new(cls, *args, **kw):
|
|
21
|
+
return cls(*args, **kw)
|
|
22
|
+
|
|
23
|
+
def range(self, other: "ArithString", count: int):
|
|
24
|
+
assert isinstance(other, ArithString)
|
|
25
|
+
checkpoints = split_space(self.int, other.int, count)
|
|
26
|
+
return [self.new(int=i) for i in checkpoints]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ArithUUID(UUID, ArithString):
|
|
30
|
+
"""A UUID that supports basic arithmetic (add, sub)."""
|
|
31
|
+
|
|
32
|
+
def __int__(self):
|
|
33
|
+
return self.int
|
|
34
|
+
|
|
35
|
+
def __add__(self, other: int):
|
|
36
|
+
if isinstance(other, int):
|
|
37
|
+
return self.new(int=self.int + other)
|
|
38
|
+
return NotImplemented
|
|
39
|
+
|
|
40
|
+
def __sub__(self, other: UUID | int):
|
|
41
|
+
if isinstance(other, int):
|
|
42
|
+
return self.new(int=self.int - other)
|
|
43
|
+
if isinstance(other, UUID):
|
|
44
|
+
return self.int - other.int
|
|
45
|
+
return NotImplemented
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def numberToAlphanum(num: int, base: str = alphanums) -> str:
|
|
49
|
+
digits = []
|
|
50
|
+
while num > 0:
|
|
51
|
+
num, remainder = divmod(num, len(base))
|
|
52
|
+
digits.append(remainder)
|
|
53
|
+
return "".join(base[i] for i in digits[::-1])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def alphanumToNumber(alphanum: str, base: str = alphanums) -> int:
|
|
57
|
+
num = 0
|
|
58
|
+
for c in alphanum:
|
|
59
|
+
num = num * len(base) + base.index(c)
|
|
60
|
+
return num
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def justify_alphanums(s1: str, s2: str):
|
|
64
|
+
max_len = max(len(s1), len(s2))
|
|
65
|
+
s1 = s1.ljust(max_len)
|
|
66
|
+
s2 = s2.ljust(max_len)
|
|
67
|
+
return s1, s2
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def alphanums_to_numbers(s1: str, s2: str):
|
|
71
|
+
s1, s2 = justify_alphanums(s1, s2)
|
|
72
|
+
n1 = alphanumToNumber(s1)
|
|
73
|
+
n2 = alphanumToNumber(s2)
|
|
74
|
+
return n1, n2
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ArithAlphanumeric(ArithString):
|
|
78
|
+
"""Alphanumeric string wrapper that supports arithmetic operations for interval bisection."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, s: str, max_len=None):
|
|
81
|
+
if s is None:
|
|
82
|
+
raise ValueError("Alphanum string cannot be None")
|
|
83
|
+
if max_len and len(s) > max_len:
|
|
84
|
+
raise ValueError(f"Length of alphanum value '{s}' is longer than the expected {max_len}")
|
|
85
|
+
|
|
86
|
+
for ch in s:
|
|
87
|
+
if ch not in alphanums:
|
|
88
|
+
raise ValueError(f"Unexpected character {ch} in alphanum string")
|
|
89
|
+
|
|
90
|
+
self._str = s
|
|
91
|
+
self._max_len = max_len
|
|
92
|
+
|
|
93
|
+
def __str__(self):
|
|
94
|
+
s = self._str
|
|
95
|
+
if self._max_len:
|
|
96
|
+
s = s.rjust(self._max_len, alphanums[0])
|
|
97
|
+
return s
|
|
98
|
+
|
|
99
|
+
def __len__(self):
|
|
100
|
+
return len(self._str)
|
|
101
|
+
|
|
102
|
+
def __repr__(self):
|
|
103
|
+
return f'alphanum"{self._str}"'
|
|
104
|
+
|
|
105
|
+
def __add__(self, other: "ArithAlphanumeric | int") -> "ArithAlphanumeric":
|
|
106
|
+
if isinstance(other, int):
|
|
107
|
+
if other != 1:
|
|
108
|
+
raise NotImplementedError("not implemented for arbitrary numbers")
|
|
109
|
+
num = alphanumToNumber(self._str)
|
|
110
|
+
return self.new(numberToAlphanum(num + 1))
|
|
111
|
+
return NotImplemented
|
|
112
|
+
|
|
113
|
+
def range(self, other: "ArithAlphanumeric", count: int):
|
|
114
|
+
assert isinstance(other, ArithAlphanumeric)
|
|
115
|
+
n1, n2 = alphanums_to_numbers(self._str, other._str)
|
|
116
|
+
split = split_space(n1, n2, count)
|
|
117
|
+
return [self.new(numberToAlphanum(s)) for s in split]
|
|
118
|
+
|
|
119
|
+
def __sub__(self, other: "ArithAlphanumeric | int") -> float:
|
|
120
|
+
if isinstance(other, ArithAlphanumeric):
|
|
121
|
+
n1, n2 = alphanums_to_numbers(self._str, other._str)
|
|
122
|
+
return n1 - n2
|
|
123
|
+
return NotImplemented
|
|
124
|
+
|
|
125
|
+
def __ge__(self, other):
|
|
126
|
+
if not isinstance(other, type(self)):
|
|
127
|
+
return NotImplemented
|
|
128
|
+
return self._str >= other._str
|
|
129
|
+
|
|
130
|
+
def __lt__(self, other):
|
|
131
|
+
if not isinstance(other, type(self)):
|
|
132
|
+
return NotImplemented
|
|
133
|
+
return self._str < other._str
|
|
134
|
+
|
|
135
|
+
def __eq__(self, other):
|
|
136
|
+
if not isinstance(other, type(self)):
|
|
137
|
+
return NotImplemented
|
|
138
|
+
return self._str == other._str
|
|
139
|
+
|
|
140
|
+
def new(self, *args, **kw):
|
|
141
|
+
return type(self)(*args, **kw, max_len=self._max_len)
|