Skip to content

Commit 6cc42e9

Browse files
committed
fix p4 view
1 parent e707a66 commit 6cc42e9

10 files changed

+237
-22
lines changed

app/src/app/utils/api/apiHandlers.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ export const getP1TotPopSummaryStats: (
246246
) => Promise<SummaryStatsResult<P1TotPopSummaryStats[]>> = async mapDocument => {
247247
if (mapDocument) {
248248
return await axios
249-
.get<SummaryStatsResult<P1TotPopSummaryStats[]>>(`${process.env.NEXT_PUBLIC_API_URL}/api/districtrmap/summary_stats/P1TOTPOP/${mapDocument.parent_layer}`)
249+
.get<SummaryStatsResult<P1TotPopSummaryStats[]>>(`${process.env.NEXT_PUBLIC_API_URL}/api/districtrmap/summary_stats/P1/${mapDocument.parent_layer}`)
250250
.then(res => res.data)
251251
} else {
252252
throw new Error('No document provided');

backend/app/alembic/versions/f86991e63a62_summary_stat_udfs.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,19 @@
2121

2222

2323
def upgrade() -> None:
24-
for udf in ["summary_stats_p1.sql", "summary_stats_pop_totals.sql"]:
24+
for udf in [
25+
"summary_stats_p1.sql",
26+
"summary_stats_p1_totals.sql",
27+
"summary_stats_p4.sql",
28+
"summary_stats_p4_totals.sql",
29+
]:
2530
with Path(SQL_DIR, udf).open() as f:
2631
sql = f.read()
2732
op.execute(sql)
2833

2934

3035
def downgrade() -> None:
3136
op.execute("DROP FUNCTION IF EXISTS get_summary_stats_p1")
32-
op.execute("DROP FUNCTION IF EXISTS get_summary_stats_pop_totals")
37+
op.execute("DROP FUNCTION IF EXISTS get_summary_p1_totals")
38+
op.execute("DROP FUNCTION IF EXISTS get_summary_stats_p4")
39+
op.execute("DROP FUNCTION IF EXISTS get_summary_p4_totals")

backend/app/main.py

+12-8
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@
2929
SummaryStatisticType,
3030
SummaryStatsP1,
3131
PopulationStatsP1,
32-
GerryDbSummaryStatisticType,
32+
SummaryStatsP4,
33+
PopulationStatsP4,
3334
)
3435

3536
if settings.ENVIRONMENT == "production":
@@ -327,9 +328,11 @@ async def get_summary_stat(
327328
),
328329
SummaryStatsP1,
329330
),
330-
"P1TOTPOP": {
331-
text("SELECT * from get_summary_stats_pop_totals(:document_id)"),
332-
PopulationStatsP1,
331+
"P4": {
332+
text(
333+
"SELECT * from get_summary_stats_p4(:document_id) WHERE zone is not null"
334+
),
335+
SummaryStatsP4,
333336
},
334337
}[summary_stat]
335338
except KeyError:
@@ -359,7 +362,7 @@ async def get_gerrydb_summary_stat(
359362
summary_stat: str, gerrydb_table: str, session: Session = Depends(get_session)
360363
):
361364
try:
362-
_summary_stat = GerryDbSummaryStatisticType[summary_stat]
365+
_summary_stat = SummaryStatisticType[summary_stat]
363366
except ValueError:
364367
raise HTTPException(
365368
status_code=status.HTTP_400_BAD_REQUEST,
@@ -368,7 +371,8 @@ async def get_gerrydb_summary_stat(
368371

369372
try:
370373
summary_stat_udf, SummaryStatsModel = {
371-
"P1TOTPOP": ("get_summary_stats_pop_totals", PopulationStatsP1),
374+
"P1": ("get_summary_p1_totals", PopulationStatsP1),
375+
"P4": ("get_summary_p4_totals", PopulationStatsP4),
372376
}[summary_stat]
373377
except KeyError:
374378
raise HTTPException(
@@ -383,10 +387,10 @@ async def get_gerrydb_summary_stat(
383387
bindparam(key="gerrydb_table", type_=String),
384388
)
385389
try:
386-
results = session.execute(stmt, {"gerrydb_table": gerrydb_table}).fetchall()
390+
(row,) = session.execute(stmt, {"gerrydb_table": gerrydb_table}).one()
387391
return {
388392
"summary_stat": _summary_stat.value,
389-
"results": [SummaryStatsModel.from_orm(row) for row in results],
393+
"results": [SummaryStatsModel.from_orm(row)],
390394
}
391395
except ProgrammingError as e:
392396
logger.error(e)

backend/app/models.py

+15-4
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,6 @@ class SummaryStatisticType(Enum):
5353
P4 = "Hispanic or Latino, and Not Hispanic or Latino by Race Voting Age Population"
5454

5555

56-
class GerryDbSummaryStatisticType(Enum):
57-
P1TOTPOP = "Total Population by Race"
58-
59-
6056
class DistrictrMap(TimeStampMixin, SQLModel, table=True):
6157
uuid: str = Field(sa_column=Column(UUIDType, unique=True, primary_key=True))
6258
name: str = Field(nullable=False)
@@ -212,3 +208,18 @@ class PopulationStatsP1(BaseModel):
212208

213209
class SummaryStatsP1(PopulationStatsP1):
214210
zone: int
211+
212+
213+
class PopulationStatsP4(BaseModel):
214+
model_config = ConfigDict(from_attributes=True)
215+
hispanic_vap: int
216+
non_hispanic_asian_vap: int
217+
non_hispanic_amin_vap: int
218+
non_hispanic_nhpi_vap: int
219+
non_hispanic_black_vap: int
220+
non_hispanic_white_vap: int
221+
non_hispanic_other_vap: int
222+
223+
224+
class SummaryStatsP4(PopulationStatsP4):
225+
zone: int

backend/app/sql/available_summary_stat_udf.sql

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ BEGIN
4848
FROM INFORMATION_SCHEMA.COLUMNS
4949
WHERE table_name = gerrydb_table_name
5050
AND table_schema = 'gerrydb'
51-
AND column_name IN ('hispanic_pop',
51+
AND column_name IN ('hispanic_vap',
5252
'non_hispanic_asian_vap',
5353
'non_hispanic_amin_vap',
5454
'non_hispanic_nhpi_vap',

backend/app/sql/summary_stats_pop_totals.sql renamed to backend/app/sql/summary_stats_p1_totals.sql

+5-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
DROP FUNCTION IF EXISTS get_summary_stats_pop_totals;
2-
CREATE OR REPLACE FUNCTION get_summary_stats_pop_totals(gerrydb_table TEXT)
1+
CREATE OR REPLACE FUNCTION get_summary_p1_totals(gerrydb_table TEXT)
32
RETURNS TABLE (
43
other_pop BIGINT,
54
asian_pop BIGINT,
@@ -15,9 +14,9 @@ DECLARE
1514
BEGIN
1615
-- Check if the table exists
1716
SELECT EXISTS (
18-
SELECT 1
19-
FROM information_schema.tables
20-
WHERE table_schema = 'gerrydb'
17+
SELECT 1
18+
FROM information_schema.tables
19+
WHERE table_schema = 'gerrydb'
2120
AND table_name = $1
2221
) INTO table_exists;
2322

@@ -37,4 +36,4 @@ BEGIN
3736
', $1);
3837
RETURN QUERY EXECUTE sql_query;
3938
END;
40-
$$ LANGUAGE plpgsql;
39+
$$ LANGUAGE plpgsql;

backend/app/sql/summary_stats_p4.sql

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
CREATE OR REPLACE FUNCTION get_summary_stats_p4(document_id UUID)
2+
RETURNS TABLE (
3+
zone TEXT,
4+
hispanic_vap BIGINT,
5+
non_hispanic_asian_vap BIGINT,
6+
non_hispanic_amin_vap BIGINT,
7+
non_hispanic_nhpi_vap BIGINT,
8+
non_hispanic_black_vap BIGINT,
9+
non_hispanic_white_vap BIGINT,
10+
non_hispanic_other_vap BIGINT
11+
) AS $$
12+
DECLARE
13+
doc_districtrmap RECORD;
14+
sql_query TEXT;
15+
BEGIN
16+
SELECT districtrmap.* INTO doc_districtrmap
17+
FROM document.document
18+
LEFT JOIN districtrmap
19+
ON document.gerrydb_table = districtrmap.gerrydb_table_name
20+
WHERE document.document_id = $1;
21+
22+
IF doc_districtrmap.gerrydb_table_name IS NULL THEN
23+
RAISE EXCEPTION 'Table name not found for document_id: %', $1;
24+
END IF;
25+
26+
sql_query := format('
27+
SELECT
28+
assignments.zone::TEXT AS zone,
29+
SUM(COALESCE(blocks.hispanic_vap, 0))::BIGINT AS hispanic_vap,
30+
SUM(COALESCE(blocks.non_hispanic_asian_vap, 0))::BIGINT AS non_hispanic_asian_vap,
31+
SUM(COALESCE(blocks.non_hispanic_amin_vap, 0))::BIGINT AS non_hispanic_amin_vap,
32+
SUM(COALESCE(blocks.non_hispanic_nhpi_vap, 0))::BIGINT AS non_hispanic_nhpi_vap,
33+
SUM(COALESCE(blocks.non_hispanic_black_vap, 0))::BIGINT AS non_hispanic_black_vap,
34+
SUM(COALESCE(blocks.non_hispanic_white_vap, 0))::BIGINT AS non_hispanic_white_vap,
35+
SUM(COALESCE(blocks.non_hispanic_other_vap, 0))::BIGINT AS non_hispanic_other_vap
36+
FROM document.assignments
37+
LEFT JOIN gerrydb.%I blocks
38+
ON blocks.path = assignments.geo_id
39+
WHERE assignments.document_id = $1
40+
GROUP BY assignments.zone
41+
', doc_districtrmap.gerrydb_table_name);
42+
RETURN QUERY EXECUTE sql_query USING $1;
43+
END;
44+
$$ LANGUAGE plpgsql;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
CREATE OR REPLACE FUNCTION get_summary_p4_totals(gerrydb_table TEXT)
2+
RETURNS TABLE (
3+
hispanic_vap BIGINT,
4+
non_hispanic_asian_vap BIGINT,
5+
non_hispanic_amin_vap BIGINT,
6+
non_hispanic_nhpi_vap BIGINT,
7+
non_hispanic_black_vap BIGINT,
8+
non_hispanic_white_vap BIGINT,
9+
non_hispanic_other_vap BIGINT
10+
) AS $$
11+
DECLARE
12+
table_exists BOOLEAN;
13+
sql_query TEXT;
14+
15+
BEGIN
16+
-- Check if the table exists
17+
SELECT EXISTS (
18+
SELECT 1
19+
FROM information_schema.tables
20+
WHERE table_schema = 'gerrydb'
21+
AND table_name = $1
22+
) INTO table_exists;
23+
24+
IF NOT table_exists THEN
25+
RAISE EXCEPTION 'Table % does not exist in gerrydb schema', $1;
26+
END IF;
27+
28+
sql_query := format('
29+
SELECT
30+
SUM(COALESCE(blocks.hispanic_vap, 0))::BIGINT AS hispanic_vap,
31+
SUM(COALESCE(blocks.non_hispanic_asian_vap, 0))::BIGINT AS non_hispanic_asian_vap,
32+
SUM(COALESCE(blocks.non_hispanic_amin_vap, 0))::BIGINT AS non_hispanic_amin_vap,
33+
SUM(COALESCE(blocks.non_hispanic_nhpi_vap, 0))::BIGINT AS non_hispanic_nhpi_vap,
34+
SUM(COALESCE(blocks.non_hispanic_black_vap, 0))::BIGINT AS non_hispanic_black_vap,
35+
SUM(COALESCE(blocks.non_hispanic_white_vap, 0))::BIGINT AS non_hispanic_white_vap,
36+
SUM(COALESCE(blocks.non_hispanic_other_vap, 0))::BIGINT AS non_hispanic_other_vap
37+
FROM gerrydb.%I
38+
', $1);
39+
RETURN QUERY EXECUTE sql_query;
40+
END;
41+
$$ LANGUAGE plpgsql;

0 commit comments

Comments
 (0)