seed-dev-db 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.
- seed/__init__.py +3 -0
- seed/cli.py +395 -0
- seed/config.py +251 -0
- seed/exporting/__init__.py +1 -0
- seed/exporting/files.py +165 -0
- seed/exporting/sql.py +84 -0
- seed/exporting/tabular.py +46 -0
- seed/generation/__init__.py +1 -0
- seed/generation/engine.py +260 -0
- seed/generation/record_checks.py +180 -0
- seed/generation/relationships.py +213 -0
- seed/generation/scalars.py +112 -0
- seed/generation/streaming.py +124 -0
- seed/metadata.py +126 -0
- seed/planning/__init__.py +1 -0
- seed/planning/bindings.py +138 -0
- seed/planning/dependencies.py +123 -0
- seed/planning/numeric.py +122 -0
- seed/planning/plan.py +305 -0
- seed/planning/selection.py +62 -0
- seed/postgres/__init__.py +1 -0
- seed/postgres/apply_guard.py +268 -0
- seed/postgres/catalog.py +386 -0
- seed/postgres/connection.py +160 -0
- seed/postgres/insertion.py +237 -0
- seed/postgres/inspection.py +76 -0
- seed/postgres/schema.py +234 -0
- seed/reporting/__init__.py +1 -0
- seed/reporting/dataset.py +72 -0
- seed/reporting/inspection.py +65 -0
- seed/reporting/plan.py +64 -0
- seed/workflows/__init__.py +1 -0
- seed/workflows/apply.py +95 -0
- seed/workflows/export.py +168 -0
- seed/workflows/initialize.py +53 -0
- seed/workflows/preview.py +101 -0
- seed/workflows/validate.py +94 -0
- seed_dev_db-0.1.0.dist-info/METADATA +29 -0
- seed_dev_db-0.1.0.dist-info/RECORD +42 -0
- seed_dev_db-0.1.0.dist-info/WHEEL +4 -0
- seed_dev_db-0.1.0.dist-info/entry_points.txt +2 -0
- seed_dev_db-0.1.0.dist-info/licenses/LICENSE +202 -0
seed/metadata.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Typed schema metadata and deterministic serialization."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
9
|
+
|
|
10
|
+
type Capability = Literal["MVP", "Partial", "Detected only", "Future"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Metadata(BaseModel):
|
|
14
|
+
model_config = ConfigDict(frozen=True)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TableId(Metadata):
|
|
18
|
+
schema_name: str = Field(alias="schema")
|
|
19
|
+
table: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Target(Metadata):
|
|
23
|
+
host: str
|
|
24
|
+
port: int
|
|
25
|
+
database: str
|
|
26
|
+
schema_name: str = Field(alias="schema")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Feature(Metadata):
|
|
30
|
+
name: str
|
|
31
|
+
status: Capability
|
|
32
|
+
reason: str | None = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ColumnType(Metadata):
|
|
36
|
+
name: str
|
|
37
|
+
supported: bool
|
|
38
|
+
length: int | None = None
|
|
39
|
+
precision: int | None = None
|
|
40
|
+
scale: int | None = None
|
|
41
|
+
timezone: bool | None = None
|
|
42
|
+
enum_labels: tuple[str, ...] = ()
|
|
43
|
+
type_schema: str | None = None
|
|
44
|
+
type_name: str | None = None
|
|
45
|
+
collation: str | None = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ColumnSchema(Metadata):
|
|
49
|
+
name: str
|
|
50
|
+
ordinal: int
|
|
51
|
+
type: ColumnType
|
|
52
|
+
nullable: bool
|
|
53
|
+
default_kind: str
|
|
54
|
+
identity: str | None = None
|
|
55
|
+
sequence_max: int | None = None
|
|
56
|
+
generated: str | None = None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Key(Metadata):
|
|
60
|
+
name: str
|
|
61
|
+
columns: tuple[str, ...]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ForeignKey(Key):
|
|
65
|
+
parent: TableId
|
|
66
|
+
parent_columns: tuple[str, ...]
|
|
67
|
+
match: str = "SIMPLE"
|
|
68
|
+
validated: bool | None = None
|
|
69
|
+
deferrable: bool = False
|
|
70
|
+
enforced: bool | None = None
|
|
71
|
+
on_update: str = "NO ACTION"
|
|
72
|
+
on_delete: str = "NO ACTION"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class UniqueKey(Key):
|
|
76
|
+
nulls_distinct: bool | None = None
|
|
77
|
+
source: str = "constraint"
|
|
78
|
+
supported: bool | None = None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class NumericBound(Metadata):
|
|
82
|
+
column: str
|
|
83
|
+
operator: str
|
|
84
|
+
value: str
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Check(Key):
|
|
88
|
+
status: Capability = "Detected only"
|
|
89
|
+
validated: bool | None = None
|
|
90
|
+
bounds: tuple[NumericBound, ...] = ()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class TableSchema(Metadata):
|
|
94
|
+
id: TableId
|
|
95
|
+
kind: str
|
|
96
|
+
columns: tuple[ColumnSchema, ...]
|
|
97
|
+
primary_key: Key | None = None
|
|
98
|
+
foreign_keys: tuple[ForeignKey, ...] = ()
|
|
99
|
+
unique_keys: tuple[UniqueKey, ...] = ()
|
|
100
|
+
checks: tuple[Check, ...] = ()
|
|
101
|
+
features: tuple[Feature, ...] = ()
|
|
102
|
+
issues: tuple[str, ...] = ()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class DatabaseSchema(Metadata):
|
|
106
|
+
target: Target
|
|
107
|
+
server_major: int
|
|
108
|
+
schemas: tuple[str, ...]
|
|
109
|
+
tables: tuple[TableSchema, ...]
|
|
110
|
+
fingerprint: str
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True)
|
|
114
|
+
class Inspection:
|
|
115
|
+
"""Public metadata and private evidence for a later live comparison."""
|
|
116
|
+
|
|
117
|
+
schema: DatabaseSchema
|
|
118
|
+
catalog_identities: tuple[tuple[str, int], ...]
|
|
119
|
+
definition_digest: str
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def digest(value: object) -> str:
|
|
123
|
+
"""Fingerprint ordered, JSON-compatible structural data."""
|
|
124
|
+
return hashlib.sha256(
|
|
125
|
+
json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode()
|
|
126
|
+
).hexdigest()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Table selection, dependencies, and generation plans."""
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Choose and validate planned generators without producing values."""
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, date, datetime
|
|
4
|
+
from decimal import Decimal, DecimalException
|
|
5
|
+
from uuid import UUID
|
|
6
|
+
|
|
7
|
+
from seed.config import GeneratorRule, Scalar
|
|
8
|
+
from seed.metadata import ColumnSchema, Metadata, NumericBound
|
|
9
|
+
from seed.planning.numeric import INTEGER_BITS, numeric_grid
|
|
10
|
+
|
|
11
|
+
_GENERIC = {
|
|
12
|
+
**dict.fromkeys(INTEGER_BITS, "integer"),
|
|
13
|
+
"numeric": "decimal",
|
|
14
|
+
"text": "text",
|
|
15
|
+
"varchar": "text",
|
|
16
|
+
"boolean": "boolean",
|
|
17
|
+
"date": "date",
|
|
18
|
+
"timestamp": "datetime",
|
|
19
|
+
"uuid": "uuid",
|
|
20
|
+
"enum": "choice",
|
|
21
|
+
}
|
|
22
|
+
_SEMANTIC = {
|
|
23
|
+
**dict.fromkeys(("email", "email_address"), "email"),
|
|
24
|
+
**dict.fromkeys(("phone", "phone_number"), "phone"),
|
|
25
|
+
**{
|
|
26
|
+
name: name
|
|
27
|
+
for name in ("first_name", "last_name", "name", "address", "city", "country", "description")
|
|
28
|
+
},
|
|
29
|
+
}
|
|
30
|
+
_TEXT_GENERATORS = frozenset(_SEMANTIC.values()) | {"text"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Binding(Metadata):
|
|
34
|
+
column: str
|
|
35
|
+
source: str
|
|
36
|
+
generator: str | None = None
|
|
37
|
+
foreign_key: str | None = None
|
|
38
|
+
explicit: bool = False
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def choose_binding(
|
|
42
|
+
column: ColumnSchema,
|
|
43
|
+
rule: GeneratorRule | None,
|
|
44
|
+
locale: str,
|
|
45
|
+
bounds: tuple[NumericBound, ...],
|
|
46
|
+
) -> tuple[Binding, bool]:
|
|
47
|
+
"""Select a generator and report whether its bindings fit the reflected schema."""
|
|
48
|
+
kind = column.type
|
|
49
|
+
generic = _GENERIC.get(kind.name)
|
|
50
|
+
inferred = _SEMANTIC.get(column.name.lower()) if generic == "text" else None
|
|
51
|
+
if inferred == "phone" and (
|
|
52
|
+
locale != "en_US" or (kind.length is not None and kind.length < 15)
|
|
53
|
+
):
|
|
54
|
+
inferred = None
|
|
55
|
+
if inferred == "email" and kind.length is not None and kind.length < 13:
|
|
56
|
+
inferred = None
|
|
57
|
+
explicit = rule.generator if rule else None
|
|
58
|
+
generator = explicit or inferred or generic
|
|
59
|
+
binding = Binding(
|
|
60
|
+
column=column.name, source="generator", generator=generator, explicit=rule is not None
|
|
61
|
+
)
|
|
62
|
+
if not kind.supported or not generator or not generic:
|
|
63
|
+
return binding, False
|
|
64
|
+
if rule and rule.null_rate and not column.nullable:
|
|
65
|
+
return binding, False
|
|
66
|
+
if explicit == "phone" and (
|
|
67
|
+
locale != "en_US" or (kind.length is not None and kind.length < 15)
|
|
68
|
+
):
|
|
69
|
+
return binding, False
|
|
70
|
+
if explicit == "email" and kind.length is not None and kind.length < 13:
|
|
71
|
+
return binding, False
|
|
72
|
+
if explicit in {"choice", "constant"}:
|
|
73
|
+
assert rule is not None
|
|
74
|
+
values = rule.values if rule.values is not None else [rule.value]
|
|
75
|
+
valid_values = all(
|
|
76
|
+
value is not None and compatible_value(value, column, bounds) for value in values
|
|
77
|
+
)
|
|
78
|
+
if valid_values and kind.name == "numeric":
|
|
79
|
+
normalized = {Decimal(value) for value in values if isinstance(value, (int, str))}
|
|
80
|
+
valid_values = len(normalized) == len(values)
|
|
81
|
+
return binding, valid_values
|
|
82
|
+
if generator != generic and not (generic == "text" and generator in _TEXT_GENERATORS):
|
|
83
|
+
return binding, False
|
|
84
|
+
if generic == "choice" and not kind.enum_labels:
|
|
85
|
+
return binding, False
|
|
86
|
+
if generic in {"integer", "decimal"}:
|
|
87
|
+
return binding, _feasible_numeric(column, rule, bounds)
|
|
88
|
+
return binding, True
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def compatible_value(value: Scalar, column: ColumnSchema, bounds: tuple[NumericBound, ...]) -> bool:
|
|
92
|
+
"""Check an exact scalar against its reflected type and numeric checks."""
|
|
93
|
+
kind = column.type
|
|
94
|
+
if kind.name in INTEGER_BITS:
|
|
95
|
+
return type(value) is int and _feasible_numeric(column, None, bounds, Decimal(value))
|
|
96
|
+
if kind.name == "numeric":
|
|
97
|
+
if not isinstance(value, str) and type(value) is not int:
|
|
98
|
+
return False
|
|
99
|
+
try:
|
|
100
|
+
return _feasible_numeric(column, None, bounds, Decimal(value))
|
|
101
|
+
except DecimalException:
|
|
102
|
+
return False
|
|
103
|
+
if kind.name in {"text", "varchar", "enum"}:
|
|
104
|
+
return (
|
|
105
|
+
isinstance(value, str)
|
|
106
|
+
and "\x00" not in value
|
|
107
|
+
and (kind.length is None or len(value) <= kind.length)
|
|
108
|
+
and (kind.name != "enum" or value in kind.enum_labels)
|
|
109
|
+
)
|
|
110
|
+
if kind.name == "uuid" and isinstance(value, str):
|
|
111
|
+
try:
|
|
112
|
+
return str(UUID(value)) == value
|
|
113
|
+
except ValueError:
|
|
114
|
+
return False
|
|
115
|
+
if kind.name == "boolean":
|
|
116
|
+
return type(value) is bool
|
|
117
|
+
if kind.name == "date":
|
|
118
|
+
return type(value) is date
|
|
119
|
+
if kind.name == "timestamp" and isinstance(value, datetime):
|
|
120
|
+
aware = value.utcoffset() is not None
|
|
121
|
+
if aware != bool(kind.timezone):
|
|
122
|
+
return False
|
|
123
|
+
try:
|
|
124
|
+
normalized = value.astimezone(UTC) if aware else value
|
|
125
|
+
except OverflowError:
|
|
126
|
+
return False
|
|
127
|
+
precision = kind.precision if kind.precision is not None else 6
|
|
128
|
+
return bool(normalized.microsecond % (10 ** (6 - precision)) == 0)
|
|
129
|
+
return False
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _feasible_numeric(
|
|
133
|
+
column: ColumnSchema,
|
|
134
|
+
rule: GeneratorRule | None,
|
|
135
|
+
bounds: tuple[NumericBound, ...],
|
|
136
|
+
value: Decimal | None = None,
|
|
137
|
+
) -> bool:
|
|
138
|
+
return numeric_grid(column, rule, bounds, value) is not None
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Expand required parents and order the generation graph."""
|
|
2
|
+
|
|
3
|
+
import heapq
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from seed.metadata import ForeignKey
|
|
9
|
+
from seed.planning.selection import Selection
|
|
10
|
+
|
|
11
|
+
type KeySource = Literal["generated", "existing", "none", "null"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Dependency:
|
|
16
|
+
key: ForeignKey
|
|
17
|
+
source: KeySource
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class GraphIssue:
|
|
22
|
+
table: str
|
|
23
|
+
code: str
|
|
24
|
+
message: str
|
|
25
|
+
constraint: str | None = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class DependencyGraph:
|
|
30
|
+
order: tuple[str, ...]
|
|
31
|
+
dependencies: dict[str, tuple[Dependency, ...]]
|
|
32
|
+
issues: tuple[GraphIssue, ...]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def resolve_dependencies(selection: Selection, null_rate: float) -> DependencyGraph:
|
|
36
|
+
"""Expand the reachable graph without reading any database rows."""
|
|
37
|
+
pending = list(selection.requested)
|
|
38
|
+
heapq.heapify(pending)
|
|
39
|
+
edges: dict[str, tuple[Dependency, ...]] = {}
|
|
40
|
+
issues: list[GraphIssue] = []
|
|
41
|
+
while pending:
|
|
42
|
+
name = heapq.heappop(pending)
|
|
43
|
+
if name in edges:
|
|
44
|
+
continue
|
|
45
|
+
table = selection.tables[name]
|
|
46
|
+
dependencies: list[Dependency] = []
|
|
47
|
+
if selection.counts[name]:
|
|
48
|
+
nullable = {column.name for column in table.columns if column.nullable}
|
|
49
|
+
unsupported = {
|
|
50
|
+
feature.name
|
|
51
|
+
for feature in table.features
|
|
52
|
+
if feature.reason == "UNSUPPORTED_FOREIGN_KEY"
|
|
53
|
+
}
|
|
54
|
+
for key in table.foreign_keys:
|
|
55
|
+
parent = key.parent.table
|
|
56
|
+
if key.parent == table.id:
|
|
57
|
+
code, message = (
|
|
58
|
+
"SELF_REFERENCE",
|
|
59
|
+
"Self-referencing foreign keys are unsupported.",
|
|
60
|
+
)
|
|
61
|
+
elif (
|
|
62
|
+
key.parent.schema_name != table.id.schema_name
|
|
63
|
+
or f"foreign key {key.name}" in unsupported
|
|
64
|
+
or key.validated is not True
|
|
65
|
+
or key.enforced is not True
|
|
66
|
+
or key.deferrable
|
|
67
|
+
or key.match != "SIMPLE"
|
|
68
|
+
):
|
|
69
|
+
code, message = "UNSUPPORTED_FOREIGN_KEY", "A foreign key is unsupported."
|
|
70
|
+
elif parent not in selection.tables:
|
|
71
|
+
code, message = "MISSING_PARENT", "A foreign key parent could not be inspected."
|
|
72
|
+
else:
|
|
73
|
+
source: KeySource = "none"
|
|
74
|
+
if null_rate == 1 and key.columns and nullable.issuperset(key.columns):
|
|
75
|
+
source = "null"
|
|
76
|
+
elif selection.counts[parent]:
|
|
77
|
+
source = "generated"
|
|
78
|
+
elif parent in selection.reuse_existing:
|
|
79
|
+
source = "existing"
|
|
80
|
+
dependencies.append(Dependency(key, source))
|
|
81
|
+
if source != "null":
|
|
82
|
+
heapq.heappush(pending, parent)
|
|
83
|
+
if source != "none":
|
|
84
|
+
continue
|
|
85
|
+
code, message = (
|
|
86
|
+
"EMPTY_PARENT",
|
|
87
|
+
"A foreign key has no planned parent key source.",
|
|
88
|
+
)
|
|
89
|
+
issues.append(GraphIssue(name, code, message, key.name))
|
|
90
|
+
edges[name] = tuple(dependencies)
|
|
91
|
+
|
|
92
|
+
order, unresolved = _parent_first(edges)
|
|
93
|
+
if unresolved:
|
|
94
|
+
issues.append(
|
|
95
|
+
GraphIssue(
|
|
96
|
+
unresolved[0],
|
|
97
|
+
"DEPENDENCY_CYCLE",
|
|
98
|
+
"A dependency cycle prevents ordering every reachable table.",
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
return DependencyGraph(tuple(order + unresolved), edges, tuple(issues))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _parent_first(edges: dict[str, tuple[Dependency, ...]]) -> tuple[list[str], list[str]]:
|
|
105
|
+
parents = {
|
|
106
|
+
name: {edge.key.parent.table for edge in dependencies if edge.source != "null"}
|
|
107
|
+
for name, dependencies in edges.items()
|
|
108
|
+
}
|
|
109
|
+
children: dict[str, set[str]] = defaultdict(set)
|
|
110
|
+
for name, requirements in parents.items():
|
|
111
|
+
for parent in requirements:
|
|
112
|
+
children[parent].add(name)
|
|
113
|
+
ready = [name for name, requirements in parents.items() if not requirements]
|
|
114
|
+
heapq.heapify(ready)
|
|
115
|
+
ordered = []
|
|
116
|
+
while ready:
|
|
117
|
+
ready_name = heapq.heappop(ready)
|
|
118
|
+
ordered.append(ready_name)
|
|
119
|
+
for child in children[ready_name]:
|
|
120
|
+
parents[child].remove(ready_name)
|
|
121
|
+
if not parents[child]:
|
|
122
|
+
heapq.heappush(ready, child)
|
|
123
|
+
return ordered, sorted(set(edges) - set(ordered))
|
seed/planning/numeric.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Share exact numeric domains between planning and generation."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from decimal import ROUND_CEILING, ROUND_FLOOR, Context, Decimal, DecimalException, localcontext
|
|
5
|
+
|
|
6
|
+
from seed.config import GeneratorRule
|
|
7
|
+
from seed.metadata import ColumnSchema, NumericBound
|
|
8
|
+
|
|
9
|
+
INTEGER_BITS = {"smallint": 16, "integer": 32, "bigint": 64}
|
|
10
|
+
_PG_NUMERIC_LIMIT = Decimal("1e131072")
|
|
11
|
+
_PG_NUMERIC_SCALE = 16_383
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class NumericGrid:
|
|
16
|
+
first: int
|
|
17
|
+
last: int
|
|
18
|
+
scale: int
|
|
19
|
+
|
|
20
|
+
def decimal(self, units: int) -> Decimal:
|
|
21
|
+
"""Convert an integer grid point without implicit context rounding."""
|
|
22
|
+
number = Decimal(units)
|
|
23
|
+
with localcontext(Context(prec=len(number.as_tuple().digits))):
|
|
24
|
+
return number.scaleb(-self.scale)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def numeric_grid(
|
|
28
|
+
column: ColumnSchema,
|
|
29
|
+
rule: GeneratorRule | None,
|
|
30
|
+
bounds: tuple[NumericBound, ...],
|
|
31
|
+
value: Decimal | None = None,
|
|
32
|
+
) -> NumericGrid | None:
|
|
33
|
+
"""Intersect schema, rule, and check constraints on a representable grid."""
|
|
34
|
+
if value is not None and not value.is_finite():
|
|
35
|
+
return None
|
|
36
|
+
lows: list[tuple[Decimal, bool]] = []
|
|
37
|
+
highs: list[tuple[Decimal, bool]] = []
|
|
38
|
+
for bound in bounds:
|
|
39
|
+
number = Decimal(bound.value)
|
|
40
|
+
if bound.operator in {">", ">=", "="}:
|
|
41
|
+
lows.append((number, bound.operator == ">"))
|
|
42
|
+
if bound.operator in {"<", "<=", "="}:
|
|
43
|
+
highs.append((number, bound.operator == "<"))
|
|
44
|
+
if rule and rule.min is not None:
|
|
45
|
+
lows.append((Decimal(rule.min), False))
|
|
46
|
+
if rule and rule.max is not None:
|
|
47
|
+
highs.append((Decimal(rule.max), False))
|
|
48
|
+
if value is not None:
|
|
49
|
+
lows.append((value, False))
|
|
50
|
+
highs.append((value, False))
|
|
51
|
+
|
|
52
|
+
kind = column.type
|
|
53
|
+
scale = kind.scale
|
|
54
|
+
if kind.name in INTEGER_BITS:
|
|
55
|
+
limit = 2 ** (INTEGER_BITS[kind.name] - 1)
|
|
56
|
+
lows.append((Decimal(-limit), False))
|
|
57
|
+
highs.append((Decimal(limit - 1), False))
|
|
58
|
+
scale = 0
|
|
59
|
+
elif kind.precision is not None and scale is not None:
|
|
60
|
+
limit_decimal = Decimal((0, (9,) * kind.precision, -scale))
|
|
61
|
+
lows.append((limit_decimal.copy_negate(), False))
|
|
62
|
+
highs.append((limit_decimal, False))
|
|
63
|
+
|
|
64
|
+
lower = max(lows, default=None)
|
|
65
|
+
upper = min(highs, key=lambda item: (item[0], not item[1]), default=None)
|
|
66
|
+
if lower and upper and lower[0] > upper[0]:
|
|
67
|
+
return None
|
|
68
|
+
if scale is None:
|
|
69
|
+
if lower and lower[0] >= _PG_NUMERIC_LIMIT:
|
|
70
|
+
return None
|
|
71
|
+
if upper and upper[0] <= _PG_NUMERIC_LIMIT.copy_negate():
|
|
72
|
+
return None
|
|
73
|
+
if lower and lower[0] <= _PG_NUMERIC_LIMIT.copy_negate():
|
|
74
|
+
lower = (_PG_NUMERIC_LIMIT.copy_negate(), True)
|
|
75
|
+
if upper and upper[0] >= _PG_NUMERIC_LIMIT:
|
|
76
|
+
upper = (_PG_NUMERIC_LIMIT, True)
|
|
77
|
+
# One extra decimal place permits sampling a nonempty open interval.
|
|
78
|
+
scale = min(
|
|
79
|
+
_PG_NUMERIC_SCALE,
|
|
80
|
+
max(
|
|
81
|
+
[
|
|
82
|
+
2,
|
|
83
|
+
*(
|
|
84
|
+
-int(bound[0].as_tuple().exponent) + int(bound[1])
|
|
85
|
+
for bound in (lower, upper)
|
|
86
|
+
if bound
|
|
87
|
+
),
|
|
88
|
+
],
|
|
89
|
+
),
|
|
90
|
+
)
|
|
91
|
+
try:
|
|
92
|
+
start = _units(lower, scale, True) if lower else None
|
|
93
|
+
end = _units(upper, scale, False) if upper else None
|
|
94
|
+
except DecimalException:
|
|
95
|
+
return None
|
|
96
|
+
if start is not None and end is not None and start > end:
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
if kind.name == "numeric" and kind.scale is None:
|
|
100
|
+
# Sample at most a bounded window of values near zero or the nearest bound.
|
|
101
|
+
span = 1000 * 10**scale
|
|
102
|
+
anchor = max(0, start) if start is not None else 0
|
|
103
|
+
if end is not None:
|
|
104
|
+
anchor = min(anchor, end)
|
|
105
|
+
start = anchor - span if start is None else max(start, anchor - span)
|
|
106
|
+
end = anchor + span if end is None else min(end, anchor + span)
|
|
107
|
+
if start is None or end is None:
|
|
108
|
+
return None
|
|
109
|
+
return NumericGrid(start, end, scale)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _units(bound: tuple[Decimal, bool], scale: int, lower: bool) -> int:
|
|
113
|
+
value, exclusive = bound
|
|
114
|
+
if value and value.adjusted() + scale < 0:
|
|
115
|
+
return int(value > 0) if lower else -int(value < 0)
|
|
116
|
+
precision = max(len(value.as_tuple().digits), value.adjusted() + scale + 1) + 2
|
|
117
|
+
with localcontext(Context(prec=precision)):
|
|
118
|
+
scaled = value.scaleb(scale)
|
|
119
|
+
integral = scaled.to_integral_value(rounding=ROUND_CEILING if lower else ROUND_FLOOR)
|
|
120
|
+
if exclusive and scaled == integral:
|
|
121
|
+
integral += 1 if lower else -1
|
|
122
|
+
return int(integral)
|