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.
Files changed (54) hide show
  1. collate_data_diff-0.11.2.dist-info/LICENSE +18 -0
  2. collate_data_diff-0.11.2.dist-info/METADATA +77 -0
  3. collate_data_diff-0.11.2.dist-info/RECORD +54 -0
  4. collate_data_diff-0.11.2.dist-info/WHEEL +4 -0
  5. collate_data_diff-0.11.2.dist-info/entry_points.txt +3 -0
  6. data_diff/__init__.py +180 -0
  7. data_diff/__main__.py +618 -0
  8. data_diff/abcs/__init__.py +0 -0
  9. data_diff/abcs/compiler.py +13 -0
  10. data_diff/abcs/database_types.py +308 -0
  11. data_diff/cloud/__init__.py +2 -0
  12. data_diff/cloud/data_source.py +318 -0
  13. data_diff/cloud/datafold_api.py +304 -0
  14. data_diff/config.py +127 -0
  15. data_diff/databases/__init__.py +17 -0
  16. data_diff/databases/_connect.py +306 -0
  17. data_diff/databases/base.py +1291 -0
  18. data_diff/databases/bigquery.py +315 -0
  19. data_diff/databases/clickhouse.py +203 -0
  20. data_diff/databases/databricks.py +248 -0
  21. data_diff/databases/duckdb.py +192 -0
  22. data_diff/databases/mssql.py +229 -0
  23. data_diff/databases/mysql.py +159 -0
  24. data_diff/databases/oracle.py +195 -0
  25. data_diff/databases/postgresql.py +258 -0
  26. data_diff/databases/presto.py +197 -0
  27. data_diff/databases/redshift.py +217 -0
  28. data_diff/databases/snowflake.py +207 -0
  29. data_diff/databases/trino.py +50 -0
  30. data_diff/databases/vertica.py +160 -0
  31. data_diff/dbt.py +604 -0
  32. data_diff/dbt_config_validators.py +65 -0
  33. data_diff/dbt_parser.py +523 -0
  34. data_diff/diff_tables.py +416 -0
  35. data_diff/errors.py +74 -0
  36. data_diff/format.py +359 -0
  37. data_diff/hashdiff_tables.py +264 -0
  38. data_diff/info_tree.py +62 -0
  39. data_diff/joindiff_tables.py +399 -0
  40. data_diff/lexicographic_space.py +240 -0
  41. data_diff/parse_time.py +74 -0
  42. data_diff/py.typed +0 -0
  43. data_diff/queries/__init__.py +0 -0
  44. data_diff/queries/api.py +200 -0
  45. data_diff/queries/ast_classes.py +798 -0
  46. data_diff/queries/base.py +24 -0
  47. data_diff/queries/extras.py +29 -0
  48. data_diff/query_utils.py +56 -0
  49. data_diff/schema.py +52 -0
  50. data_diff/table_segment.py +286 -0
  51. data_diff/thread_utils.py +98 -0
  52. data_diff/tracking.py +237 -0
  53. data_diff/utils.py +625 -0
  54. data_diff/version.py +1 -0
@@ -0,0 +1,306 @@
1
+ import logging
2
+ from typing import Hashable, MutableMapping, Type, Optional, Union, Dict
3
+ from itertools import zip_longest
4
+ from contextlib import suppress
5
+ import weakref
6
+
7
+ import attrs
8
+ import dsnparse
9
+ import toml
10
+
11
+ from typing_extensions import Self
12
+
13
+ from data_diff.databases.base import Database, ThreadedDatabase
14
+ from data_diff.databases.postgresql import PostgreSQL
15
+ from data_diff.databases.mysql import MySQL
16
+ from data_diff.databases.oracle import Oracle
17
+ from data_diff.databases.snowflake import Snowflake
18
+ from data_diff.databases.bigquery import BigQuery
19
+ from data_diff.databases.redshift import Redshift
20
+ from data_diff.databases.presto import Presto
21
+ from data_diff.databases.databricks import Databricks
22
+ from data_diff.databases.trino import Trino
23
+ from data_diff.databases.clickhouse import Clickhouse
24
+ from data_diff.databases.vertica import Vertica
25
+ from data_diff.databases.duckdb import DuckDB
26
+ from data_diff.databases.mssql import MsSQL
27
+
28
+
29
+ @attrs.frozen
30
+ class MatchUriPath:
31
+ database_cls: Type[Database]
32
+
33
+ def match_path(self, dsn):
34
+ help_str = self.database_cls.CONNECT_URI_HELP
35
+ params = self.database_cls.CONNECT_URI_PARAMS
36
+ kwparams = self.database_cls.CONNECT_URI_KWPARAMS
37
+
38
+ dsn_dict = dict(dsn.query)
39
+ matches = {}
40
+ for param, arg in zip_longest(params, dsn.paths):
41
+ if param is None:
42
+ raise ValueError(f"Too many parts to path. Expected format: {help_str}")
43
+
44
+ optional = param.endswith("?")
45
+ param = param.rstrip("?")
46
+
47
+ if arg is None:
48
+ try:
49
+ arg = dsn_dict.pop(param)
50
+ except KeyError:
51
+ if not optional:
52
+ raise ValueError(f"URI must specify '{param}'. Expected format: {help_str}")
53
+
54
+ arg = None
55
+
56
+ assert param and param not in matches
57
+ matches[param] = arg
58
+
59
+ for param in kwparams:
60
+ try:
61
+ arg = dsn_dict.pop(param)
62
+ except KeyError:
63
+ raise ValueError(f"URI must specify '{param}'. Expected format: {help_str}")
64
+
65
+ assert param and arg and param not in matches, (param, arg, matches.keys())
66
+ matches[param] = arg
67
+
68
+ for param, value in dsn_dict.items():
69
+ if param in matches:
70
+ raise ValueError(
71
+ f"Parameter '{param}' already provided as positional argument. Expected format: {help_str}"
72
+ )
73
+
74
+ matches[param] = value
75
+
76
+ return matches
77
+
78
+
79
+ DATABASE_BY_SCHEME = {
80
+ "postgresql": PostgreSQL,
81
+ "mysql": MySQL,
82
+ "oracle": Oracle,
83
+ "redshift": Redshift,
84
+ "snowflake": Snowflake,
85
+ "presto": Presto,
86
+ "bigquery": BigQuery,
87
+ "databricks": Databricks,
88
+ "duckdb": DuckDB,
89
+ "trino": Trino,
90
+ "clickhouse": Clickhouse,
91
+ "vertica": Vertica,
92
+ "mssql": MsSQL,
93
+ }
94
+
95
+
96
+ @attrs.define(frozen=False, init=False)
97
+ class Connect:
98
+ """Provides methods for connecting to a supported database using a URL or connection dict."""
99
+
100
+ database_by_scheme: Dict[str, Database]
101
+ conn_cache: MutableMapping[Hashable, Database]
102
+
103
+ def __init__(self, database_by_scheme: Dict[str, Database] = DATABASE_BY_SCHEME) -> None:
104
+ super().__init__()
105
+ self.database_by_scheme = database_by_scheme
106
+ self.conn_cache = weakref.WeakValueDictionary()
107
+
108
+ def for_databases(self, *dbs) -> Self:
109
+ database_by_scheme = {k: db for k, db in self.database_by_scheme.items() if k in dbs}
110
+ return type(self)(database_by_scheme)
111
+
112
+ def connect_to_uri(self, db_uri: str, thread_count: Optional[int] = 1, **kwargs) -> Database:
113
+ """Connect to the given database uri
114
+
115
+ thread_count determines the max number of worker threads per database,
116
+ if relevant. None means no limit.
117
+
118
+ Parameters:
119
+ db_uri (str): The URI for the database to connect
120
+ thread_count (int, optional): Size of the threadpool. Ignored by cloud databases. (default: 1)
121
+
122
+ Note: For non-cloud databases, a low thread-pool size may be a performance bottleneck.
123
+
124
+ Supported schemes:
125
+ - postgresql
126
+ - mysql
127
+ - oracle
128
+ - snowflake
129
+ - bigquery
130
+ - redshift
131
+ - presto
132
+ - databricks
133
+ - trino
134
+ - clickhouse
135
+ - vertica
136
+ - duckdb
137
+ """
138
+
139
+ dsn = dsnparse.parse(db_uri)
140
+ if len(dsn.schemes) > 1:
141
+ raise NotImplementedError("No support for multiple schemes")
142
+ (scheme,) = dsn.schemes
143
+
144
+ if scheme == "toml":
145
+ toml_path = dsn.path or dsn.host
146
+ database = dsn.fragment
147
+ if not database:
148
+ raise ValueError("Must specify a database name, e.g. 'toml://path#database'. ")
149
+ with open(toml_path) as f:
150
+ config = toml.load(f)
151
+ try:
152
+ conn_dict = config["database"][database]
153
+ except KeyError:
154
+ raise ValueError(f"Cannot find database config named '{database}'.")
155
+ return self.connect_with_dict(conn_dict, thread_count, **kwargs)
156
+
157
+ try:
158
+ cls = self.database_by_scheme[scheme]
159
+ except KeyError:
160
+ raise NotImplementedError(f"Scheme '{scheme}' currently not supported")
161
+
162
+ if scheme == "databricks":
163
+ assert not dsn.user
164
+ kw = {}
165
+ kw["access_token"] = dsn.password
166
+ kw["http_path"] = dsn.path
167
+ kw["server_hostname"] = dsn.host
168
+ kw.update(dsn.query)
169
+ elif scheme == "duckdb":
170
+ kw = {}
171
+ kw["filepath"] = dsn.dbname
172
+ kw["dbname"] = dsn.user
173
+ else:
174
+ matcher = MatchUriPath(cls)
175
+ kw = matcher.match_path(dsn)
176
+
177
+ if scheme == "bigquery":
178
+ kw["project"] = dsn.host
179
+ return cls(**kw, **kwargs)
180
+
181
+ if scheme == "snowflake":
182
+ kw["account"] = dsn.host
183
+ assert not dsn.port
184
+ kw["user"] = dsn.user
185
+ kw["password"] = dsn.password
186
+ else:
187
+ if scheme == "oracle":
188
+ kw["host"] = dsn.hostloc
189
+ else:
190
+ kw["host"] = dsn.host
191
+ kw["port"] = dsn.port
192
+ kw["user"] = dsn.user
193
+ if dsn.password:
194
+ kw["password"] = dsn.password
195
+
196
+ kw = {k: v for k, v in kw.items() if v is not None}
197
+
198
+ if isinstance(cls, type) and issubclass(cls, ThreadedDatabase):
199
+ db = cls(thread_count=thread_count, **kw, **kwargs)
200
+ else:
201
+ db = cls(**kw, **kwargs)
202
+
203
+ return self._connection_created(db)
204
+
205
+ def connect_with_dict(self, d, thread_count, **kwargs):
206
+ d = dict(d)
207
+ driver = d.pop("driver")
208
+ try:
209
+ cls = self.database_by_scheme[driver]
210
+ except KeyError:
211
+ raise NotImplementedError(f"Driver '{driver}' currently not supported")
212
+
213
+ if issubclass(cls, ThreadedDatabase):
214
+ db = cls(thread_count=thread_count, **d, **kwargs)
215
+ else:
216
+ db = cls(**d, **kwargs)
217
+
218
+ return self._connection_created(db)
219
+
220
+ def _connection_created(self, db):
221
+ "Nop function to be overridden by subclasses."
222
+ return db
223
+
224
+ def __call__(
225
+ self, db_conf: Union[str, dict], thread_count: Optional[int] = 1, shared: bool = True, **kwargs
226
+ ) -> Database:
227
+ """Connect to a database using the given database configuration.
228
+
229
+ Configuration can be given either as a URI string, or as a dict of {option: value}.
230
+
231
+ The dictionary configuration uses the same keys as the TOML 'database' definition given with --conf.
232
+
233
+ thread_count determines the max number of worker threads per database,
234
+ if relevant. None means no limit.
235
+
236
+ Parameters:
237
+ db_conf (str | dict): The configuration for the database to connect. URI or dict.
238
+ thread_count (int, optional): Size of the threadpool. Ignored by cloud databases. (default: 1)
239
+ shared (bool): Whether to cache and return the same connection for the same db_conf. (default: True)
240
+ bigquery_credentials (google.oauth2.credentials.Credentials): Custom Google oAuth2 credential for BigQuery.
241
+ (default: None)
242
+
243
+ Note: For non-cloud databases, a low thread-pool size may be a performance bottleneck.
244
+
245
+ Supported drivers:
246
+ - postgresql
247
+ - mysql
248
+ - oracle
249
+ - snowflake
250
+ - bigquery
251
+ - redshift
252
+ - presto
253
+ - databricks
254
+ - trino
255
+ - clickhouse
256
+ - vertica
257
+
258
+ Example:
259
+ >>> connect("mysql://localhost/db")
260
+ <data_diff.databases.mysql.MySQL object at ...>
261
+ >>> connect({"driver": "mysql", "host": "localhost", "database": "db"})
262
+ <data_diff.databases.mysql.MySQL object at ...>
263
+ """
264
+ cache_key = self.__make_cache_key(db_conf)
265
+ if shared:
266
+ with suppress(KeyError):
267
+ conn = self.conn_cache[cache_key]
268
+ if not conn.is_closed:
269
+ return conn
270
+
271
+ if isinstance(db_conf, str):
272
+ conn = self.connect_to_uri(db_conf, thread_count, **kwargs)
273
+ elif isinstance(db_conf, dict):
274
+ conn = self.connect_with_dict(db_conf, thread_count, **kwargs)
275
+ else:
276
+ raise TypeError(f"db configuration must be a URI string or a dictionary. Instead got '{db_conf}'.")
277
+
278
+ if shared:
279
+ self.conn_cache[cache_key] = conn
280
+ return conn
281
+
282
+ def __make_cache_key(self, db_conf: Union[str, dict]) -> Hashable:
283
+ if isinstance(db_conf, dict):
284
+ return tuple(db_conf.items())
285
+ return db_conf
286
+
287
+
288
+ @attrs.define(frozen=False, init=False)
289
+ class Connect_SetUTC(Connect):
290
+ """Provides methods for connecting to a supported database using a URL or connection dict.
291
+
292
+ Ensures all sessions use UTC Timezone, if possible.
293
+ """
294
+
295
+ def _connection_created(self, db):
296
+ db = super()._connection_created(db)
297
+ try:
298
+ db.query(db.dialect.set_timezone_to_utc())
299
+ except NotImplementedError:
300
+ logging.debug(
301
+ f"Database '{db}' does not allow setting timezone. We recommend making sure it's set to 'UTC'."
302
+ )
303
+ return db
304
+
305
+
306
+ connect = Connect_SetUTC(DATABASE_BY_SCHEME)