collate-data-diff 0.11.2__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.
- collate_data_diff-0.11.2.dist-info/LICENSE +18 -0
- collate_data_diff-0.11.2.dist-info/METADATA +77 -0
- collate_data_diff-0.11.2.dist-info/RECORD +54 -0
- collate_data_diff-0.11.2.dist-info/WHEEL +4 -0
- collate_data_diff-0.11.2.dist-info/entry_points.txt +3 -0
- data_diff/__init__.py +180 -0
- data_diff/__main__.py +618 -0
- data_diff/abcs/__init__.py +0 -0
- data_diff/abcs/compiler.py +13 -0
- data_diff/abcs/database_types.py +308 -0
- data_diff/cloud/__init__.py +2 -0
- data_diff/cloud/data_source.py +318 -0
- data_diff/cloud/datafold_api.py +304 -0
- data_diff/config.py +127 -0
- data_diff/databases/__init__.py +17 -0
- data_diff/databases/_connect.py +306 -0
- data_diff/databases/base.py +1291 -0
- data_diff/databases/bigquery.py +315 -0
- data_diff/databases/clickhouse.py +203 -0
- data_diff/databases/databricks.py +248 -0
- data_diff/databases/duckdb.py +192 -0
- data_diff/databases/mssql.py +229 -0
- data_diff/databases/mysql.py +159 -0
- data_diff/databases/oracle.py +195 -0
- data_diff/databases/postgresql.py +258 -0
- data_diff/databases/presto.py +197 -0
- data_diff/databases/redshift.py +217 -0
- data_diff/databases/snowflake.py +207 -0
- data_diff/databases/trino.py +50 -0
- data_diff/databases/vertica.py +160 -0
- data_diff/dbt.py +604 -0
- data_diff/dbt_config_validators.py +65 -0
- data_diff/dbt_parser.py +523 -0
- data_diff/diff_tables.py +416 -0
- data_diff/errors.py +74 -0
- data_diff/format.py +359 -0
- data_diff/hashdiff_tables.py +264 -0
- data_diff/info_tree.py +62 -0
- data_diff/joindiff_tables.py +399 -0
- data_diff/lexicographic_space.py +240 -0
- data_diff/parse_time.py +74 -0
- data_diff/py.typed +0 -0
- data_diff/queries/__init__.py +0 -0
- data_diff/queries/api.py +200 -0
- data_diff/queries/ast_classes.py +798 -0
- data_diff/queries/base.py +24 -0
- data_diff/queries/extras.py +29 -0
- data_diff/query_utils.py +56 -0
- data_diff/schema.py +52 -0
- data_diff/table_segment.py +286 -0
- data_diff/thread_utils.py +98 -0
- data_diff/tracking.py +237 -0
- data_diff/utils.py +625 -0
- data_diff/version.py +1 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from typing import Generator
|
|
2
|
+
|
|
3
|
+
import attrs
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@attrs.define(frozen=True)
|
|
7
|
+
class _SKIP:
|
|
8
|
+
def __repr__(self) -> str:
|
|
9
|
+
return "SKIP"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
SKIP = _SKIP()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SqeletonError(Exception):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def args_as_tuple(exprs):
|
|
20
|
+
if len(exprs) == 1:
|
|
21
|
+
(e,) = exprs
|
|
22
|
+
if isinstance(e, Generator):
|
|
23
|
+
return tuple(e)
|
|
24
|
+
return exprs
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"Useful AST classes that don't quite fall within the scope of regular SQL"
|
|
2
|
+
|
|
3
|
+
from typing import Callable, Optional, Sequence
|
|
4
|
+
|
|
5
|
+
import attrs
|
|
6
|
+
|
|
7
|
+
from data_diff.abcs.database_types import ColType
|
|
8
|
+
from data_diff.queries.ast_classes import Expr, ExprNode
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@attrs.define(frozen=True)
|
|
12
|
+
class NormalizeAsString(ExprNode):
|
|
13
|
+
expr: ExprNode
|
|
14
|
+
expr_type: Optional[ColType] = None
|
|
15
|
+
|
|
16
|
+
@property
|
|
17
|
+
def type(self) -> Optional[type]:
|
|
18
|
+
return str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@attrs.define(frozen=True)
|
|
22
|
+
class ApplyFuncAndNormalizeAsString(ExprNode):
|
|
23
|
+
expr: ExprNode
|
|
24
|
+
apply_func: Optional[Callable] = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@attrs.define(frozen=True)
|
|
28
|
+
class Checksum(ExprNode):
|
|
29
|
+
exprs: Sequence[Expr]
|
data_diff/query_utils.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"Module for query utilities that didn't make it into the query-builder (yet)"
|
|
2
|
+
|
|
3
|
+
from contextlib import suppress
|
|
4
|
+
|
|
5
|
+
from data_diff.abcs.database_types import DbPath
|
|
6
|
+
from data_diff.databases.base import QueryError
|
|
7
|
+
from data_diff.databases.oracle import Oracle
|
|
8
|
+
from data_diff.queries.api import table, commit, Expr
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _drop_table_oracle(name: DbPath):
|
|
12
|
+
t = table(name)
|
|
13
|
+
# Experience shows double drop is necessary
|
|
14
|
+
with suppress(QueryError):
|
|
15
|
+
yield t.drop()
|
|
16
|
+
yield t.drop()
|
|
17
|
+
yield commit
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _drop_table(name: DbPath):
|
|
21
|
+
t = table(name)
|
|
22
|
+
yield t.drop(if_exists=True)
|
|
23
|
+
yield commit
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def drop_table(db, tbl) -> None:
|
|
27
|
+
if isinstance(db, Oracle):
|
|
28
|
+
db.query(_drop_table_oracle(tbl))
|
|
29
|
+
else:
|
|
30
|
+
db.query(_drop_table(tbl))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _append_to_table_oracle(path: DbPath, expr: Expr):
|
|
34
|
+
"""See append_to_table"""
|
|
35
|
+
assert expr.schema, expr
|
|
36
|
+
t = table(path, schema=expr.schema)
|
|
37
|
+
with suppress(QueryError):
|
|
38
|
+
yield t.create() # uses expr.schema
|
|
39
|
+
yield commit
|
|
40
|
+
yield t.insert_expr(expr)
|
|
41
|
+
yield commit
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _append_to_table(path: DbPath, expr: Expr):
|
|
45
|
+
"""Append to table"""
|
|
46
|
+
assert expr.schema, expr
|
|
47
|
+
t = table(path, schema=expr.schema)
|
|
48
|
+
yield t.create(if_not_exists=True) # uses expr.schema
|
|
49
|
+
yield commit
|
|
50
|
+
yield t.insert_expr(expr)
|
|
51
|
+
yield commit
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def append_to_table(db, path, expr) -> None:
|
|
55
|
+
f = _append_to_table_oracle if isinstance(db, Oracle) else _append_to_table
|
|
56
|
+
db.query(f(path, expr))
|
data_diff/schema.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any, Collection, Iterator, Optional
|
|
3
|
+
|
|
4
|
+
import attrs
|
|
5
|
+
|
|
6
|
+
from data_diff.utils import CaseAwareMapping, CaseInsensitiveDict, CaseSensitiveDict
|
|
7
|
+
from data_diff.abcs.database_types import DbPath
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger("schema")
|
|
10
|
+
|
|
11
|
+
Schema = CaseAwareMapping
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@attrs.frozen(kw_only=True)
|
|
15
|
+
class RawColumnInfo(Collection[Any]):
|
|
16
|
+
"""
|
|
17
|
+
A raw row representing the schema info about a column.
|
|
18
|
+
|
|
19
|
+
Do not rely on this class too much, it will be removed soon when the schema
|
|
20
|
+
selecting & parsing methods are united into one overrideable method.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
column_name: str
|
|
24
|
+
data_type: str
|
|
25
|
+
datetime_precision: Optional[int] = None
|
|
26
|
+
numeric_precision: Optional[int] = None
|
|
27
|
+
numeric_scale: Optional[int] = None
|
|
28
|
+
collation_name: Optional[str] = None
|
|
29
|
+
|
|
30
|
+
# It was a tuple once, so we keep it backward compatible temporarily, until remade to classes.
|
|
31
|
+
def __iter__(self) -> Iterator[Any]:
|
|
32
|
+
return iter(
|
|
33
|
+
(self.column_name, self.data_type, self.datetime_precision, self.numeric_precision, self.numeric_scale)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def __len__(self) -> int:
|
|
37
|
+
return 5
|
|
38
|
+
|
|
39
|
+
def __contains__(self, item: Any) -> bool:
|
|
40
|
+
return False # that was not used
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def create_schema(db_name: str, table_path: DbPath, schema: dict, case_sensitive: bool) -> CaseAwareMapping:
|
|
44
|
+
logger.info(f"[{db_name}] Schema = {schema}")
|
|
45
|
+
|
|
46
|
+
if case_sensitive:
|
|
47
|
+
return CaseSensitiveDict(schema)
|
|
48
|
+
|
|
49
|
+
if len({k.lower() for k in schema}) < len(schema):
|
|
50
|
+
logger.warning(f'Ambiguous schema for {db_name}:{".".join(table_path)} | Columns = {", ".join(list(schema))}')
|
|
51
|
+
logger.warning("We recommend to disable case-insensitivity (set --case-sensitive).")
|
|
52
|
+
return CaseInsensitiveDict(schema)
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Container, Dict, List, Optional, Sequence, Tuple
|
|
3
|
+
import logging
|
|
4
|
+
from itertools import product
|
|
5
|
+
|
|
6
|
+
import attrs
|
|
7
|
+
from typing_extensions import Self
|
|
8
|
+
|
|
9
|
+
from data_diff.utils import safezip, Vector
|
|
10
|
+
from data_diff.utils import ArithString, split_space
|
|
11
|
+
from data_diff.databases.base import Database
|
|
12
|
+
from data_diff.abcs.database_types import DbPath, DbKey, DbTime, IKey
|
|
13
|
+
from data_diff.schema import RawColumnInfo, Schema, create_schema
|
|
14
|
+
from data_diff.queries.extras import Checksum
|
|
15
|
+
from data_diff.queries.api import Count, SKIP, table, this, Expr, min_, max_, Code
|
|
16
|
+
from data_diff.queries.extras import ApplyFuncAndNormalizeAsString, NormalizeAsString
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger("table_segment")
|
|
19
|
+
|
|
20
|
+
RECOMMENDED_CHECKSUM_DURATION = 20
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def split_key_space(min_key: DbKey, max_key: DbKey, count: int) -> List[DbKey]:
|
|
24
|
+
assert min_key < max_key
|
|
25
|
+
|
|
26
|
+
if max_key - min_key <= count:
|
|
27
|
+
count = 1
|
|
28
|
+
|
|
29
|
+
if isinstance(min_key, ArithString):
|
|
30
|
+
assert type(min_key) is type(max_key)
|
|
31
|
+
checkpoints = min_key.range(max_key, count)
|
|
32
|
+
else:
|
|
33
|
+
checkpoints = split_space(min_key, max_key, count)
|
|
34
|
+
|
|
35
|
+
assert all(min_key < x < max_key for x in checkpoints)
|
|
36
|
+
return [min_key] + checkpoints + [max_key]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def int_product(nums: List[int]) -> int:
|
|
40
|
+
p = 1
|
|
41
|
+
for n in nums:
|
|
42
|
+
p *= n
|
|
43
|
+
return p
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def split_compound_key_space(mn: Vector, mx: Vector, count: int) -> List[List[DbKey]]:
|
|
47
|
+
"""Returns a list of split-points for each key dimension, essentially returning an N-dimensional grid of split points."""
|
|
48
|
+
return [split_key_space(mn_k, mx_k, count) for mn_k, mx_k in safezip(mn, mx)]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def create_mesh_from_points(*values_per_dim: list) -> List[Tuple[Vector, Vector]]:
|
|
52
|
+
"""Given a list of values along each axis of N dimensional space,
|
|
53
|
+
return an array of boxes whose start-points & end-points align with the given values,
|
|
54
|
+
and together consitute a mesh filling that space entirely (within the bounds of the given values).
|
|
55
|
+
|
|
56
|
+
Assumes given values are already ordered ascending.
|
|
57
|
+
|
|
58
|
+
len(boxes) == ∏i( len(i)-1 )
|
|
59
|
+
|
|
60
|
+
Example:
|
|
61
|
+
::
|
|
62
|
+
>>> d1 = 'a', 'b', 'c'
|
|
63
|
+
>>> d2 = 1, 2, 3
|
|
64
|
+
>>> d3 = 'X', 'Y'
|
|
65
|
+
>>> create_mesh_from_points(d1, d2, d3)
|
|
66
|
+
[
|
|
67
|
+
[('a', 1, 'X'), ('b', 2, 'Y')],
|
|
68
|
+
[('a', 2, 'X'), ('b', 3, 'Y')],
|
|
69
|
+
[('b', 1, 'X'), ('c', 2, 'Y')],
|
|
70
|
+
[('b', 2, 'X'), ('c', 3, 'Y')]
|
|
71
|
+
]
|
|
72
|
+
"""
|
|
73
|
+
assert all(len(v) >= 2 for v in values_per_dim), values_per_dim
|
|
74
|
+
|
|
75
|
+
# Create tuples of (v1, v2) for each pair of adjacent values
|
|
76
|
+
ranges = [list(zip(values[:-1], values[1:])) for values in values_per_dim]
|
|
77
|
+
|
|
78
|
+
assert all(a <= b for r in ranges for a, b in r)
|
|
79
|
+
|
|
80
|
+
# Create a product of all the ranges
|
|
81
|
+
res = [tuple(Vector(a) for a in safezip(*r)) for r in product(*ranges)]
|
|
82
|
+
|
|
83
|
+
expected_len = int_product(len(v) - 1 for v in values_per_dim)
|
|
84
|
+
assert len(res) == expected_len, (len(res), expected_len)
|
|
85
|
+
return res
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@attrs.define(frozen=True)
|
|
89
|
+
class TableSegment:
|
|
90
|
+
"""Signifies a segment of rows (and selected columns) within a table
|
|
91
|
+
|
|
92
|
+
Parameters:
|
|
93
|
+
database (Database): Database instance. See :meth:`connect`
|
|
94
|
+
table_path (:data:`DbPath`): Path to table in form of a tuple. e.g. `('my_dataset', 'table_name')`
|
|
95
|
+
key_columns (Tuple[str]): Name of the key column, which uniquely identifies each row (usually id)
|
|
96
|
+
update_column (str, optional): Name of updated column, which signals that rows changed.
|
|
97
|
+
Usually updated_at or last_update. Used by `min_update` and `max_update`.
|
|
98
|
+
extra_columns (Tuple[str, ...], optional): Extra columns to compare
|
|
99
|
+
min_key (:data:`Vector`, optional): Lowest key value, used to restrict the segment
|
|
100
|
+
max_key (:data:`Vector`, optional): Highest key value, used to restrict the segment
|
|
101
|
+
min_update (:data:`DbTime`, optional): Lowest update_column value, used to restrict the segment
|
|
102
|
+
max_update (:data:`DbTime`, optional): Highest update_column value, used to restrict the segment
|
|
103
|
+
where (str, optional): An additional 'where' expression to restrict the search space.
|
|
104
|
+
|
|
105
|
+
case_sensitive (bool): If false, the case of column names will adjust according to the schema. Default is true.
|
|
106
|
+
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
# Location of table
|
|
110
|
+
database: Database
|
|
111
|
+
table_path: DbPath
|
|
112
|
+
|
|
113
|
+
# Columns
|
|
114
|
+
key_columns: Tuple[str, ...]
|
|
115
|
+
update_column: Optional[str] = None
|
|
116
|
+
extra_columns: Tuple[str, ...] = ()
|
|
117
|
+
ignored_columns: Container[str] = frozenset()
|
|
118
|
+
|
|
119
|
+
# Restrict the segment
|
|
120
|
+
min_key: Optional[Vector] = None
|
|
121
|
+
max_key: Optional[Vector] = None
|
|
122
|
+
min_update: Optional[DbTime] = None
|
|
123
|
+
max_update: Optional[DbTime] = None
|
|
124
|
+
where: Optional[str] = None
|
|
125
|
+
|
|
126
|
+
case_sensitive: Optional[bool] = True
|
|
127
|
+
_schema: Optional[Schema] = None
|
|
128
|
+
|
|
129
|
+
def __attrs_post_init__(self) -> None:
|
|
130
|
+
if not self.update_column and (self.min_update or self.max_update):
|
|
131
|
+
raise ValueError("Error: the min_update/max_update feature requires 'update_column' to be set.")
|
|
132
|
+
|
|
133
|
+
if self.min_key is not None and self.max_key is not None and self.min_key >= self.max_key:
|
|
134
|
+
raise ValueError(f"Error: min_key expected to be smaller than max_key! ({self.min_key} >= {self.max_key})")
|
|
135
|
+
|
|
136
|
+
if self.min_update is not None and self.max_update is not None and self.min_update >= self.max_update:
|
|
137
|
+
raise ValueError(
|
|
138
|
+
f"Error: min_update expected to be smaller than max_update! ({self.min_update} >= {self.max_update})"
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
def _where(self) -> Optional[str]:
|
|
142
|
+
return f"({self.where})" if self.where else None
|
|
143
|
+
|
|
144
|
+
def _with_raw_schema(self, raw_schema: Dict[str, RawColumnInfo]) -> Self:
|
|
145
|
+
schema = self.database._process_table_schema(self.table_path, raw_schema, self.relevant_columns, self._where())
|
|
146
|
+
return self.new(schema=create_schema(self.database.name, self.table_path, schema, self.case_sensitive))
|
|
147
|
+
|
|
148
|
+
def with_schema(self) -> Self:
|
|
149
|
+
"Queries the table schema from the database, and returns a new instance of TableSegment, with a schema."
|
|
150
|
+
if self._schema:
|
|
151
|
+
return self
|
|
152
|
+
|
|
153
|
+
return self._with_raw_schema(self.database.query_table_schema(self.table_path))
|
|
154
|
+
|
|
155
|
+
def get_schema(self) -> Dict[str, RawColumnInfo]:
|
|
156
|
+
return self.database.query_table_schema(self.table_path)
|
|
157
|
+
|
|
158
|
+
def _make_key_range(self):
|
|
159
|
+
if self.min_key is not None:
|
|
160
|
+
for mn, k in safezip(self.min_key, self.key_columns):
|
|
161
|
+
yield mn <= this[k]
|
|
162
|
+
if self.max_key is not None:
|
|
163
|
+
for k, mx in safezip(self.key_columns, self.max_key):
|
|
164
|
+
yield this[k] < mx
|
|
165
|
+
|
|
166
|
+
def _make_update_range(self):
|
|
167
|
+
if self.min_update is not None:
|
|
168
|
+
yield self.min_update <= this[self.update_column]
|
|
169
|
+
if self.max_update is not None:
|
|
170
|
+
yield this[self.update_column] < self.max_update
|
|
171
|
+
|
|
172
|
+
@property
|
|
173
|
+
def source_table(self):
|
|
174
|
+
return table(*self.table_path, schema=self._schema)
|
|
175
|
+
|
|
176
|
+
def make_select(self):
|
|
177
|
+
return self.source_table.where(
|
|
178
|
+
*self._make_key_range(), *self._make_update_range(), Code(self._where()) if self.where else SKIP
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def get_values(self) -> list:
|
|
182
|
+
"Download all the relevant values of the segment from the database"
|
|
183
|
+
|
|
184
|
+
# Fetch all the original columns, even if some were later excluded from checking.
|
|
185
|
+
fetched_cols = [NormalizeAsString(this[c]) for c in self.relevant_columns]
|
|
186
|
+
select = self.make_select().select(*fetched_cols)
|
|
187
|
+
return self.database.query(select, List[Tuple])
|
|
188
|
+
|
|
189
|
+
def choose_checkpoints(self, count: int) -> List[List[DbKey]]:
|
|
190
|
+
"Suggests a bunch of evenly-spaced checkpoints to split by, including start, end."
|
|
191
|
+
|
|
192
|
+
assert self.is_bounded
|
|
193
|
+
|
|
194
|
+
# Take Nth root of count, to approximate the appropriate box size
|
|
195
|
+
count = int(count ** (1 / len(self.key_columns))) or 1
|
|
196
|
+
|
|
197
|
+
return split_compound_key_space(self.min_key, self.max_key, count)
|
|
198
|
+
|
|
199
|
+
def segment_by_checkpoints(self, checkpoints: List[List[DbKey]]) -> List["TableSegment"]:
|
|
200
|
+
"Split the current TableSegment to a bunch of smaller ones, separated by the given checkpoints"
|
|
201
|
+
|
|
202
|
+
return [self.new_key_bounds(min_key=s, max_key=e) for s, e in create_mesh_from_points(*checkpoints)]
|
|
203
|
+
|
|
204
|
+
def new(self, **kwargs) -> Self:
|
|
205
|
+
"""Creates a copy of the instance using 'replace()'"""
|
|
206
|
+
return attrs.evolve(self, **kwargs)
|
|
207
|
+
|
|
208
|
+
def new_key_bounds(self, min_key: Vector, max_key: Vector, *, key_types: Optional[Sequence[IKey]] = None) -> Self:
|
|
209
|
+
if self.min_key is not None:
|
|
210
|
+
assert self.min_key <= min_key, (self.min_key, min_key)
|
|
211
|
+
assert self.min_key < max_key
|
|
212
|
+
|
|
213
|
+
if self.max_key is not None:
|
|
214
|
+
assert min_key < self.max_key
|
|
215
|
+
assert max_key <= self.max_key
|
|
216
|
+
|
|
217
|
+
# If asked, enforce the PKs to proper types, mainly to meta-params of the relevant side,
|
|
218
|
+
# so that we do not leak e.g. casing of UUIDs from side A to side B and vice versa.
|
|
219
|
+
# If not asked, keep the meta-params of the keys as is (assume them already casted).
|
|
220
|
+
if key_types is not None:
|
|
221
|
+
min_key = Vector(type.make_value(val) for type, val in safezip(key_types, min_key))
|
|
222
|
+
max_key = Vector(type.make_value(val) for type, val in safezip(key_types, max_key))
|
|
223
|
+
|
|
224
|
+
return attrs.evolve(self, min_key=min_key, max_key=max_key)
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def relevant_columns(self) -> List[str]:
|
|
228
|
+
extras = list(self.extra_columns)
|
|
229
|
+
|
|
230
|
+
if self.update_column and self.update_column not in extras:
|
|
231
|
+
extras = [self.update_column] + extras
|
|
232
|
+
|
|
233
|
+
return list(self.key_columns) + extras
|
|
234
|
+
|
|
235
|
+
def count(self) -> int:
|
|
236
|
+
"""Count how many rows are in the segment, in one pass."""
|
|
237
|
+
return self.database.query(self.make_select().select(Count()), int)
|
|
238
|
+
|
|
239
|
+
def count_and_checksum(self) -> Tuple[int, int]:
|
|
240
|
+
"""Count and checksum the rows in the segment, in one pass."""
|
|
241
|
+
|
|
242
|
+
checked_columns = [c for c in self.relevant_columns if c not in self.ignored_columns]
|
|
243
|
+
cols = [NormalizeAsString(this[c]) for c in checked_columns]
|
|
244
|
+
|
|
245
|
+
start = time.monotonic()
|
|
246
|
+
q = self.make_select().select(Count(), Checksum(cols))
|
|
247
|
+
count, checksum = self.database.query(q, tuple)
|
|
248
|
+
duration = time.monotonic() - start
|
|
249
|
+
if duration > RECOMMENDED_CHECKSUM_DURATION:
|
|
250
|
+
logger.warning(
|
|
251
|
+
"Checksum is taking longer than expected (%.2f). "
|
|
252
|
+
"We recommend increasing --bisection-factor or decreasing --threads.",
|
|
253
|
+
duration,
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
if count:
|
|
257
|
+
assert checksum, (count, checksum)
|
|
258
|
+
return count or 0, int(checksum) if count else None
|
|
259
|
+
|
|
260
|
+
def query_key_range(self) -> Tuple[tuple, tuple]:
|
|
261
|
+
"""Query database for minimum and maximum key. This is used for setting the initial bounds."""
|
|
262
|
+
# Normalizes the result (needed for UUIDs) after the min/max computation
|
|
263
|
+
select = self.make_select().select(
|
|
264
|
+
ApplyFuncAndNormalizeAsString(this[k], f) for k in self.key_columns for f in (min_, max_)
|
|
265
|
+
)
|
|
266
|
+
result = tuple(self.database.query(select, tuple))
|
|
267
|
+
|
|
268
|
+
if any(i is None for i in result):
|
|
269
|
+
raise ValueError("Table appears to be empty")
|
|
270
|
+
|
|
271
|
+
# Min/max keys are interleaved
|
|
272
|
+
min_key, max_key = result[::2], result[1::2]
|
|
273
|
+
assert len(min_key) == len(max_key)
|
|
274
|
+
|
|
275
|
+
return min_key, max_key
|
|
276
|
+
|
|
277
|
+
@property
|
|
278
|
+
def is_bounded(self):
|
|
279
|
+
return self.min_key is not None and self.max_key is not None
|
|
280
|
+
|
|
281
|
+
def approximate_size(self):
|
|
282
|
+
if not self.is_bounded:
|
|
283
|
+
raise RuntimeError("Cannot approximate the size of an unbounded segment. Must have min_key and max_key.")
|
|
284
|
+
diff = self.max_key - self.min_key
|
|
285
|
+
assert all(d > 0 for d in diff)
|
|
286
|
+
return int_product(diff)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
from queue import PriorityQueue
|
|
3
|
+
from collections import deque
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
6
|
+
from concurrent.futures.thread import _WorkItem
|
|
7
|
+
from time import sleep
|
|
8
|
+
from typing import Any, Callable, Iterator, Optional
|
|
9
|
+
|
|
10
|
+
import attrs
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AutoPriorityQueue(PriorityQueue):
|
|
14
|
+
"""Overrides PriorityQueue to automatically get the priority from _WorkItem.kwargs
|
|
15
|
+
|
|
16
|
+
We also assign a unique id for each item, to avoid making comparisons on _WorkItem.
|
|
17
|
+
As a side effect, items with the same priority are returned FIFO.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
_counter = itertools.count().__next__
|
|
21
|
+
|
|
22
|
+
def put(self, item: Optional[_WorkItem], block=True, timeout=None) -> None:
|
|
23
|
+
priority = item.kwargs.pop("priority") if item is not None else 0
|
|
24
|
+
super().put((-priority, self._counter(), item), block, timeout)
|
|
25
|
+
|
|
26
|
+
def get(self, block=True, timeout=None) -> Optional[_WorkItem]:
|
|
27
|
+
_p, _c, work_item = super().get(block, timeout)
|
|
28
|
+
return work_item
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PriorityThreadPoolExecutor(ThreadPoolExecutor):
|
|
32
|
+
"""Overrides ThreadPoolExecutor to use AutoPriorityQueue
|
|
33
|
+
|
|
34
|
+
XXX WARNING: Might break in future versions of Python
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, *args) -> None:
|
|
38
|
+
super().__init__(*args)
|
|
39
|
+
self._work_queue = AutoPriorityQueue()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@attrs.define(frozen=False, init=False)
|
|
43
|
+
class ThreadedYielder(Iterable):
|
|
44
|
+
"""Yields results from multiple threads into a single iterator, ordered by priority.
|
|
45
|
+
|
|
46
|
+
To add a source iterator, call ``submit()`` with a function that returns an iterator.
|
|
47
|
+
Priority for the iterator can be provided via the keyword argument 'priority'. (higher runs first)
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
_pool: ThreadPoolExecutor
|
|
51
|
+
_futures: deque
|
|
52
|
+
_yield: deque
|
|
53
|
+
_exception: Optional[None]
|
|
54
|
+
|
|
55
|
+
_pool: ThreadPoolExecutor
|
|
56
|
+
_futures: deque
|
|
57
|
+
_yield: deque = attrs.field(alias="_yield") # Python keyword!
|
|
58
|
+
_exception: Optional[None]
|
|
59
|
+
yield_list: bool
|
|
60
|
+
|
|
61
|
+
def __init__(self, max_workers: Optional[int] = None, yield_list: bool = False) -> None:
|
|
62
|
+
super().__init__()
|
|
63
|
+
self._pool = PriorityThreadPoolExecutor(max_workers)
|
|
64
|
+
self._futures = deque()
|
|
65
|
+
self._yield = deque()
|
|
66
|
+
self._exception = None
|
|
67
|
+
self.yield_list = yield_list
|
|
68
|
+
|
|
69
|
+
def _worker(self, fn, *args, **kwargs) -> None:
|
|
70
|
+
try:
|
|
71
|
+
res = fn(*args, **kwargs)
|
|
72
|
+
if res is not None:
|
|
73
|
+
if self.yield_list:
|
|
74
|
+
self._yield.append(res)
|
|
75
|
+
else:
|
|
76
|
+
self._yield += res
|
|
77
|
+
except Exception as e:
|
|
78
|
+
self._exception = e
|
|
79
|
+
|
|
80
|
+
def submit(self, fn: Callable, *args, priority: int = 0, **kwargs) -> None:
|
|
81
|
+
self._futures.append(self._pool.submit(self._worker, fn, *args, priority=priority, **kwargs))
|
|
82
|
+
|
|
83
|
+
def __iter__(self) -> Iterator[Any]:
|
|
84
|
+
while True:
|
|
85
|
+
if self._exception:
|
|
86
|
+
raise self._exception
|
|
87
|
+
|
|
88
|
+
while self._yield:
|
|
89
|
+
yield self._yield.popleft()
|
|
90
|
+
|
|
91
|
+
if not self._futures:
|
|
92
|
+
# No more tasks
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
if self._futures[0].done():
|
|
96
|
+
self._futures.popleft()
|
|
97
|
+
else:
|
|
98
|
+
sleep(0.001)
|