Skip to content

Refactor: replace Haversine with native spatial query for nearby dive sites#179

Merged
kargig merged 1 commit intomainfrom
feature/refactor-nearby-dive-sites-spatial
Mar 25, 2026
Merged

Refactor: replace Haversine with native spatial query for nearby dive sites#179
kargig merged 1 commit intomainfrom
feature/refactor-nearby-dive-sites-spatial

Conversation

@kargig
Copy link
Copy Markdown
Owner

@kargig kargig commented Mar 25, 2026

The GET /api/v1/dive-sites/{id}/nearby endpoint previously calculated distances using the Haversine formula on standard float columns, forcing a full table scan and dynamic calculation for every query.

This commit resolves the performance bottleneck by:

  • Adding a location column of type POINT SRID 4326 to dive_sites
  • Applying a SPATIAL INDEX to the location column
  • Adding SQLAlchemy event listeners to sync latitude and longitude into the new location POINT on insert/update
  • Refactoring the /nearby endpoint to execute a highly optimized raw MySQL ST_Distance_Sphere query
  • Generating Alembic migration 0073 to backfill existing data
  • Adding @pytest.mark.spatial to test coverage

The frontend API contract and UI remain completely unaffected, but map and detail views rendering nearby sites will now scale efficiently regardless of database size.

… sites

The `GET /api/v1/dive-sites/{id}/nearby` endpoint previously calculated
distances using the Haversine formula on standard float columns, forcing
a full table scan and dynamic calculation for every query.

This commit resolves the performance bottleneck by:
- Adding a `location` column of type `POINT SRID 4326` to `dive_sites`
- Applying a `SPATIAL INDEX` to the `location` column
- Adding SQLAlchemy event listeners to sync `latitude` and `longitude`
  into the new `location` POINT on insert/update
- Refactoring the `/nearby` endpoint to execute a highly optimized
  raw MySQL `ST_Distance_Sphere` query
- Generating Alembic migration 0073 to backfill existing data
- Adding `@pytest.mark.spatial` to test coverage

The frontend API contract and UI remain completely unaffected,
but map and detail views rendering nearby sites will now
scale efficiently regardless of database size.
@kargig kargig merged commit 6c23bf8 into main Mar 25, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant