Skip to content

Commit

Permalink
update get_percentage_water_stress_area
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeh committed Sep 5, 2023
1 parent dee0774 commit c1461c8
Showing 1 changed file with 38 additions and 32 deletions.
70 changes: 38 additions & 32 deletions api/src/migrations/1692854789441-UpdateImpactStoredFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,41 +125,47 @@ export class UpdateImpactStoredFunctions1692854789441
await queryRunner.query(`
DROP FUNCTION IF EXISTS get_percentage_water_stress_area;
CREATE OR REPLACE FUNCTION get_percentage_water_stress_area(
geo_region_id uuid,
name_code text
CREATE OR REPLACE FUNCTION get_percentage_water_stress_area_update(
geo_region_id uuid,
nameCode text
)
RETURNS float AS
RETURNS double precision
AS
$$
DECLARE
aqueduct_h3_table_name varchar;
aqueduct_h3_column_name varchar;
h3_resolution integer;
percentage float;
BEGIN
-- Get h3data table name, column
SELECT * INTO aqueduct_h3_table_name, aqueduct_h3_column_name, h3_resolution
FROM get_h3_table_column_for_indicators_by_name_code(name_code);
DECLARE
aqueduct_h3_table_name varchar;
aqueduct_h3_column_name varchar;
h3_resolution integer;
percentage double precision;
BEGIN
-- Get h3data table name, column
SELECT * INTO aqueduct_h3_table_name, aqueduct_h3_column_name, h3_resolution
FROM get_h3_table_column_for_indicators(nameCode);
EXECUTE format(
'SELECT
ROUND(
CAST(reduced.ws_area AS NUMERIC) /
CAST(reduced.g_area AS NUMERIC),
2
) AS percentage
FROM
(SELECT
sum(case when aqueduct.%I > 3 then 1 else 0 end) ws_area,
count(aqueduct.%I) g_area
FROM get_h3_uncompact_geo_region($1, $2) geo_region
INNER JOIN %I aqueduct ON aqueduct.h3index = geo_region.h3index) reduced
WHERE reduced.g_area > 0;',
aqueduct_h3_column_name,
aqueduct_h3_column_name,
aqueduct_h3_table_name
)
USING geo_region_id, h3_resolution
INTO percentage;
EXECUTE format(
'SELECT reduced.ws_area/ reduced.g_area as percentage
FROM
(SELECT
sum(case when aqueduct.%I > 3 then 1 else 0 end) ws_area, count(aqueduct.%I) g_area
FROM get_h3_uncompact_geo_region($1, $2) geo_region
INNER JOIN %I aqueduct ON aqueduct.h3index = geo_region.h3index) reduced
WHERE reduced.g_area > 0;',
aqueduct_h3_column_name,
aqueduct_h3_column_name,
aqueduct_h3_table_name
)
USING geo_region_id, h3_resolution
INTO percentage;
RETURN percentage;
END;
RETURN percentage;
END;
$$
LANGUAGE plpgsql;`);

Expand Down

0 comments on commit c1461c8

Please sign in to comment.