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
data_diff/__main__.py ADDED
@@ -0,0 +1,618 @@
1
+ import json
2
+ import logging
3
+ import os
4
+ import sys
5
+ import time
6
+ from copy import deepcopy
7
+ from datetime import datetime
8
+ from itertools import islice
9
+ from typing import Dict, Optional, Tuple, Union, List, Set
10
+
11
+ import click
12
+ import rich
13
+ from rich.logging import RichHandler
14
+
15
+ from data_diff import Database, DbPath
16
+ from data_diff.config import apply_config_from_file
17
+ from data_diff.databases._connect import connect
18
+ from data_diff.dbt import dbt_diff
19
+ from data_diff.diff_tables import Algorithm, TableDiffer
20
+ from data_diff.hashdiff_tables import HashDiffer, DEFAULT_BISECTION_THRESHOLD, DEFAULT_BISECTION_FACTOR
21
+ from data_diff.joindiff_tables import TABLE_WRITE_LIMIT, JoinDiffer
22
+ from data_diff.parse_time import parse_time_before, UNITS_STR, ParseError
23
+ from data_diff.queries.api import current_timestamp
24
+ from data_diff.schema import RawColumnInfo, create_schema
25
+ from data_diff.table_segment import TableSegment
26
+ from data_diff.tracking import disable_tracking, set_entrypoint_name
27
+ from data_diff.utils import eval_name_template, remove_password_from_url, safezip, match_like, LogStatusHandler
28
+ from data_diff.version import __version__
29
+
30
+ COLOR_SCHEME = {
31
+ "+": "green",
32
+ "-": "red",
33
+ }
34
+
35
+ set_entrypoint_name(os.getenv("DATAFOLD_TRIGGERED_BY", "CLI"))
36
+
37
+
38
+ def _get_log_handlers(is_dbt: Optional[bool] = False) -> Dict[str, logging.Handler]:
39
+ handlers = {}
40
+ date_format = "%H:%M:%S"
41
+ log_format_rich = "%(message)s"
42
+
43
+ # limits to 100 characters arbitrarily
44
+ log_format_status = "%(message).100s"
45
+ rich_handler = RichHandler(rich_tracebacks=True)
46
+ rich_handler.setFormatter(logging.Formatter(log_format_rich, datefmt=date_format))
47
+ rich_handler.setLevel(logging.WARN)
48
+ handlers["rich_handler"] = rich_handler
49
+
50
+ # only use log_status_handler in an interactive terminal session
51
+ if rich_handler.console.is_interactive and is_dbt:
52
+ log_status_handler = LogStatusHandler()
53
+ log_status_handler.setFormatter(logging.Formatter(log_format_status, datefmt=date_format))
54
+ log_status_handler.setLevel(logging.DEBUG)
55
+ handlers["log_status_handler"] = log_status_handler
56
+
57
+ return handlers
58
+
59
+
60
+ def _remove_passwords_in_dict(d: dict) -> None:
61
+ for k, v in d.items():
62
+ if k == "password":
63
+ d[k] = "*" * len(v)
64
+ elif k == "filepath":
65
+ if "motherduck_token=" in v:
66
+ d[k] = v.split("motherduck_token=")[0] + "motherduck_token=**********"
67
+ elif isinstance(v, dict):
68
+ _remove_passwords_in_dict(v)
69
+ elif k.startswith("database"):
70
+ d[k] = remove_password_from_url(v)
71
+
72
+
73
+ def _get_schema(pair: Tuple[Database, DbPath]) -> Dict[str, RawColumnInfo]:
74
+ db, table_path = pair
75
+ return db.query_table_schema(table_path)
76
+
77
+
78
+ def diff_schemas(table1, table2, schema1, schema2, columns) -> None:
79
+ logging.info("Diffing schemas...")
80
+ attrs = "name", "type", "datetime_precision", "numeric_precision", "numeric_scale"
81
+ for c in columns:
82
+ if c is None: # Skip for convenience
83
+ continue
84
+ diffs = []
85
+
86
+ if c not in schema1:
87
+ cols = ", ".join(schema1)
88
+ raise ValueError(f"Column '{c}' not found in table 1, named '{table1}'. Columns: {cols}")
89
+ if c not in schema2:
90
+ cols = ", ".join(schema1)
91
+ raise ValueError(f"Column '{c}' not found in table 2, named '{table2}'. Columns: {cols}")
92
+
93
+ col1 = schema1[c]
94
+ col2 = schema2[c]
95
+
96
+ for attr, v1, v2 in safezip(attrs, col1, col2):
97
+ if v1 != v2:
98
+ diffs.append(f"{attr}:({v1} != {v2})")
99
+ if diffs:
100
+ logging.warning(f"Schema mismatch in column '{c}': {', '.join(diffs)}")
101
+
102
+
103
+ class MyHelpFormatter(click.HelpFormatter):
104
+ def __init__(self, **kwargs) -> None:
105
+ super().__init__(self, **kwargs)
106
+ self.indent_increment = 6
107
+
108
+ def write_usage(self, prog: str, args: str = "", prefix: Optional[str] = None) -> None:
109
+ self.write(f"data-diff v{__version__} - efficiently diff rows across database tables.\n\n")
110
+ self.write("Usage:\n")
111
+ self.write(f" * In-db diff: {prog} <database_a> <table_a> <table_b> [OPTIONS]\n")
112
+ self.write(f" * Cross-db diff: {prog} <database_a> <table_a> <database_b> <table_b> [OPTIONS]\n")
113
+ self.write(f" * Using config: {prog} --conf PATH [--run NAME] [OPTIONS]\n")
114
+
115
+
116
+ click.Context.formatter_class = MyHelpFormatter
117
+
118
+
119
+ @click.command(no_args_is_help=True)
120
+ @click.argument("database1", required=False)
121
+ @click.argument("table1", required=False)
122
+ @click.argument("database2", required=False)
123
+ @click.argument("table2", required=False)
124
+ @click.option(
125
+ "-k", "--key-columns", default=[], multiple=True, help="Names of primary key columns. Default='id'.", metavar="NAME"
126
+ )
127
+ @click.option("-t", "--update-column", default=None, help="Name of updated_at/last_updated column", metavar="NAME")
128
+ @click.option(
129
+ "-c",
130
+ "--columns",
131
+ default=[],
132
+ multiple=True,
133
+ help="Names of extra columns to compare."
134
+ "Can be used more than once in the same command. "
135
+ "Accepts a name or a pattern like in SQL. Example: -c col% -c another_col",
136
+ metavar="NAME",
137
+ )
138
+ @click.option("-l", "--limit", default=None, help="Maximum number of differences to find", metavar="NUM")
139
+ @click.option(
140
+ "--bisection-factor",
141
+ default=None,
142
+ help=f"Segments per iteration. Default={DEFAULT_BISECTION_FACTOR}.",
143
+ metavar="NUM",
144
+ )
145
+ @click.option(
146
+ "--bisection-threshold",
147
+ default=None,
148
+ help=f"Minimal bisection threshold. Below it, data-diff will download the data and compare it locally. Default={DEFAULT_BISECTION_THRESHOLD}.",
149
+ metavar="NUM",
150
+ )
151
+ @click.option(
152
+ "-m",
153
+ "--materialize-to-table",
154
+ default=None,
155
+ metavar="TABLE_NAME",
156
+ help="(joindiff only) Materialize the diff results into a new table in the database. If a table exists by that name, it will be replaced.",
157
+ )
158
+ @click.option(
159
+ "--min-age",
160
+ default=None,
161
+ help="Considers only rows older than specified. Useful for specifying replication lag."
162
+ "Example: --min-age=5min ignores rows from the last 5 minutes. "
163
+ f"\nValid units: {UNITS_STR}",
164
+ metavar="AGE",
165
+ )
166
+ @click.option(
167
+ "--max-age", default=None, help="Considers only rows younger than specified. See --min-age.", metavar="AGE"
168
+ )
169
+ @click.option("-s", "--stats", is_flag=True, help="Print stats instead of a detailed diff")
170
+ @click.option("-d", "--debug", is_flag=True, help="Print debug info")
171
+ @click.option("--json", "json_output", is_flag=True, help="Print JSONL output for machine readability")
172
+ @click.option("-v", "--verbose", is_flag=True, help="Print extra info")
173
+ @click.option("--version", is_flag=True, help="Print version info and exit")
174
+ @click.option("-i", "--interactive", is_flag=True, help="Confirm queries, implies --debug")
175
+ @click.option("--no-tracking", is_flag=True, help="data-diff sends home anonymous usage data. Use this to disable it.")
176
+ @click.option(
177
+ "--case-sensitive",
178
+ is_flag=True,
179
+ help="Column names are treated as case-sensitive. Otherwise, data-diff corrects their case according to schema.",
180
+ )
181
+ @click.option(
182
+ "--assume-unique-key",
183
+ is_flag=True,
184
+ help="Skip validating the uniqueness of the key column during joindiff, which is costly in non-cloud dbs.",
185
+ )
186
+ @click.option(
187
+ "--sample-exclusive-rows",
188
+ is_flag=True,
189
+ help="Sample several rows that only appear in one of the tables, but not the other. (joindiff only)",
190
+ )
191
+ @click.option(
192
+ "--materialize-all-rows",
193
+ is_flag=True,
194
+ help="Materialize every row, even if they are the same, instead of just the differing rows. (joindiff only)",
195
+ )
196
+ @click.option(
197
+ "--table-write-limit",
198
+ default=TABLE_WRITE_LIMIT,
199
+ help=f"Maximum number of rows to write when creating materialized or sample tables, per thread. Default={TABLE_WRITE_LIMIT}",
200
+ metavar="COUNT",
201
+ )
202
+ @click.option(
203
+ "-j",
204
+ "--threads",
205
+ default=None,
206
+ help="Number of worker threads to use per database. Default=1. "
207
+ "A higher number will increase performance, but take more capacity from your database. "
208
+ "'serial' guarantees a single-threaded execution of the algorithm (useful for debugging).",
209
+ metavar="COUNT",
210
+ )
211
+ @click.option(
212
+ "-w",
213
+ "--where",
214
+ default=None,
215
+ help="An additional 'where' expression to restrict the search space. Beware of SQL Injection!",
216
+ metavar="EXPR",
217
+ )
218
+ @click.option("-a", "--algorithm", default=Algorithm.AUTO.value, type=click.Choice([i.value for i in Algorithm]))
219
+ @click.option(
220
+ "--conf",
221
+ default=None,
222
+ help="Path to a configuration.toml file, to provide a default configuration, and a list of possible runs.",
223
+ metavar="PATH",
224
+ )
225
+ @click.option(
226
+ "--run",
227
+ default=None,
228
+ help="Name of run-configuration to run. If used, CLI arguments for database and table must be omitted.",
229
+ metavar="NAME",
230
+ )
231
+ @click.option(
232
+ "--dbt",
233
+ is_flag=True,
234
+ help="Run a diff using your local dbt project. Expects to be run from a dbt project folder by default.",
235
+ )
236
+ @click.option(
237
+ "--cloud",
238
+ is_flag=True,
239
+ help="Add this flag along with --dbt to run a diff using your local dbt project on Datafold cloud. Expects an api key on env var DATAFOLD_API_KEY.",
240
+ )
241
+ @click.option(
242
+ "--dbt-profiles-dir",
243
+ envvar="DBT_PROFILES_DIR",
244
+ default=None,
245
+ metavar="PATH",
246
+ help="Which directory to look in for the profiles.yml file. If not set, we follow the default profiles.yml location for the dbt version being used. Can also be set via the DBT_PROFILES_DIR environment variable.",
247
+ )
248
+ @click.option(
249
+ "--dbt-project-dir",
250
+ default=None,
251
+ metavar="PATH",
252
+ help="Which directory to look in for the dbt_project.yml file. Default is the current working directory and its parents.",
253
+ )
254
+ @click.option(
255
+ "--select",
256
+ "-s",
257
+ default=None,
258
+ metavar="SELECTION or MODEL_NAME",
259
+ help="--select dbt resources to compare using dbt selection syntax in dbt versions >= 1.5.\nIn versions < 1.5, it will naively search for a model with MODEL_NAME as the name.",
260
+ )
261
+ @click.option(
262
+ "--state",
263
+ "-s",
264
+ default=None,
265
+ metavar="PATH",
266
+ help="Specify manifest to utilize for 'prod' comparison paths instead of using configuration.",
267
+ )
268
+ @click.option(
269
+ "-pd",
270
+ "--prod-database",
271
+ "prod_database",
272
+ default=None,
273
+ help="Override the dbt production database configuration within dbt_project.yml",
274
+ )
275
+ @click.option(
276
+ "-ps",
277
+ "--prod-schema",
278
+ "prod_schema",
279
+ default=None,
280
+ help="Override the dbt production schema configuration within dbt_project.yml",
281
+ )
282
+ def main(conf, run, **kw) -> None:
283
+ log_handlers = _get_log_handlers(kw["dbt"])
284
+ if kw["table2"] is None and kw["database2"]:
285
+ # Use the "database table table" form
286
+ kw["table2"] = kw["database2"]
287
+ kw["database2"] = kw["database1"]
288
+
289
+ if kw["version"]:
290
+ print(f"v{__version__}")
291
+ return
292
+
293
+ if conf:
294
+ kw = apply_config_from_file(conf, run, kw)
295
+
296
+ if kw["no_tracking"]:
297
+ disable_tracking()
298
+
299
+ if kw.get("interactive"):
300
+ kw["debug"] = True
301
+
302
+ if kw["debug"]:
303
+ log_handlers["rich_handler"].setLevel(logging.DEBUG)
304
+ logging.basicConfig(level=logging.DEBUG, handlers=list(log_handlers.values()))
305
+ if kw.get("__conf__"):
306
+ kw["__conf__"] = deepcopy(kw["__conf__"])
307
+ _remove_passwords_in_dict(kw["__conf__"])
308
+ logging.debug(f"Applied run configuration: {kw['__conf__']}")
309
+ elif kw.get("verbose"):
310
+ log_handlers["rich_handler"].setLevel(logging.INFO)
311
+ logging.basicConfig(level=logging.DEBUG, handlers=list(log_handlers.values()))
312
+ else:
313
+ log_handlers["rich_handler"].setLevel(logging.WARNING)
314
+ logging.basicConfig(level=logging.DEBUG, handlers=list(log_handlers.values()))
315
+
316
+ try:
317
+ state = kw.pop("state", None)
318
+ if state:
319
+ state = os.path.expanduser(state)
320
+ profiles_dir_override = kw.pop("dbt_profiles_dir", None)
321
+ if profiles_dir_override:
322
+ profiles_dir_override = os.path.expanduser(profiles_dir_override)
323
+ project_dir_override = kw.pop("dbt_project_dir", None)
324
+ if project_dir_override:
325
+ project_dir_override = os.path.expanduser(project_dir_override)
326
+ if kw["dbt"]:
327
+ dbt_diff(
328
+ log_status_handler=log_handlers.get("log_status_handler"),
329
+ profiles_dir_override=profiles_dir_override,
330
+ project_dir_override=project_dir_override,
331
+ is_cloud=kw["cloud"],
332
+ dbt_selection=kw["select"],
333
+ json_output=kw["json_output"],
334
+ state=state,
335
+ where_flag=kw["where"],
336
+ stats_flag=kw["stats"],
337
+ columns_flag=kw["columns"],
338
+ production_database_flag=kw["prod_database"],
339
+ production_schema_flag=kw["prod_schema"],
340
+ )
341
+ else:
342
+ _data_diff(dbt_project_dir=project_dir_override, dbt_profiles_dir=profiles_dir_override, state=state, **kw)
343
+ except Exception as e:
344
+ logging.error(e)
345
+ raise
346
+
347
+
348
+ def _get_dbs(
349
+ threads: int, database1: str, threads1: int, database2: str, threads2: int, interactive: bool
350
+ ) -> Tuple[Database, Database]:
351
+ db1 = connect(database1, threads1 or threads)
352
+ if database1 == database2:
353
+ db2 = db1
354
+ else:
355
+ db2 = connect(database2, threads2 or threads)
356
+
357
+ if interactive:
358
+ db1.enable_interactive()
359
+ db2.enable_interactive()
360
+
361
+ return db1, db2
362
+
363
+
364
+ def _set_age(options: dict, min_age: Optional[str], max_age: Optional[str], db: Database) -> None:
365
+ if min_age or max_age:
366
+ now: datetime = db.query(current_timestamp(), datetime).replace(tzinfo=None)
367
+ try:
368
+ if max_age:
369
+ options["min_update"] = parse_time_before(now, max_age)
370
+ if min_age:
371
+ options["max_update"] = parse_time_before(now, min_age)
372
+ except ParseError as e:
373
+ logging.error(f"Error while parsing age expression: {e}")
374
+
375
+
376
+ def _get_table_differ(
377
+ algorithm: str,
378
+ db1: Database,
379
+ db2: Database,
380
+ threaded: bool,
381
+ threads: int,
382
+ assume_unique_key: bool,
383
+ sample_exclusive_rows: bool,
384
+ materialize_all_rows: bool,
385
+ table_write_limit: int,
386
+ materialize_to_table: Optional[str],
387
+ bisection_factor: Optional[int],
388
+ bisection_threshold: Optional[int],
389
+ ) -> TableDiffer:
390
+ algorithm = Algorithm(algorithm)
391
+ if algorithm == Algorithm.AUTO:
392
+ algorithm = Algorithm.JOINDIFF if db1 == db2 else Algorithm.HASHDIFF
393
+
394
+ logging.info(f"Using algorithm '{algorithm.name.lower()}'.")
395
+
396
+ if algorithm == Algorithm.JOINDIFF:
397
+ return JoinDiffer(
398
+ threaded=threaded,
399
+ max_threadpool_size=threads and threads * 2,
400
+ validate_unique_key=not assume_unique_key,
401
+ sample_exclusive_rows=sample_exclusive_rows,
402
+ materialize_all_rows=materialize_all_rows,
403
+ table_write_limit=table_write_limit,
404
+ materialize_to_table=(
405
+ materialize_to_table and db1.dialect.parse_table_name(eval_name_template(materialize_to_table))
406
+ ),
407
+ )
408
+
409
+ assert algorithm == Algorithm.HASHDIFF
410
+ return HashDiffer(
411
+ bisection_factor=DEFAULT_BISECTION_FACTOR if bisection_factor is None else bisection_factor,
412
+ bisection_threshold=DEFAULT_BISECTION_THRESHOLD if bisection_threshold is None else bisection_threshold,
413
+ threaded=threaded,
414
+ max_threadpool_size=threads and threads * 2,
415
+ )
416
+
417
+
418
+ def _print_result(stats, json_output, diff_iter) -> None:
419
+ if stats:
420
+ if json_output:
421
+ rich.print(json.dumps(diff_iter.get_stats_dict()))
422
+ else:
423
+ rich.print(diff_iter.get_stats_string())
424
+
425
+ else:
426
+ for op, values in diff_iter:
427
+ color = COLOR_SCHEME.get(op, "grey62")
428
+
429
+ if json_output:
430
+ jsonl = json.dumps([op, list(values)])
431
+ rich.print(f"[{color}]{jsonl}[/{color}]")
432
+ else:
433
+ text = f"{op} {', '.join(map(str, values))}"
434
+ rich.print(f"[{color}]{text}[/{color}]")
435
+
436
+ sys.stdout.flush()
437
+
438
+
439
+ def _get_expanded_columns(
440
+ columns: List[str],
441
+ case_sensitive: bool,
442
+ mutual: Set[str],
443
+ db1: Database,
444
+ schema1: dict,
445
+ table1: str,
446
+ db2: Database,
447
+ schema2: dict,
448
+ table2: str,
449
+ ) -> Set[str]:
450
+ expanded_columns: Set[str] = set()
451
+ for c in columns:
452
+ cc = c if case_sensitive else c.lower()
453
+ match = set(match_like(cc, mutual))
454
+ if not match:
455
+ m1 = None if any(match_like(cc, schema1.keys())) else f"{db1}/{table1}"
456
+ m2 = None if any(match_like(cc, schema2.keys())) else f"{db2}/{table2}"
457
+ not_matched = ", ".join(m for m in [m1, m2] if m)
458
+ raise ValueError(f"Column '{c}' not found in: {not_matched}")
459
+
460
+ expanded_columns |= match
461
+ return expanded_columns
462
+
463
+
464
+ def _get_threads(threads: Union[int, str, None], threads1: Optional[int], threads2: Optional[int]) -> Tuple[bool, int]:
465
+ threaded = True
466
+ if threads is None:
467
+ threads = 1
468
+ elif isinstance(threads, str) and threads.lower() == "serial":
469
+ assert not (threads1 or threads2)
470
+ threaded = False
471
+ threads = 1
472
+ else:
473
+ try:
474
+ threads = int(threads)
475
+ except ValueError:
476
+ logging.error("Error: threads must be a number, or 'serial'.")
477
+ raise
478
+
479
+ if threads < 1:
480
+ logging.error("Error: threads must be >= 1")
481
+ raise ValueError("Error: threads must be >= 1")
482
+
483
+ return threaded, threads
484
+
485
+
486
+ def _data_diff(
487
+ database1,
488
+ table1,
489
+ database2,
490
+ table2,
491
+ key_columns,
492
+ update_column,
493
+ columns,
494
+ limit,
495
+ algorithm,
496
+ bisection_factor,
497
+ bisection_threshold,
498
+ min_age,
499
+ max_age,
500
+ stats,
501
+ debug,
502
+ verbose,
503
+ version,
504
+ interactive,
505
+ no_tracking,
506
+ threads,
507
+ case_sensitive,
508
+ json_output,
509
+ where,
510
+ assume_unique_key,
511
+ sample_exclusive_rows,
512
+ materialize_all_rows,
513
+ table_write_limit,
514
+ materialize_to_table,
515
+ dbt,
516
+ cloud,
517
+ dbt_profiles_dir,
518
+ dbt_project_dir,
519
+ prod_database,
520
+ prod_schema,
521
+ select,
522
+ state,
523
+ threads1=None,
524
+ threads2=None,
525
+ __conf__=None,
526
+ ) -> None:
527
+ if limit and stats:
528
+ logging.error("Cannot specify a limit when using the -s/--stats switch")
529
+ return
530
+
531
+ key_columns = key_columns or ("id",)
532
+ threaded, threads = _get_threads(threads, threads1, threads2)
533
+ start = time.monotonic()
534
+
535
+ if database1 is None or database2 is None:
536
+ logging.error(
537
+ f"Error: Databases not specified. Got {database1} and {database2}. Use --help for more information."
538
+ )
539
+ return
540
+
541
+ db1: Database
542
+ db2: Database
543
+ db1, db2 = _get_dbs(threads, database1, threads1, database2, threads2, interactive)
544
+ with db1, db2:
545
+ options = {
546
+ "case_sensitive": case_sensitive,
547
+ "where": where,
548
+ }
549
+
550
+ _set_age(options, min_age, max_age, db1)
551
+ dbs: Tuple[Database, Database] = db1, db2
552
+
553
+ differ = _get_table_differ(
554
+ algorithm,
555
+ db1,
556
+ db2,
557
+ threaded,
558
+ threads,
559
+ assume_unique_key,
560
+ sample_exclusive_rows,
561
+ materialize_all_rows,
562
+ table_write_limit,
563
+ materialize_to_table,
564
+ bisection_factor,
565
+ bisection_threshold,
566
+ )
567
+
568
+ table_names = table1, table2
569
+ table_paths = [db.dialect.parse_table_name(t) for db, t in safezip(dbs, table_names)]
570
+
571
+ schemas = list(differ._thread_map(_get_schema, safezip(dbs, table_paths)))
572
+ schema1, schema2 = schemas = [
573
+ create_schema(db.name, table_path, schema, case_sensitive)
574
+ for db, table_path, schema in safezip(dbs, table_paths, schemas)
575
+ ]
576
+
577
+ mutual = schema1.keys() & schema2.keys() # Case-aware, according to case_sensitive
578
+ logging.debug(f"Available mutual columns: {mutual}")
579
+
580
+ expanded_columns = _get_expanded_columns(
581
+ columns, case_sensitive, mutual, db1, schema1, table1, db2, schema2, table2
582
+ )
583
+ columns = tuple(expanded_columns - {*key_columns, update_column})
584
+
585
+ if db1 == db2:
586
+ diff_schemas(
587
+ table_names[0],
588
+ table_names[1],
589
+ schema1,
590
+ schema2,
591
+ (
592
+ *key_columns,
593
+ update_column,
594
+ *columns,
595
+ ),
596
+ )
597
+
598
+ logging.info(f"Diffing using columns: key={key_columns} update={update_column} extra={columns}.")
599
+
600
+ segments = [
601
+ TableSegment(db, table_path, key_columns, update_column, columns, **options)._with_raw_schema(raw_schema)
602
+ for db, table_path, raw_schema in safezip(dbs, table_paths, schemas)
603
+ ]
604
+
605
+ diff_iter = differ.diff_tables(*segments)
606
+
607
+ if limit:
608
+ assert not stats
609
+ diff_iter = islice(diff_iter, int(limit))
610
+
611
+ _print_result(stats, json_output, diff_iter)
612
+
613
+ end = time.monotonic()
614
+ logging.info(f"Duration: {end-start:.2f} seconds.")
615
+
616
+
617
+ if __name__ == "__main__":
618
+ main()
File without changes
@@ -0,0 +1,13 @@
1
+ from abc import ABC
2
+
3
+ import attrs
4
+
5
+
6
+ @attrs.define(frozen=False)
7
+ class AbstractCompiler(ABC):
8
+ pass
9
+
10
+
11
+ @attrs.define(frozen=False, eq=False)
12
+ class Compilable(ABC):
13
+ pass