Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test for 'a has fewer rows than b' #221

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,19 @@ models:

```

#### fewer_rows_than ([source](macros/schema_tests/fewer_rows_than.sql))
This schema test asserts that this model has fewer rows than the referenced model.

Usage:
```yaml
version: 2

models:
- name: model_name
tests:
- dbt_utils.fewer_rows_than:
compare_model: ref('other_table_name')

#### equality ([source](macros/schema_tests/equality.sql))
This schema test asserts the equality of two relations. Optionally specify a subset of columns to compare.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
field
1
2
3
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
field
1
2
3
4
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
with data as (

select * from {{ ref('data_test_fewer_rows_than_table_1') }}

)

select
field
from data
39 changes: 39 additions & 0 deletions macros/schema_tests/fewer_rows_than.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{% macro test_fewer_rows_than(model) %}

{% set compare_model = kwargs.get('compare_model', kwargs.get('arg')) %}

with a as (

select count(*) as count_ourmodel from {{ model }}

),
b as (

select count(*) as count_comparisonmodel from {{ compare_model }}

),
counts as (

select
(select count_ourmodel from a) as count_model_with_fewer_rows,
(select count_comparisonmodel from b) as count_model_with_more_rows

),
final as (

select
case
-- fail the test if we have more rows than the reference model and return the row count delta
when count_model_with_fewer_rows > count_model_with_more_rows then (count_model_with_fewer_rows - count_model_with_more_rows)
-- fail the test if they are the same number
when count_model = count_comparison then 1
-- pass the test if the delta is positive (i.e. return the number 0)
else 0
end as row_count_delta
from counts

)

select row_count_delta from final

{% endmacro %}