-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdb_access.py
1528 lines (1289 loc) · 52.2 KB
/
db_access.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import functools
import json
import operator
from abc import ABC, abstractmethod
from collections import Counter
from dataclasses import dataclass
from typing import Any, Callable, Iterator, Sequence, final, overload
import sqlalchemy as sa
from sqlalchemy.sql import selectable
from sqlalchemy.sql.expression import FromClause
def is_mssql(engine: sa.engine.Engine) -> bool:
return engine.name == "mssql"
def is_postgresql(engine: sa.engine.Engine) -> bool:
return engine.name == "postgresql"
def is_snowflake(engine: sa.engine.Engine) -> bool:
return engine.name == "snowflake"
def is_bigquery(engine: sa.engine.Engine) -> bool:
return engine.name == "bigquery"
def is_impala(engine: sa.engine.Engine) -> bool:
return engine.name == "impala"
def is_db2(engine: sa.engine.Engine) -> bool:
return engine.name == "ibm_db_sa"
def get_table_columns(
table: sa.Table | sa.Subquery, column_names: Sequence[str]
) -> list[sa.ColumnElement]:
return [table.c[column_name] for column_name in column_names]
def apply_patches(engine: sa.engine.Engine) -> None:
"""Apply patches to e.g. specific dialect not implemented by sqlalchemy."""
if is_bigquery(engine):
# Patch for the EXCEPT operator (see BigQuery set operators
# https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#set_operators)
# This is implemented in the same way as for sqlalchemy-bigquery, see
# https://github.com/googleapis/python-bigquery-sqlalchemy/blob/f1889443bd4d680550387b9bb14daeea8eb792d4/sqlalchemy_bigquery/base.py#L187
compound_keywords_extensions = {
selectable.CompoundSelect.EXCEPT: "EXCEPT DISTINCT", # type: ignore[attr-defined]
selectable.CompoundSelect.EXCEPT_ALL: "EXCEPT ALL", # type: ignore[attr-defined]
}
engine.dialect.statement_compiler.compound_keywords.update(
compound_keywords_extensions
)
# Patch for the INTERSECT operator (see BigQuery set operators
# https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#set_operators)
# This might cause some problems (see discussion in
# https://github.com/googleapis/python-bigquery-sqlalchemy/issues/388) but doesn't seem
# to be an issue here.
compound_keywords_extensions = {
selectable.CompoundSelect.INTERSECT: "INTERSECT DISTINCT", # type: ignore[attr-defined]
selectable.CompoundSelect.INTERSECT_ALL: "INTERSECT ALL", # type: ignore[attr-defined]
}
engine.dialect.statement_compiler.compound_keywords.update(
compound_keywords_extensions
)
@overload
def lowercase_column_names(column_names: str) -> str: # fmt: off
...
@overload
def lowercase_column_names(column_names: list[str]) -> list[str]: # fmt: off
...
def lowercase_column_names(column_names: str | list[str]) -> str | list[str]:
# This function is used due to capitalization problems with snowflake.
# Once these issues are resolved in snowflake-sqlalchemy, the usages of this
# function should be removed.
# See https://github.com/snowflakedb/snowflake-sqlalchemy/issues/157.
if isinstance(column_names, str):
return column_names.lower()
return [column_name.lower() for column_name in column_names]
@dataclass(frozen=True)
class Condition:
"""Condition allows for further narrowing down of a DataSource in a Constraint.
A ``Condition`` can be thought of as a filter, the content of a sql 'where' clause
or a condition as known from probability theory.
While a ``DataSource`` is expressed more generally, one might be interested
in testing properties of a specific part of said ``DataSource`` in light
of a particular constraint. Hence using ``Condition`` allows for the reusage
of a ``DataSource``, in lieu of creating a new custom ``DataSource`` with
the ``Condition`` implicitly built in.
A ``Condition`` can either be 'atomic', i.e. not further reducible to sub-conditions
or 'composite', i.e. combining multiple subconditions. In the former case, it can
be instantiated with help of the ``raw_string`` parameter, e.g. ``"col1 > 0"``. In the
latter case, it can be instantiated with help of the ``conditions`` and
``reduction_operator`` parameters. ``reduction_operator`` allows for two values: ``"and"`` (logical
conjunction) and ``"or"`` (logical disjunction). Note that composition of ``Condition``
supports arbitrary degrees of nesting.
"""
raw_string: str | None = None
conditions: Sequence[Condition] | None = None
reduction_operator: str | None = None
def __post_init__(self):
if self._is_atomic() and self.conditions is not None:
raise ValueError(
"Condition can either be instantiated atomically, with "
"the raw_query parameter, or in a composite fashion, with "
"the conditions parameter. "
"Exactly one of them needs to be provided, yet both are."
)
if not self._is_atomic() and (
self.conditions is None or len(self.conditions) == 0
):
raise ValueError(
"Condition can either be instantiated atomically, with "
"the raw_query parameter, or in a composite fashion, with "
"the conditions parameter. "
"Exactly one of them needs to be provided, yet none is."
)
if not self._is_atomic() and self.reduction_operator not in ["and", "or"]:
raise ValueError(
"reuction_operator has to be either 'and' or 'or' but "
f"obtained {self.reduction_operator}."
)
def _is_atomic(self) -> bool:
return self.raw_string is not None
def __str__(self) -> str:
if self._is_atomic():
if self.raw_string is None:
raise ValueError(
"Condition can either be instantiated atomically, with "
"the raw_query parameter, or in a composite fashion, with "
"the conditions parameter. "
"Exactly one of them needs to be provided, yet none is."
)
return self.raw_string
if not self.conditions:
raise ValueError("This should never happen thanks to __post__init.")
return f" {self.reduction_operator} ".join(
f"({condition})" for condition in self.conditions
)
def snowflake_str(self) -> str:
# Temporary method - should be removed as soon as snowflake-sqlalchemy
# bug is fixed.
return str(self)
@dataclass
class MatchAndCompare:
matching_columns1: Sequence[str]
matching_columns2: Sequence[str]
comparison_columns1: Sequence[str]
comparison_columns2: Sequence[str]
def _get_matching_columns(self) -> Iterator[tuple[str, str]]:
return zip(self.matching_columns1, self.matching_columns2)
def _get_comparison_columns(self) -> Iterator[tuple[str, str]]:
return zip(self.comparison_columns1, self.comparison_columns2)
def __str__(self) -> str:
return (
f"Matched on {self.matching_columns1} and "
f"{self.matching_columns2}. Compared on "
f"{self.comparison_columns1} and "
f"{self.comparison_columns2}."
)
def get_matching_string(self, table_variable1: str, table_variable2: str) -> str:
return " AND ".join(
[
f"{table_variable1}.{column1} = {table_variable2}.{column2}"
for (column1, column2) in self._get_matching_columns()
]
)
def get_comparison_string(self, table_variable1: str, table_variable2: str) -> str:
return " AND ".join(
[
(
f"({table_variable1}.{column1} = "
f"{table_variable2}.{column2} "
f"OR ({table_variable1}.{column1} IS NULL AND "
f"{table_variable2}.{column2} IS NULL))"
)
for (column1, column2) in self._get_comparison_columns()
]
)
class DataSource(ABC):
@abstractmethod
def __str__(self) -> str:
pass
@abstractmethod
def get_clause(self, engine: sa.engine.Engine) -> FromClause:
pass
@functools.lru_cache(maxsize=1)
def get_metadata() -> sa.MetaData:
return sa.MetaData()
@final
class TableDataSource(DataSource):
def __init__(
self,
db_name: str,
table_name: str,
schema_name: str | None = None,
):
self.db_name = db_name
self.table_name = table_name
self.schema_name = schema_name
def __str__(self) -> str:
if self.schema_name:
return f"{self.db_name}.{self.schema_name}.{self.table_name}"
return self.table_name
def get_clause(self, engine: sa.engine.Engine) -> FromClause:
schema = self.schema_name
if is_mssql(engine):
schema = self.db_name + "." + self.schema_name # type: ignore
return sa.Table(
self.table_name,
get_metadata(),
autoload_with=engine,
schema=schema,
)
@final
class ExpressionDataSource(DataSource):
def __init__(self, expression: FromClause | sa.Select, name: str):
self.expression = expression
self.name = name
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return f"{self.__class__.__name__}(expression={self.expression!r}, name={self.name})"
def get_clause(self, engine: sa.engine.Engine) -> FromClause:
return self.expression.alias()
@final
class RawQueryDataSource(DataSource):
def __init__(self, query_string: str, name: str, columns: list[str] | None = None):
self.query_string = query_string
self.name = name
self.columns = columns
wrapped_query = f"({query_string}) as t"
if columns is not None and len(columns) > 0:
subquery = (
sa.text(query_string)
.columns(*[sa.column(column_name) for column_name in columns])
.subquery()
)
self.clause = subquery
else:
wrapped_query = f"({query_string}) as t"
self.clause = sa.select("*").select_from(sa.text(wrapped_query)).alias()
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return f"{self.__class__.__name__}(query_string={self.query_string}, name={self.name}, columns={self.columns})"
def get_clause(self, engine: sa.engine.Engine) -> FromClause:
return self.clause
class DataReference:
def __init__(
self,
data_source: DataSource,
columns: list[str] | None = None,
condition: Condition | None = None,
):
if columns is not None and not isinstance(columns, list):
raise TypeError(f"columns must be a list, not {type(columns)}")
self.data_source = data_source
self.columns = columns
self.condition = condition
def __repr__(self) -> str:
return f"{self.__class__.__name__}(data_source={self.data_source!r}, columns={self.columns!r}, condition={self.condition!r})"
def get_selection(self, engine: sa.engine.Engine) -> sa.Select:
clause = self.data_source.get_clause(engine)
if self.columns:
column_names = self.get_columns(engine)
if column_names is None:
raise ValueError("This shouldn't happen.")
selection = sa.select(
*[clause.c[column_name] for column_name in column_names]
)
else:
selection = sa.select(clause)
if self.condition is not None:
text = str(self.condition)
if is_snowflake(engine):
text = self.condition.snowflake_str()
selection = selection.where(sa.text(text))
if is_mssql(engine) and isinstance(self.data_source, TableDataSource):
# Allow dirty reads when using MSSQL.
# When using an ExpressionDataSource or StringDataSource, the user is
# expected to specify this by themselves.
# More on this:
# https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-2016
selection = selection.with_hint(clause, "WITH (NOLOCK)")
return selection
def get_column(self, engine: sa.engine.Engine) -> str:
"""Fetch the only relevant column of a DataReference."""
if self.columns is None:
raise ValueError(
f"Trying to access column of DataReference "
f"{str(self)} yet none is given."
)
columns = self.get_columns(engine)
if columns is None:
raise ValueError("No columns defined.")
if len(columns) > 1:
raise ValueError(
"DataReference was expected to only have a single column but had multiple: "
f"{columns}"
)
return columns[0]
def get_columns(self, engine: sa.engine.Engine) -> list[str] | None:
"""Fetch all relevant columns of a DataReference."""
if self.columns is None:
return None
if is_snowflake(engine):
return lowercase_column_names(self.columns)
return self.columns
def get_columns_or_pk_columns(self, engine: sa.engine.Engine) -> list[str] | None:
return (
self.columns
if self.columns is not None
else get_primary_keys(engine, self)[0]
)
def get_column_selection_string(self) -> str:
if self.columns is None:
return " * "
return ", ".join(map(lambda x: f"'{x}'", self.columns))
def get_clause_string(self, *, return_where: bool = True) -> str:
where_string = "WHERE " if return_where else ""
return "" if self.condition is None else where_string + str(self.condition)
def __str__(self) -> str:
if self.columns is None:
return str(self.data_source)
return f"{self.data_source}'s column(s) {self.get_column_selection_string()}"
def merge_conditions(
condition1: Condition | None, condition2: Condition | None
) -> Condition | None:
if condition1 and condition2 is None:
return None
if condition1 is None:
return condition2
if condition2 is None:
return condition1
return Condition(conditions=[condition1, condition2], reduction_operator="and")
def get_date_span(
engine: sa.engine.Engine, ref: DataReference, date_column_name: str
) -> tuple[float, list[sa.Select]]:
if is_snowflake(engine):
date_column_name = lowercase_column_names(date_column_name)
subquery = ref.get_selection(engine).alias()
column = subquery.c[date_column_name]
if is_postgresql(engine):
selection = sa.select(
*[
sa.sql.extract(
"day",
(
sa.func.date_trunc(sa.literal("day"), sa.func.max(column))
- sa.func.date_trunc(sa.literal("day"), sa.func.min(column))
),
)
]
)
elif is_mssql(engine) or is_snowflake(engine):
selection = sa.select(
*[
sa.func.datediff(
sa.text("day"),
sa.func.min(column),
sa.func.max(column),
)
]
)
elif is_bigquery(engine):
selection = sa.select(
*[
sa.func.date_diff(
sa.func.max(column),
sa.func.min(column),
sa.literal_column("DAY"),
)
]
)
elif is_impala(engine):
selection = sa.select(
*[
sa.func.datediff(
sa.func.to_date(sa.func.max(column)),
sa.func.to_date(sa.func.min(column)),
)
]
)
elif is_db2(engine):
selection = sa.select(
*[
sa.func.days_between(
sa.func.max(column),
sa.func.min(column),
)
]
)
else:
raise NotImplementedError(
"Date spans not yet implemented for this sql dialect."
)
date_span = engine.connect().execute(selection).scalar()
if date_span is None:
raise ValueError("Date span could not be fetched.")
if date_span < 0:
raise ValueError(
f"Date span has negative value: {date_span}. It must be positive."
)
# Note (ivergara): From postgres 13 to 14 the type returned by the selection changed from float to Decimal.
# Now we're making sure that the returned type of this function is a float to comply with downstream expectations.
# Since we're dealing with date spans, and most likely the level of precision doesn't require a Decimal
# representation, we decided to enforce here the float type instead of using Decimal downstream.
return float(date_span), [selection]
def get_date_growth_rate(
engine: sa.engine.Engine,
ref: DataReference,
ref2: DataReference,
date_column: str,
date_column2: str,
) -> tuple[float, list[sa.Select]]:
date_span, selections = get_date_span(engine, ref, date_column)
date_span2, selections2 = get_date_span(engine, ref2, date_column2)
if date_span2 == 0:
raise ValueError("Reference date span is not allowed to be zero.")
return date_span / date_span2 - 1, [*selections, *selections2]
def get_interval_overlaps_nd(
engine: sa.engine.Engine,
ref: DataReference,
key_columns: list[str] | None,
start_columns: list[str],
end_columns: list[str],
end_included: bool,
) -> tuple[sa.sql.selectable.CompoundSelect, sa.sql.selectable.Select]:
r"""Create selectables for interval overlaps in n dimensions.
We define the presence of 'overlap' as presence of a non-empty intersection
between two intervals.
Given that we care about a single dimension and have two intervals :math:`t1` and :math:`t2`,
we define an overlap follows:
.. math::
\\begin{align} \\text{overlap}(t_1, t_2) \\Leftrightarrow
&(min(t_1) \\leq min(t_2) \\land max(t_1) \\geq min(t_2)) \\\\
&\\lor \\\\
&(min(t_2) \\leq min(t_1) \\land max(t_2) \\geq min(t_1))
\\end{align}
We can drop the second clause of the above disjunction if we define :math:`t_1` to be the 'leftmost'
interval. We do so when building our query.
Note that the above equations are representative of ``end_included=True`` and the second clause
of the conjunction would use a strict inequality if ``end_included=False``.
We define an overlap in several dimensions as the conjunction of overlaps in every single dimension.
"""
if is_snowflake(engine):
if key_columns:
key_columns = lowercase_column_names(key_columns)
start_columns = lowercase_column_names(start_columns)
end_columns = lowercase_column_names(end_columns)
if len(start_columns) != len(end_columns):
raise ValueError(
f"Expected same dimensionality for start_columns and end_columns. "
f"Instead, start_columns has dimensionality {len(start_columns)} and "
f"end_columns has dimensionality {len(end_columns)}."
)
dimensionality = len(start_columns)
table1 = ref.get_selection(engine).alias()
table2 = ref.get_selection(engine).alias()
key_conditions = (
[table1.c[key_column] == table2.c[key_column] for key_column in key_columns]
if key_columns
else [sa.literal(True)]
)
table_key_columns = get_table_columns(table1, key_columns) if key_columns else []
end_operator = operator.ge if end_included else operator.gt
# We have a violation in two scenarios:
# 1. At least two entries are exactly equal in key and interval columns
# 2. Two entries are not exactly equal in key and interval_columns and fuilfill violation_condition
# Scenario 1
duplicate_selection = duplicates(table1)
duplicate_subquery = duplicate_selection.subquery()
# scenario 2
naive_violation_condition = sa.and_(
*[
sa.and_(
table1.c[start_columns[dimension]]
<= table2.c[start_columns[dimension]],
end_operator(
table1.c[end_columns[dimension]], table2.c[start_columns[dimension]]
),
)
for dimension in range(dimensionality)
]
)
interval_inequality_condition = sa.or_(
*[
sa.or_(
table1.c[start_columns[dimension]]
!= table2.c[start_columns[dimension]],
table2.c[end_columns[dimension]] != table2.c[end_columns[dimension]],
)
for dimension in range(dimensionality)
]
)
distinct_violation_condition = sa.and_(
naive_violation_condition,
interval_inequality_condition,
)
distinct_join_condition = sa.and_(*key_conditions, distinct_violation_condition)
distinct_violation_selection = sa.select(
*table_key_columns,
*[
table.c[start_column]
for table in [table1, table2]
for start_column in start_columns
],
*[
table.c[end_column]
for table in [table1, table2]
for end_column in end_columns
],
).select_from(table1.join(table2, distinct_join_condition))
distinct_violation_subquery = distinct_violation_selection.subquery()
# Note, Kevin, 21/12/09
# The following approach would likely be preferable to the approach used
# subsequently. Sadly, it seems to not work for mssql. As of now, it is
# unclear to me why.
# distincter = (
# sa.func.distinct(sa.tuple_(*get_table_columns(violation_subquery, key_columns)))
# if key_columns
# else sa.func.distinct("*")
# )
# n_violations_selection = sa.select([sa.func.count(distincter)]).select_from(
# violation_subquery
# )
# Merge scenarios 1 and 2.
# We need to 'impute' the missing columns for the duplicate selection in order for the union between
# both selections to work.
duplicate_selection = sa.select(
*(
# Already existing columns
[
duplicate_subquery.c[column]
for column in distinct_violation_subquery.columns.keys()
if column in duplicate_subquery.columns.keys()
]
# Fill all missing columns with NULLs.
+ [
sa.null().label(column)
for column in distinct_violation_subquery.columns.keys()
if column not in duplicate_subquery.columns.keys()
]
)
)
violation_selection = duplicate_selection.union(distinct_violation_selection)
violation_subquery = violation_selection.subquery()
keys = (
get_table_columns(violation_subquery, key_columns)
if key_columns
else violation_subquery.columns
)
violation_subquery = sa.select(*keys).group_by(*keys).subquery()
n_violations_selection = sa.select(sa.func.count()).select_from(violation_subquery)
return violation_selection, n_violations_selection
def _not_in_interval_condition(
main_table: sa.Table | sa.Subquery,
helper_table: sa.Table | sa.Subquery,
date_column: str,
key_columns: list[str],
start_column: str,
end_column: str,
) -> sa.ColumnElement:
return sa.not_(
sa.exists(
sa.select(helper_table).where(
sa.and_(
*[
main_table.c[key_column] == helper_table.c[key_column]
for key_column in key_columns
],
main_table.c[date_column] > helper_table.c[start_column],
main_table.c[date_column] < helper_table.c[end_column],
)
)
)
)
def _get_interval_gaps(
engine: sa.engine.Engine,
ref: DataReference,
key_columns: list[str] | None,
start_column: str,
end_column: str,
legitimate_gap_size: float,
make_gap_condition: Callable[
[sa.Engine, sa.Subquery, sa.Subquery, str, str, float], sa.ColumnElement[bool]
],
) -> tuple[sa.Select, sa.Select]:
if is_snowflake(engine):
if key_columns:
key_columns = lowercase_column_names(key_columns)
start_column = lowercase_column_names(start_column)
end_column = lowercase_column_names(end_column)
# Inspired by
# https://stackoverflow.com/questions/9604400/sql-query-to-show-gaps-between-multiple-date-ranges.
helper_table = ref.get_selection(engine).alias()
raw_start_table = ref.get_selection(engine).alias()
raw_end_table = ref.get_selection(engine).alias()
if key_columns is None or key_columns == []:
key_columns = [
column.name
for column in helper_table.columns
if column.name not in [start_column, end_column]
]
start_not_in_other_interval_condition = _not_in_interval_condition(
raw_start_table,
helper_table,
start_column,
key_columns,
start_column,
end_column,
)
end_not_in_other_interval_condition = _not_in_interval_condition(
raw_end_table, helper_table, end_column, key_columns, start_column, end_column
)
start_rank_column = (
sa.func.row_number()
.over(order_by=[raw_start_table.c[col] for col in [start_column] + key_columns])
.label("start_rank")
)
end_rank_column = (
sa.func.row_number()
.over(order_by=[raw_end_table.c[col] for col in [end_column] + key_columns])
.label("end_rank")
)
start_table = (
sa.select(*raw_start_table.columns, start_rank_column)
.where(start_not_in_other_interval_condition)
.subquery()
)
end_table = (
sa.select(*raw_end_table.columns, end_rank_column)
.where(end_not_in_other_interval_condition)
.subquery()
)
gap_condition = make_gap_condition(
engine, start_table, end_table, start_column, end_column, legitimate_gap_size
)
join_condition = sa.and_(
*[
start_table.c[key_column] == end_table.c[key_column]
for key_column in key_columns
],
start_table.c["start_rank"] == end_table.c["end_rank"] + 1,
gap_condition,
)
violation_selection = sa.select(
*get_table_columns(start_table, key_columns),
start_table.c[start_column],
end_table.c[end_column],
).select_from(start_table.join(end_table, join_condition))
violation_subquery = violation_selection.subquery()
keys = get_table_columns(violation_subquery, key_columns)
grouped_violation_subquery = sa.select(*keys).group_by(*keys).subquery()
n_violations_selection = sa.select(sa.func.count()).select_from(
grouped_violation_subquery
)
return violation_selection, n_violations_selection
def _date_gap_condition(
engine: sa.engine.Engine,
start_table: sa.Subquery,
end_table: sa.Subquery,
start_column: str,
end_column: str,
legitimate_gap_size: float,
) -> sa.ColumnElement[bool]:
if is_mssql(engine) or is_snowflake(engine):
gap_condition = (
sa.func.datediff(
sa.text("day"),
end_table.c[end_column],
start_table.c[start_column],
)
> legitimate_gap_size
)
elif is_impala(engine):
gap_condition = (
sa.func.datediff(
sa.func.to_date(start_table.c[start_column]),
sa.func.to_date(end_table.c[end_column]),
)
> legitimate_gap_size
)
elif is_bigquery(engine):
# see https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date_diff
# Note that to have a gap (positive date_diff), the first date (start table)
# in date_diff must be greater than the second date (end_table)
gap_condition = (
sa.func.date_diff(
start_table.c[start_column], end_table.c[end_column], sa.text("DAY")
)
> legitimate_gap_size
)
elif is_postgresql(engine):
gap_condition = (
sa.sql.extract(
"day",
(
sa.func.date_trunc(sa.literal("day"), start_table.c[start_column])
- sa.func.date_trunc(sa.literal("day"), end_table.c[end_column])
),
)
> legitimate_gap_size
)
elif is_db2(engine):
gap_condition = (
sa.func.days_between(
start_table.c[start_column],
end_table.c[end_column],
)
> legitimate_gap_size
)
else:
raise NotImplementedError(f"Date gaps not yet implemented for {engine.name}.")
return gap_condition
def get_date_gaps(
engine: sa.engine.Engine,
ref: DataReference,
key_columns: list[str] | None,
start_column: str,
end_column: str,
legitimate_gap_size: float,
) -> tuple[sa.Select, sa.Select]:
return _get_interval_gaps(
engine,
ref,
key_columns,
start_column,
end_column,
legitimate_gap_size,
_date_gap_condition,
)
def _numeric_gap_condition(
_engine: sa.engine.Engine,
start_table: sa.Subquery,
end_table: sa.Subquery,
start_column: str,
end_column: str,
legitimate_gap_size: float,
) -> sa.ColumnElement[bool]:
gap_condition = (
start_table.c[start_column] - end_table.c[end_column]
) > legitimate_gap_size
return gap_condition
def get_numeric_gaps(
engine: sa.engine.Engine,
ref: DataReference,
key_columns: list[str] | None,
start_column: str,
end_column: str,
legitimate_gap_size: float = 0,
) -> tuple[sa.Select, sa.Select]:
return _get_interval_gaps(
engine,
ref,
key_columns,
start_column,
end_column,
legitimate_gap_size,
_numeric_gap_condition,
)
def get_functional_dependency_violations(
engine: sa.engine.Engine,
ref: DataReference,
key_columns: list[str],
) -> tuple[Any, list[sa.Select]]:
selection = ref.get_selection(engine)
uniques = selection.distinct().cte()
key_columns_sa = [uniques.c[key_column] for key_column in key_columns]
violations_stmt = (
sa.select(*key_columns_sa).group_by(*key_columns_sa).having(sa.func.count() > 1)
).cte()
join_condition = sa.and_(
*[
uniques.c[key_column] == violations_stmt.c[key_column]
for key_column in key_columns
]
)
violation_tuples = sa.select(uniques).select_from(
uniques.join(violations_stmt, join_condition)
)
result = engine.connect().execute(violation_tuples).fetchall()
return result, [violation_tuples]
def get_row_count(
engine: sa.engine.Engine, ref: DataReference, row_limit: int | None = None
) -> tuple[int, list[sa.Select]]:
"""Return the number of rows for a `DataReference`.
If `row_limit` is given, the number of rows is capped at the limit.
"""
selection = ref.get_selection(engine)
if row_limit:
selection = selection.limit(row_limit)
subquery = selection.alias()
final_selection = sa.select(sa.cast(sa.func.count(), sa.BigInteger)).select_from(
subquery
)
result = int(str(engine.connect().execute(final_selection).scalar()))
return result, [final_selection]
def get_column(
engine: sa.engine.Engine,
ref: DataReference,
*,
aggregate_operator: Callable | None = None,
) -> tuple[Any, list[sa.Select]]:
"""
Query the database for the values of the relevant column (as returned by `get_column(...)`).
If an aggregation operation is passed, the results are aggregated accordingly
and a single scalar value is returned.
"""
subquery = ref.get_selection(engine).alias()
column = subquery.c[ref.get_column(engine)]
result: Any | None | Sequence[Any]
if not aggregate_operator:
selection = sa.select(column)
result = engine.connect().execute(selection).scalars().all()
else:
selection = sa.select(aggregate_operator(column))
result = engine.connect().execute(selection).scalar()
return result, [selection]
def get_min(
engine: sa.engine.Engine, ref: DataReference
) -> tuple[Any, list[sa.Select]]:
column_operator = sa.func.min
return get_column(engine, ref, aggregate_operator=column_operator)
def get_max(
engine: sa.engine.Engine, ref: DataReference
) -> tuple[Any, list[sa.Select]]:
column_operator = sa.func.max
return get_column(engine, ref, aggregate_operator=column_operator)
def get_mean(
engine: sa.engine.Engine, ref: DataReference
) -> tuple[Any, list[sa.Select]]:
def column_operator(column):
if is_impala(engine):
return sa.func.avg(column)
return sa.func.avg(sa.cast(column, sa.DECIMAL))
return get_column(engine, ref, aggregate_operator=column_operator)
def get_percentile(
engine: sa.engine.Engine, ref: DataReference, percentage: float
) -> tuple[float, list[sa.Select]]:
row_count = "dj_row_count"
row_num = "dj_row_num"
column_name = ref.get_column(engine)
base_selection = ref.get_selection(engine)
column = base_selection.subquery().c[column_name]
counting_selection = sa.select(
column,
sa.func.row_number().over(order_by=column).label(row_num),
sa.func.count().over(partition_by=None).label(row_count),
).where(column.is_not(None))
counting_subquery = counting_selection.subquery()