|
| 1 | +module DrRai |
| 2 | + class BpFudgingQueryFactory < QueryFactory |
| 3 | + INSERTER_SQL = "insert into #{DrRai::Data::BpFudging.table_name} (state, district, slug, quarter, numerator, denominator, ratio)".freeze |
| 4 | + |
| 5 | + CONFLICT_HANDLER_SQL = <<~SQL |
| 6 | + on conflict (state, district, slug, quarter) do |
| 7 | + update set |
| 8 | + numerator = excluded.numerator, |
| 9 | + denominator = excluded.denominator, |
| 10 | + ratio = excluded.ratio, |
| 11 | + updated_at = now(); -- ...for good bookkeeping |
| 12 | + SQL |
| 13 | + |
| 14 | + def inserter |
| 15 | + base_query(INSERTER_SQL, "") { |enhancement| enhancement } |
| 16 | + end |
| 17 | + |
| 18 | + def updater |
| 19 | + base_query(INSERTER_SQL, CONFLICT_HANDLER_SQL) { |enhancement| enhancement } |
| 20 | + end |
| 21 | + |
| 22 | + private |
| 23 | + |
| 24 | + # This query is a modified version of what we use in Metabase; linked in Quick Links as well. |
| 25 | + # The modifications are thus |
| 26 | + # 1. Wide to Tall query on Quarter |
| 27 | + # 2. Added facility name to the mix, as "slug" |
| 28 | + # 3. Remove the filters on state and org |
| 29 | + def base_query inserter, conflict_handler |
| 30 | + <<~SQL |
| 31 | + #{yield inserter} |
| 32 | + ( |
| 33 | + select |
| 34 | + reporting_facilities.state_name as "state", |
| 35 | + reporting_facilities.district_name "district", |
| 36 | + reporting_facilities.facility_name as "slug", |
| 37 | + to_char(bp.created_at, '"Q"q-yyyy') as "quarter", |
| 38 | + count(*) filter (where bp.systolic between 130 and 139) as "numerator", |
| 39 | + count(*) filter (where bp.systolic between 140 and 149) as "denominator", |
| 40 | + count(*) filter (where bp.systolic between 130 and 139) * 1.0 / |
| 41 | + nullif(count(*) filter (where bp.systolic between 140 and 149), 0) as "ratio" |
| 42 | + from blood_pressures bp |
| 43 | + join reporting_facilities on bp.facility_id = reporting_facilities.facility_id |
| 44 | + where 1 = 1 |
| 45 | + and bp.created_at >= date_trunc('quarter', current_date - interval '12 months') |
| 46 | + group by |
| 47 | + 1, 2, 3, 4 |
| 48 | + ) |
| 49 | + #{yield conflict_handler}; |
| 50 | + SQL |
| 51 | + end |
| 52 | + end |
| 53 | +end |
0 commit comments