diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a9a3d82..d9c7d0fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - feat(nix): use datasources.settings.datasources to allow merging Grafana sources from multiple modules (#4870 - @JakobLichterfeld) - fix(nix): correctly set default Grafana dashboard path (#4870 - @JakobLichterfeld) - feat(nix): allow disabling default Grafana dashboard with setDefaultDashboard option (#4870 - @JakobLichterfeld) +- fix: set descent and ascent to 0 when out of bounds (> 32767 meters) to ensure migration succeeds (#4882 - @swiffer) #### Build, CI, internal diff --git a/lib/teslamate/log.ex b/lib/teslamate/log.ex index 02392f51..a7609f3c 100644 --- a/lib/teslamate/log.ex +++ b/lib/teslamate/log.ex @@ -291,6 +291,8 @@ defmodule TeslaMate.Log do not is_nil(p.odometer), limit: 1 + # If the sum of elevation gains exceeds the max value of a smallint (32767), set it to 0. + # If the sum of elevation losses exceeds the max value of a smallint (32767), set it to 0. elevation_data = from p1 in subquery( from p in Position, @@ -301,20 +303,16 @@ defmodule TeslaMate.Log do ), select: %{ elevation_gains: - sum( - fragment( - "CASE WHEN ? > 0 THEN ? ELSE 0 END", - p1.elevation_diff, - p1.elevation_diff - ) + fragment( + "COALESCE(NULLIF(LEAST(SUM(CASE WHEN ? > 0 THEN ? ELSE 0 END), 32768), 32768), 0)", + p1.elevation_diff, + p1.elevation_diff ), elevation_losses: - sum( - fragment( - "CASE WHEN ? < 0 THEN ABS(?) ELSE 0 END", - p1.elevation_diff, - p1.elevation_diff - ) + fragment( + "COALESCE(NULLIF(LEAST(SUM(CASE WHEN ? < 0 THEN ABS(?) ELSE 0 END), 32768), 32768), 0)", + p1.elevation_diff, + p1.elevation_diff ) } diff --git a/priv/repo/migrations/20250613133700_add_and_calculate_elevation_changes.exs b/priv/repo/migrations/20250613133700_add_and_calculate_elevation_changes.exs index 334d1a78..cebf1f0e 100644 --- a/priv/repo/migrations/20250613133700_add_and_calculate_elevation_changes.exs +++ b/priv/repo/migrations/20250613133700_add_and_calculate_elevation_changes.exs @@ -7,12 +7,15 @@ defmodule TeslaMate.Repo.Migrations.AddAndCalculateElevationChanges do add :descent, :smallint end + # If the sum of elevation gains exceeds the max value of a smallint (32767), set it to 0. + # If the sum of elevation losses exceeds the max value of a smallint (32767), set it to 0. + execute """ WITH elevation_changes AS ( SELECT drive_id, - SUM(CASE WHEN elevation_diff > 0 THEN elevation_diff ELSE 0 END) as ascent, - SUM(CASE WHEN elevation_diff < 0 THEN ABS(elevation_diff) ELSE 0 END) as descent + COALESCE(NULLIF(LEAST(SUM(CASE WHEN elevation_diff > 0 THEN elevation_diff ELSE 0 END), 32768), 32768), 0) as ascent, + COALESCE(NULLIF(LEAST(SUM(CASE WHEN elevation_diff < 0 THEN ABS(elevation_diff) ELSE 0 END), 32768), 32768), 0) as descent FROM ( SELECT drive_id,