-
Notifications
You must be signed in to change notification settings - Fork 515
/
Copy pathREADME.md
1558 lines (1109 loc) · 51.6 KB
/
README.md
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
This [dbt](https://github.com/dbt-labs/dbt) package contains macros that can be (re)used across dbt projects.
## Installation Instructions
Check [dbt Hub](https://hub.getdbt.com/dbt-labs/dbt_utils/latest/) for the latest installation instructions, or [read the docs](https://docs.getdbt.com/docs/package-management) for more information on installing packages.
----
## Contents
**[Generic tests](#generic-tests)**
- [equal_rowcount](#equal_rowcount-source)
- [fewer_rows_than](#fewer_rows_than-source)
- [equality](#equality-source)
- [expression_is_true](#expression_is_true-source)
- [recency](#recency-source)
- [at_least_one](#at_least_one-source)
- [not_constant](#not_constant-source)
- [not_empty_string](#not_empty_string-source)
- [cardinality_equality](#cardinality_equality-source)
- [not_null_proportion](#not_null_proportion-source)
- [not_accepted_values](#not_accepted_values-source)
- [relationships_where](#relationships_where-source)
- [mutually_exclusive_ranges](#mutually_exclusive_ranges-source)
- [unique_combination_of_columns](#unique_combination_of_columns-source)
- [accepted_range](#accepted_range-source)
**[Macros](#macros)**
- [Introspective macros](#introspective-macros):
- [get_column_values](#get_column_values-source)
- [get_filtered_columns_in_relation](#get_filtered_columns_in_relation-source)
- [get_relations_by_pattern](#get_relations_by_pattern-source)
- [get_relations_by_prefix](#get_relations_by_prefix-source)
- [get_query_results_as_dict](#get_query_results_as_dict-source)
- [SQL generators](#sql-generators)
- [date_spine](#date_spine-source)
- [deduplicate](#deduplicate-source)
- [haversine_distance](#haversine_distance-source)
- [group_by](#group_by-source)
- [star](#star-source)
- [union_relations](#union_relations-source)
- [generate_series](#generate_series-source)
- [surrogate_key](#surrogate_key-source)
- [safe_add](#safe_add-source)
- [pivot](#pivot-source)
- [unpivot](#unpivot-source)
- [width_bucket](#width_bucket-source)
- [Web macros](#web-macros)
- [get_url_parameter](#get_url_parameter-source)
- [get_url_host](#get_url_host-source)
- [get_url_path](#get_url_path-source)
- [Cross-database macros](#cross-database-macros):
- [dateadd](#dateadd-source)
- [datediff](#datediff-source)
- [split_part](#split_part-source)
- [last_day](#last_day-source)
- [listagg](#listagg-source)
- [array_construct](#array_construct-source)
- [array_append](#array_append-source)
- [array_concat](#array_concat-source)
- [cast_array_to_string](#cast_array_to_string-source)
- [Jinja Helpers](#jinja-helpers)
- [pretty_time](#pretty_time-source)
- [pretty_log_format](#pretty_log_format-source)
- [log_info](#log_info-source)
- [slugify](#slugify-source)
[Materializations](#materializations):
- [insert_by_period](#insert_by_period-source)
----
### Generic Tests
#### equal_rowcount ([source](macros/generic_tests/equal_rowcount.sql))
Asserts that two relations have the same number of rows.
**Usage:**
```yaml
version: 2
models:
- name: model_name
tests:
- dbt_utils.equal_rowcount:
compare_model: ref('other_table_name')
```
This test supports the `group_by_columns` parameter; see [Grouping in tests](#grouping-in-tests) for details.
#### fewer_rows_than ([source](macros/generic_tests/fewer_rows_than.sql))
Asserts that the respective model has fewer rows than the model being compared.
Usage:
```yaml
version: 2
models:
- name: model_name
tests:
- dbt_utils.fewer_rows_than:
compare_model: ref('other_table_name')
```
This test supports the `group_by_columns` parameter; see [Grouping in tests](#grouping-in-tests) for details.
#### equality ([source](macros/generic_tests/equality.sql))
Asserts the equality of two relations. Optionally specify a subset of columns to compare.
**Usage:**
```yaml
version: 2
models:
- name: model_name
tests:
- dbt_utils.equality:
compare_model: ref('other_table_name')
compare_columns:
- first_column
- second_column
```
#### expression_is_true ([source](macros/generic_tests/expression_is_true.sql))
Asserts that a valid SQL expression is true for all records. This is useful when checking integrity across columns.
Examples:
- Verify an outcome based on the application of basic alegbraic operations between columns.
- Verify the length of a column.
- Verify the truth value of a column.
**Usage:**
```yaml
version: 2
models:
- name: model_name
tests:
- dbt_utils.expression_is_true:
expression: "col_a + col_b = total"
```
The macro accepts an optional argument `condition` that allows for asserting
the `expression` on a subset of all records.
**Usage:**
```yaml
version: 2
models:
- name: model_name
tests:
- dbt_utils.expression_is_true:
expression: "col_a + col_b = total"
condition: "created_at > '2018-12-31'"
```
This macro can also be used at the column level. When this is done, the `expression` is evaluated against the column.
```yaml
version: 2
models:
- name: model_name
columns:
- name: col_a
tests:
- dbt_utils.expression_is_true:
expression: '>= 1'
- name: col_b
tests:
- dbt_utils.expression_is_true:
expression: '= 1'
condition: col_a = 1
```
#### recency ([source](macros/generic_tests/recency.sql))
Asserts that a timestamp column in the reference model contains data that is at least as recent as the defined date interval.
**Usage:**
```yaml
version: 2
models:
- name: model_name
tests:
- dbt_utils.recency:
datepart: day
field: created_at
interval: 1
```
This test supports the `group_by_columns` parameter; see [Grouping in tests](#grouping-in-tests) for details.
#### at_least_one ([source](macros/generic_tests/at_least_one.sql))
Asserts that a column has at least one value.
**Usage:**
```yaml
version: 2
models:
- name: model_name
columns:
- name: col_name
tests:
- dbt_utils.at_least_one
```
This test supports the `group_by_columns` parameter; see [Grouping in tests](#grouping-in-tests) for details.
#### not_constant ([source](macros/generic_tests/not_constant.sql))
Asserts that a column does not have the same value in all rows.
**Usage:**
```yaml
version: 2
models:
- name: model_name
columns:
- name: column_name
tests:
- dbt_utils.not_constant
```
This test supports the `group_by_columns` parameter; see [Grouping in tests](#grouping-in-tests) for details.
#### not_empty_string ([source](macros/generic_tests/not_empty_string.sql))
Asserts that a column does not have any values equal to `''`.
**Usage:**
```yaml
version: 2
models:
- name: model_name
columns:
- name: column_name
tests:
- dbt_utils.not_empty_string
```
The macro accepts an optional argument `trim_whitespace` that controls whether whitespace should be trimmed from the column when evaluating. The default is `true`.
**Usage:**
```yaml
version: 2
models:
- name: model_name
columns:
- name: column_name
tests:
- dbt_utils.not_empty_string:
trim_whitespace: false
```
#### cardinality_equality ([source](macros/generic_tests/cardinality_equality.sql))
Asserts that values in a given column have exactly the same cardinality as values from a different column in a different model.
**Usage:**
```yaml
version: 2
models:
- name: model_name
columns:
- name: from_column
tests:
- dbt_utils.cardinality_equality:
field: other_column_name
to: ref('other_model_name')
```
#### not_null_proportion ([source](macros/generic_tests/not_null_proportion.sql))
Asserts that the proportion of non-null values present in a column is between a specified range [`at_least`, `at_most`] where `at_most` is an optional argument (default: `1.0`).
**Usage:**
```yaml
version: 2
models:
- name: my_model
columns:
- name: id
tests:
- dbt_utils.not_null_proportion:
at_least: 0.95
```
This test supports the `group_by_columns` parameter; see [Grouping in tests](#grouping-in-tests) for details.
#### not_accepted_values ([source](macros/generic_tests/not_accepted_values.sql))
Asserts that there are no rows that match the given values.
Usage:
```yaml
version: 2
models:
- name: my_model
columns:
- name: city
tests:
- dbt_utils.not_accepted_values:
values: ['Barcelona', 'New York']
```
#### relationships_where ([source](macros/generic_tests/relationships_where.sql))
Asserts the referential integrity between two relations (same as the core relationships assertions) with an added predicate to filter out some rows from the test. This is useful to exclude records such as test entities, rows created in the last X minutes/hours to account for temporary gaps due to ETL limitations, etc.
**Usage:**
```yaml
version: 2
models:
- name: model_name
columns:
- name: id
tests:
- dbt_utils.relationships_where:
to: ref('other_model_name')
field: client_id
from_condition: id <> '4ca448b8-24bf-4b88-96c6-b1609499c38b'
to_condition: created_date >= '2020-01-01'
```
#### mutually_exclusive_ranges ([source](macros/generic_tests/mutually_exclusive_ranges.sql))
Asserts that for a given lower_bound_column and upper_bound_column,
the ranges between the lower and upper bounds do not overlap with the ranges
of another row.
**Usage:**
```yaml
version: 2
models:
# test that age ranges do not overlap
- name: age_brackets
tests:
- dbt_utils.mutually_exclusive_ranges:
lower_bound_column: min_age
upper_bound_column: max_age
gaps: not_allowed
# test that each customer can only have one subscription at a time
- name: subscriptions
tests:
- dbt_utils.mutually_exclusive_ranges:
lower_bound_column: started_at
upper_bound_column: ended_at
partition_by: customer_id
gaps: required
# test that each customer can have subscriptions that start and end on the same date
- name: subscriptions
tests:
- dbt_utils.mutually_exclusive_ranges:
lower_bound_column: started_at
upper_bound_column: ended_at
partition_by: customer_id
zero_length_range_allowed: true
```
**Args:**
- `lower_bound_column` (required): The name of the column that represents the
lower value of the range. Must be not null.
- `upper_bound_column` (required): The name of the column that represents the
upper value of the range. Must be not null.
- `partition_by` (optional): If a subset of records should be mutually exclusive
(e.g. all periods for a single subscription_id are mutually exclusive), use this
argument to indicate which column to partition by. `default=none`
- `gaps` (optional): Whether there can be gaps are allowed between ranges.
`default='allowed', one_of=['not_allowed', 'allowed', 'required']`
- `zero_length_range_allowed` (optional): Whether ranges can start and end on the same date.
`default=False`
**Note:** Both `lower_bound_column` and `upper_bound_column` should be not null.
If this is not the case in your data source, consider passing a coalesce function
to the `lower_` and `upper_bound_column` arguments, like so:
```yaml
version: 2
models:
- name: subscriptions
tests:
- dbt_utils.mutually_exclusive_ranges:
lower_bound_column: coalesce(started_at, '1900-01-01')
upper_bound_column: coalesce(ended_at, '2099-12-31')
partition_by: customer_id
gaps: allowed
```
<details>
<summary>Additional `gaps` and `zero_length_range_allowed` examples</summary>
**Understanding the `gaps` argument:**
Here are a number of examples for each allowed `gaps` argument.
- `gaps: not_allowed`: The upper bound of one record must be the lower bound of
the next record.
| lower_bound | upper_bound |
|-------------|-------------|
| 0 | 1 |
| 1 | 2 |
| 2 | 3 |
- `gaps: allowed` (default): There may be a gap between the upper bound of one
record and the lower bound of the next record.
| lower_bound | upper_bound |
|-------------|-------------|
| 0 | 1 |
| 2 | 3 |
| 3 | 4 |
- `gaps: required`: There must be a gap between the upper bound of one record and
the lower bound of the next record (common for date ranges).
| lower_bound | upper_bound |
|-------------|-------------|
| 0 | 1 |
| 2 | 3 |
| 4 | 5 |
**Understanding the `zero_length_range_allowed` argument:**
Here are a number of examples for each allowed `zero_length_range_allowed` argument.
- `zero_length_range_allowed: false`: (default) The upper bound of each record must be greater than its lower bound.
| lower_bound | upper_bound |
|-------------|-------------|
| 0 | 1 |
| 1 | 2 |
| 2 | 3 |
- `zero_length_range_allowed: true`: The upper bound of each record can be greater than or equal to its lower bound.
| lower_bound | upper_bound |
|-------------|-------------|
| 0 | 1 |
| 2 | 2 |
| 3 | 4 |
</details>
#### sequential_values ([source](macros/generic_tests/sequential_values.sql))
This test confirms that a column contains sequential values. It can be used
for both numeric values, and datetime values, as follows:
```yml
version: 2
seeds:
- name: util_even_numbers
columns:
- name: i
tests:
- dbt_utils.sequential_values:
interval: 2
- name: util_hours
columns:
- name: date_hour
tests:
- dbt_utils.sequential_values:
interval: 1
datepart: 'hour'
```
**Args:**
- `interval` (default=1): The gap between two sequential values
- `datepart` (default=None): Used when the gaps are a unit of time. If omitted, the test will check for a numeric gap.
This test supports the `group_by_columns` parameter; see [Grouping in tests](#grouping-in-tests) for details.
#### unique_combination_of_columns ([source](macros/generic_tests/unique_combination_of_columns.sql))
Asserts that the combination of columns is unique. For example, the
combination of month and product is unique, however neither column is unique
in isolation.
We generally recommend testing this uniqueness condition by either:
- generating a [surrogate_key](#surrogate_key-source) for your model and testing
the uniqueness of said key, OR
- passing the `unique` test a concatenation of the columns (as discussed [here](https://docs.getdbt.com/docs/building-a-dbt-project/testing-and-documentation/testing/#testing-expressions)).
However, these approaches can become non-perfomant on large data sets, in which
case we recommend using this test instead.
**Usage:**
```yaml
- name: revenue_by_product_by_month
tests:
- dbt_utils.unique_combination_of_columns:
combination_of_columns:
- month
- product
```
An optional `quote_columns` argument (`default=false`) can also be used if a column name needs to be quoted.
```yaml
- name: revenue_by_product_by_month
tests:
- dbt_utils.unique_combination_of_columns:
combination_of_columns:
- month
- group
quote_columns: true
```
#### accepted_range ([source](macros/generic_tests/accepted_range.sql))
Asserts that a column's values fall inside an expected range. Any combination of `min_value` and `max_value` is allowed, and the range can be inclusive or exclusive. Provide a `where` argument to filter to specific records only.
In addition to comparisons to a scalar value, you can also compare to another column's values. Any data type that supports the `>` or `<` operators can be compared, so you could also run tests like checking that all order dates are in the past.
**Usage:**
```yaml
version: 2
models:
- name: model_name
columns:
- name: user_id
tests:
- dbt_utils.accepted_range:
min_value: 0
inclusive: false
- name: account_created_at
tests:
- dbt_utils.accepted_range:
max_value: "getdate()"
#inclusive is true by default
- name: num_returned_orders
tests:
- dbt_utils.accepted_range:
min_value: 0
max_value: "num_orders"
- name: num_web_sessions
tests:
- dbt_utils.accepted_range:
min_value: 0
inclusive: false
where: "num_orders > 0"
```
----
#### Grouping in tests
Certain tests support the optional `group_by_columns` argument to provide more granularity in performing tests. This can be useful when:
- Some data checks can only be expressed within a group (e.g. ID values should be unique within a group but can be repeated between groups)
- Some data checks are more precise when done by group (e.g. not only should table rowcounts be equal but the counts within each group should be equal)
This feature is currently available for the following tests:
- equal_rowcount()
- fewer_rows_than()
- recency()
- at_least_one()
- not_constant()
- sequential_values()
- non_null_proportion()
To use this feature, the names of grouping variables can be passed as a list. For example, to test for at least one valid value by group, the `group_by_columns` argument could be used as follows:
```
- name: data_test_at_least_one
columns:
- name: field
tests:
- dbt_utils.at_least_one:
group_by_columns: ['customer_segment']
```
## Macros
### Introspective macros
These macros run a query and return the results of the query as objects. They are typically abstractions over the [statement blocks](https://docs.getdbt.com/reference/dbt-jinja-functions/statement-blocks) in dbt.
#### get_column_values ([source](macros/sql/get_column_values.sql))
This macro returns the unique values for a column in a given [relation](https://docs.getdbt.com/docs/writing-code-in-dbt/class-reference/#relation) as an array.
**Args:**
- `table` (required): a [Relation](https://docs.getdbt.com/reference/dbt-classes#relation) (a `ref` or `source`) that contains the list of columns you wish to select from
- `column` (required): The name of the column you wish to find the column values of
- `where` (optional, default=`none`): A where clause to filter the column values by.
- `order_by` (optional, default=`'count(*) desc'`): How the results should be ordered. The default is to order by `count(*) desc`, i.e. decreasing frequency. Setting this as `'my_column'` will sort alphabetically, while `'min(created_at)'` will sort by when thevalue was first observed.
- `max_records` (optional, default=`none`): The maximum number of column values you want to return
- `default` (optional, default=`[]`): The results this macro should return if the relation has not yet been created (and therefore has no column values).
**Usage:**
```sql
-- Returns a list of the payment_methods in the stg_payments model_
{% set payment_methods = dbt_utils.get_column_values(table=ref('stg_payments'), column='payment_method') %}
{% for payment_method in payment_methods %}
...
{% endfor %}
...
```
```sql
-- Returns the list sorted alphabetically
{% set payment_methods = dbt_utils.get_column_values(
table=ref('stg_payments'),
where="payment_method = 'bank_transfer'",
column='payment_method',
order_by='payment_method'
) %}
```
```sql
-- Returns the list sorted my most recently observed
{% set payment_methods = dbt_utils.get_column_values(
table=ref('stg_payments'),
column='payment_method',
order_by='max(created_at) desc',
max_records=50,
default=['bank_transfer', 'coupon', 'credit_card']
%}
...
```
#### get_filtered_columns_in_relation ([source](macros/sql/get_filtered_columns_in_relation.sql))
This macro returns an iterable Jinja list of columns for a given [relation](https://docs.getdbt.com/docs/writing-code-in-dbt/class-reference/#relation), (i.e. not from a CTE)
- optionally exclude columns
- the input values are not case-sensitive (input uppercase or lowercase and it will work!)
> Note: The native [`adapter.get_columns_in_relation` macro](https://docs.getdbt.com/reference/dbt-jinja-functions/adapter#get_columns_in_relation) allows you
to pull column names in a non-filtered fashion, also bringing along with it other (potentially unwanted) information, such as dtype, char_size, numeric_precision, etc.
**Args:**
- `from` (required): a [Relation](https://docs.getdbt.com/reference/dbt-classes#relation) (a `ref` or `source`) that contains the list of columns you wish to select from
- `except` (optional, default=`[]`): The name of the columns you wish to exclude. (case-insensitive)
**Usage:**
```sql
-- Returns a list of the columns from a relation, so you can then iterate in a for loop
{% set column_names = dbt_utils.get_filtered_columns_in_relation(from=ref('your_model'), except=["field_1", "field_2"]) %}
...
{% for column_name in column_names %}
max({{ column_name }}) ... as max_'{{ column_name }}',
{% endfor %}
...
```
#### get_relations_by_pattern ([source](macros/sql/get_relations_by_pattern.sql))
Returns a list of [Relations](https://docs.getdbt.com/docs/writing-code-in-dbt/class-reference/#relation)
that match a given schema- or table-name pattern.
This macro is particularly handy when paired with `union_relations`.
**Usage:**
```
-- Returns a list of relations that match schema_pattern%.table
{% set relations = dbt_utils.get_relations_by_pattern('schema_pattern%', 'table_pattern') %}
-- Returns a list of relations that match schema_pattern.table_pattern%
{% set relations = dbt_utils.get_relations_by_pattern('schema_pattern', 'table_pattern%') %}
-- Returns a list of relations as above, excluding any that end in `deprecated`
{% set relations = dbt_utils.get_relations_by_pattern('schema_pattern', 'table_pattern%', '%deprecated') %}
-- Example using the union_relations macro
{% set event_relations = dbt_utils.get_relations_by_pattern('venue%', 'clicks') %}
{{ dbt_utils.union_relations(relations = event_relations) }}
```
**Args:**
- `schema_pattern` (required): The schema pattern to inspect for relations.
- `table_pattern` (required): The name of the table/view (case insensitive).
- `exclude` (optional): Exclude any relations that match this table pattern.
- `database` (optional, default = `target.database`): The database to inspect
for relations.
**Examples:**
Generate drop statements for all Relations that match a naming pattern:
```sql
{% set relations_to_drop = dbt_utils.get_relations_by_pattern(
schema_pattern='public',
table_pattern='dbt\_%'
) %}
{% set sql_to_execute = [] %}
{{ log('Statements to run:', info=True) }}
{% for relation in relations_to_drop %}
{% set drop_command -%}
-- drop {{ relation.type }} {{ relation }} cascade;
{%- endset %}
{% do log(drop_command, info=True) %}
{% do sql_to_execute.append(drop_command) %}
{% endfor %}
```
#### get_relations_by_prefix ([source](macros/sql/get_relations_by_prefix.sql))
> This macro will soon be deprecated in favor of the more flexible `get_relations_by_pattern` macro (above)
Returns a list of [Relations](https://docs.getdbt.com/docs/writing-code-in-dbt/class-reference/#relation)
that match a given prefix, with an optional exclusion pattern. It's particularly
handy paired with `union_relations`.
**Usage:**
```
-- Returns a list of relations that match schema.prefix%
{% set relations = dbt_utils.get_relations_by_prefix('my_schema', 'my_prefix') %}
-- Returns a list of relations as above, excluding any that end in `deprecated`
{% set relations = dbt_utils.get_relations_by_prefix('my_schema', 'my_prefix', '%deprecated') %}
-- Example using the union_relations macro
{% set event_relations = dbt_utils.get_relations_by_prefix('events', 'event_') %}
{{ dbt_utils.union_relations(relations = event_relations) }}
```
**Args:**
- `schema` (required): The schema to inspect for relations.
- `prefix` (required): The prefix of the table/view (case insensitive)
- `exclude` (optional): Exclude any relations that match this pattern.
- `database` (optional, default = `target.database`): The database to inspect
for relations.
#### get_query_results_as_dict ([source](macros/sql/get_query_results_as_dict.sql))
This macro returns a dictionary from a sql query, so that you don't need to interact with the Agate library to operate on the result
**Usage:**
```
{% set sql_statement %}
select city, state from {{ ref('users') }}
{% endset %}
{%- set places = dbt_utils.get_query_results_as_dict(sql_statement) -%}
select
{% for city in places['CITY'] | unique -%}
sum(case when city = '{{ city }}' then 1 else 0 end) as users_in_{{ dbt_utils.slugify(city) }},
{% endfor %}
{% for state in places['STATE'] | unique -%}
sum(case when state = '{{ state }}' then 1 else 0 end) as users_in_{{ state }},
{% endfor %}
count(*) as total_total
from {{ ref('users') }}
```
### SQL generators
These macros generate SQL (either a complete query, or a part of a query). They often implement patterns that should be easy in SQL, but for some reason are much harder than they need to be.
#### date_spine ([source](macros/sql/date_spine.sql))
This macro returns the sql required to build a date spine. The spine will include the `start_date` (if it is aligned to the `datepart`), but it will not include the `end_date`.
**Usage:**
```
{{ dbt_utils.date_spine(
datepart="day",
start_date="cast('2019-01-01' as date)",
end_date="cast('2020-01-01' as date)"
)
}}
```
#### deduplicate ([source](macros/sql/deduplicate.sql))
This macro returns the sql required to remove duplicate rows from a model, source, or CTE.
**Args:**
- `relation` (required): a [Relation](https://docs.getdbt.com/reference/dbt-classes#relation) (a `ref` or `source`) or string which identifies the model to deduplicate.
- `partition_by` (required): column names (or expressions) to use to identify a set/window of rows out of which to select one as the deduplicated row.
- `order_by` (required): column names (or expressions) that determine the priority order of which row should be chosen if there are duplicates (comma-separated string). *NB.* if this order by clause results in ties then which row is returned may be nondeterministic across runs.
**Usage:**
```
{{ dbt_utils.deduplicate(
relation=source('my_source', 'my_table'),
partition_by='user_id, cast(timestamp as day)',
order_by="timestamp desc",
)
}}
```
```
{{ dbt_utils.deduplicate(
relation=ref('my_model'),
partition_by='user_id',
order_by='effective_date desc, effective_sequence desc',
)
}}
```
```
with my_cte as (
select *
from {{ source('my_source', 'my_table') }}
where user_id = 1
)
{{ dbt_utils.deduplicate(
relation='my_cte',
partition_by='user_id, cast(timestamp as day)',
order_by='timestamp desc',
)
}}
```
#### haversine_distance ([source](macros/sql/haversine_distance.sql))
This macro calculates the [haversine distance](http://daynebatten.com/2015/09/latitude-longitude-distance-sql/) between a pair of x/y coordinates.
Optionally takes a `unit` string argument ('km' or 'mi') which defaults to miles (imperial system).
**Usage:**
```
{{ dbt_utils.haversine_distance(48.864716, 2.349014, 52.379189, 4.899431) }}
{{ dbt_utils.haversine_distance(
lat1=48.864716,
lon1=2.349014,
lat2=52.379189,
lon2=4.899431,
unit='km'
) }}
```
**Args:**
- `lat1` (required): latitude of first location
- `lon1` (required): longitude of first location
- `lat2` (required): latitude of second location
- `lon3` (required): longitude of second location
- `unit` (optional, default=`'mi'`): one of `mi` (miles) or `km` (kilometers)
#### group_by ([source](macros/sql/groupby.sql))
This macro build a group by statement for fields 1...N
**Usage:**
```
{{ dbt_utils.group_by(n=3) }}
```
Would compile to:
```sql
group by 1,2,3
```
#### star ([source](macros/sql/star.sql))
This macro generates a comma-separated list of all fields that exist in the `from` relation, excluding any fields
listed in the `except` argument. The construction is identical to `select * from {{ref('my_model')}}`, replacing star (`*`) with
the star macro.
This macro also has an optional `relation_alias` argument that will prefix all generated fields with an alias (`relation_alias`.`field_name`).
The macro also has optional `prefix` and `suffix` arguments. When one or both are provided, they will be concatenated onto each field's alias
in the output (`prefix` ~ `field_name` ~ `suffix`). NB: This prevents the output from being used in any context other than a select statement.
**Args:**
- `from` (required): a [Relation](https://docs.getdbt.com/reference/dbt-classes#relation) (a `ref` or `source`) that contains the list of columns you wish to select from
- `except` (optional, default=`[]`): The name of the columns you wish to exclude. (case-insensitive)
- `relation_alias` (optional, default=`''`): will prefix all generated fields with an alias (`relation_alias`.`field_name`).
- `prefix` (optional, default=`''`): will prefix the output `field_name` (`field_name as prefix_field_name`).
- `suffix` (optional, default=`''`): will suffix the output `field_name` (`field_name as field_name_suffix`).
**Usage:**
```sql
select
{{ dbt_utils.star(ref('my_model')) }}
from {{ ref('my_model') }}
```
```sql
select
{{ dbt_utils.star(from=ref('my_model'), except=["exclude_field_1", "exclude_field_2"]) }}
from {{ ref('my_model') }}
```
```sql
select
{{ dbt_utils.star(from=ref('my_model'), except=["exclude_field_1", "exclude_field_2"], prefix="max_") }}
from {{ ref('my_model') }}
```
#### union_relations ([source](macros/sql/union.sql))
This macro unions together an array of [Relations](https://docs.getdbt.com/docs/writing-code-in-dbt/class-reference/#relation),
even when columns have differing orders in each Relation, and/or some columns are
missing from some relations. Any columns exclusive to a subset of these
relations will be filled with `null` where not present. A new column
(`_dbt_source_relation`) is also added to indicate the source for each record.
**Usage:**
```
{{ dbt_utils.union_relations(
relations=[ref('my_model'), source('my_source', 'my_table')],
exclude=["_loaded_at"]
) }}
```
**Args:**
- `relations` (required): An array of [Relations](https://docs.getdbt.com/docs/writing-code-in-dbt/class-reference/#relation).
- `exclude` (optional): A list of column names that should be excluded from
the final query.
- `include` (optional): A list of column names that should be included in the
final query. Note the `include` and `exclude` arguments are mutually exclusive.
- `column_override` (optional): A dictionary of explicit column type overrides,
e.g. `{"some_field": "varchar(100)"}`.``
- `source_column_name` (optional, `default="_dbt_source_relation"`): The name of
the column that records the source of this row. Pass `None` to omit this column from the results.
- `where` (optional): Filter conditions to include in the `where` clause.
#### generate_series ([source](macros/sql/generate_series.sql))
This macro implements a cross-database mechanism to generate an arbitrarily long list of numbers. Specify the maximum number you'd like in your list and it will create a 1-indexed SQL result set.