do you see here any issue with this procedure and how to call it
DELIMITER //
CREATE PROCEDURE generate_track_polygons()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE curr_id, seg_id INT DEFAULT 0;
DECLARE curr_lon, curr_lat, prev_lon, prev_lat DECIMAL(12,8);
DECLARE curr_course, prev_course DECIMAL(6,3);
DECLARE curr_time, start_time, end_time DATETIME(6);
DECLARE meters_per_degree DECIMAL(16,12) DEFAULT 111320.0 * COS(RADIANS(50.0)); -- For ~50°N latitude
code
-- Cursor for ordered high-precision points
DECLARE point_cur CURSOR FOR
SELECT
id, longitude, latitude, course, timestamp
FROM precise_track_points
ORDER BY timestamp;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- Temporary tables for processing
CREATE TEMPORARY TABLE IF NOT EXISTS temp_segments (
seg_id INT AUTO_INCREMENT PRIMARY KEY,
polygon GEOMETRY,
avg_course DECIMAL(6,3),
start_time DATETIME(6),
end_time DATETIME(6)
) ENGINE=Memory;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_final_polygons (
polygon GEOMETRY,
avg_course DECIMAL(6,3),
start_time DATETIME(6),
end_time DATETIME(6)
) ENGINE=Memory;
OPEN point_cur;
FETCH point_cur INTO curr_id, curr_lon, curr_lat, curr_course, curr_time;
SET prev_lon = curr_lon;
SET prev_lat = curr_lat;
SET prev_course = curr_course;
SET start_time = curr_time;
read_loop: LOOP
-- Calculate 2m offsets (precise at ~50°N latitude)
SET @offset = 2.0 / meters_per_degree;
SET @left_lon = curr_lon - @offset * SIN(RADIANS(curr_course));
SET @left_lat = curr_lat + @offset * COS(RADIANS(curr_course));
SET @right_lon = curr_lon + @offset * SIN(RADIANS(curr_course));
SET @right_lat = curr_lat - @offset * COS(RADIANS(curr_course));
-- Start new segment if course changes >10° or first point
IF seg_id = 0 OR ABS(curr_course - prev_course) > 10.0 THEN
IF seg_id > 0 THEN
-- Finalize previous segment
INSERT INTO temp_segments (polygon, avg_course, start_time, end_time)
VALUES (
create_segment_polygon(seg_id),
(SELECT AVG(course) FROM precise_track_points
WHERE timestamp BETWEEN start_time AND end_time),
start_time,
end_time
);
END IF;
-- Start new segment
SET seg_id = seg_id + 1;
SET start_time = curr_time;
-- Initialize linestrings for new segment
INSERT INTO temp_segments VALUES (seg_id, NULL, NULL, NULL, NULL);
INSERT INTO temp_left_points (seg_id, point) VALUES (seg_id, ST_Point(@left_lon, @left_lat));
INSERT INTO temp_right_points (seg_id, point) VALUES (seg_id, ST_Point(@right_lon, @right_lat));
ELSE
-- Continue current segment
INSERT INTO temp_left_points (seg_id, point) VALUES (seg_id, ST_Point(@left_lon, @left_lat));
INSERT INTO temp_right_points (seg_id, point) VALUES (seg_id, ST_Point(@right_lon, @right_lat));
SET end_time = curr_time;
END IF;
SET prev_lon = curr_lon;
SET prev_lat = curr_lat;
SET prev_course = curr_course;
FETCH point_cur INTO curr_id, curr_lon, curr_lat, curr_course, curr_time;
IF done THEN
LEAVE read_loop;
END IF;
END LOOP;
-- Finalize last segment
IF seg_id > 0 THEN
INSERT INTO temp_segments (polygon, avg_course, start_time, end_time)
VALUES (
create_segment_polygon(seg_id),
(SELECT AVG(course) FROM precise_track_points
WHERE timestamp BETWEEN start_time AND end_time),
start_time,
end_time
);
END IF;
-- Merge overlapping/adjacent polygons
INSERT INTO temp_final_polygons
WITH merged AS (
SELECT
ST_Union(polygon) AS merged_poly,
MIN(start_time) AS start_time,
MAX(end_time) AS end_time,
AVG(avg_course) AS avg_course
FROM temp_segments
GROUP BY ST_ClusterDBSCAN(polygon, 5.0, 1) OVER () -- 5m max distance between polygons
)
SELECT merged_poly, avg_course, start_time, end_time FROM merged;
-- Return final results
SELECT
ST_AsGeoJSON(polygon) AS polygon_geojson,
avg_course,
start_time,
end_time,
ST_Area(polygon) AS area_sqm
FROM temp_final_polygons;
-- Cleanup
DROP TEMPORARY TABLE IF EXISTS temp_segments;
DROP TEMPORARY TABLE IF EXISTS temp_left_points;
DROP TEMPORARY TABLE IF EXISTS temp_right_points;
DROP TEMPORARY TABLE IF EXISTS temp_final_polygons;
CLOSE point_cur;
END //
CREATE FUNCTION create_segment_polygon(seg_id INT) RETURNS GEOMETRY
DETERMINISTIC
BEGIN
DECLARE left_line, right_line, polygon GEOMETRY;
code
SELECT ST_MakeLine(point ORDER BY id) INTO left_line
FROM temp_left_points WHERE seg_id = seg_id;
SELECT ST_MakeLine(point ORDER BY id DESC) INTO right_line -- Reverse order
FROM temp_right_points WHERE seg_id = seg_id;
SET polygon = ST_MakePolygon(ST_AddPoint(left_line, right_line));
RETURN polygon;
END //
DELIMITER ;
Assistant
Below is a “code-review–style” answer: first the problems I can spot in the procedure/function, then a cleaned-up version, and finally the exact way you can call it from MySQL and from Go.
1. Issues in the original routine
#
Problem
Why it matters / what breaks
1
temp_left_points and temp_right_points are used but never created.
All INSERT statements into those tables fail.
2
Primary-key clash in temp_segments (INSERT INTO temp_segments VALUES (seg_id, …) right after you have already inserted the row that finalises the previous segment)
You’ll hit Duplicate entry 'X' for key 'PRIMARY' as soon as two segments are produced. You meant UPDATE, not INSERT.
3
create_segment_polygon() filters with WHERE seg_id = seg_id
The parameter name shadows the column → condition is always TRUE → the function collects all rows. Use a different parameter name (e.g. p_seg_id).
4
id column referenced in ST_MakeLine(point ORDER BY id) but the temp tables don’t have an id column.
Run-time error: “Unknown column ‘id’ in order clause”.
5
ST_AddPoint(left_line, right_line) – second argument must be a POINT not a LINESTRING.
MySQL complains: “Argument 2 to function ST_AddPoint must be point”.
6
Use of reserved word timestamp without back-ticks in the cursor query.
Allowed in old MySQL, but in 8.0 it is a reserved keyword → always back-tick it.
7
ST_ClusterDBSCAN( … ) OVER () inside the GROUP BY clause is not allowed.
Window functions cannot appear in GROUP BY.
8
The handler sets done = TRUE but the flag is tested after the work in the loop. Edge cases: when the table is empty you will still try to use un-initialised vars.
Safer to test right after every FETCH.
9
The procedure is parameter-less yet you hard-code the latitude for the metres/deg factor ().
50°
Works only if your data are near 50 °N.
2. A fixed / simplified version
(The geometry math kept intentionally simple; tweak to your liking.)
sql
DELIMITER //
CREATE FUNCTION create_segment_polygon(p_seg_id INT)
RETURNS GEOMETRY
DETERMINISTIC
BEGIN
DECLARE l_left GEOMETRY;
DECLARE l_right GEOMETRY;
DECLARE l_ring GEOMETRY;
-- the temporary tables below now have a real surrogate key `pt_id`
SELECT ST_MakeLine(point ORDER BY pt_id)
INTO l_left
FROM temp_left_points
WHERE seg_id = p_seg_id;
SELECT ST_MakeLine(point ORDER BY pt_id DESC)
INTO l_right
FROM temp_right_points
WHERE seg_id = p_seg_id;
-- make one long LineString (left + right + back to start) and close it
SET l_ring = ST_MakePolygon( ST_LineStringFromWKB(
ST_AsWKB(
ST_AddPoint(
ST_Union(l_left, l_right),
ST_StartPoint(l_left), -- close the ring
1 -- allow_duplicates
)
)));
RETURN l_ring;
END //
CREATE PROCEDURE generate_track_polygons()
BEGIN
-----------------------------------------------------------------
-- 0) House-keeping
-----------------------------------------------------------------
DECLARE v_done BOOL DEFAULT FALSE;
DECLARE v_seg_id INT DEFAULT 0;
/* Current / previous point */
DECLARE v_id INT;
DECLARE v_lon, v_lat DECIMAL(12,8);
DECLARE v_course DECIMAL(6,3);
DECLARE v_time DATETIME(6);
DECLARE v_prev_lon, v_prev_lat DECIMAL(12,8);
DECLARE v_prev_course DECIMAL(6,3);
DECLARE v_start_time, v_end_time DATETIME(6);
DECLARE v_metres_per_degree DECIMAL(16,12)
DEFAULT 111320.0 * COS(RADIANS(50.0)); -- FIXME!
/* ------------------------------------------------------------
1) Scratch tables
------------------------------------------------------------ */
CREATE TEMPORARY TABLE IF NOT EXISTS temp_segments(
seg_id INT PRIMARY KEY,
polygon GEOMETRY NULL,
avg_course DECIMAL(6,3) NULL,
start_time DATETIME(6) NULL,
end_time DATETIME(6) NULL
) ENGINE = MEMORY;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_left_points (
pt_id INT AUTO_INCREMENT PRIMARY KEY,
seg_id INT,
point GEOMETRY NOT NULL
) ENGINE = MEMORY;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_right_points LIKE temp_left_points;
/* ------------------------------------------------------------
2) Cursor
------------------------------------------------------------ */
DECLARE c_points CURSOR FOR
SELECT id, longitude, latitude, course, `timestamp`
FROM precise_track_points
ORDER BY `timestamp`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = TRUE;
OPEN c_points;
FETCH c_points
INTO v_id, v_lon, v_lat, v_course, v_time;
IF v_done THEN
CLOSE c_points;
SELECT 'no points' AS message;
RETURN;
END IF;
SET v_prev_lon = v_lon;
SET v_prev_lat = v_lat;
SET v_prev_course = v_course;
SET v_start_time = v_time;
SET v_seg_id = 1; -- first segment
INSERT INTO temp_segments (seg_id) VALUES (v_seg_id);
/* ------------------------------------------------------------
3) Main loop
------------------------------------------------------------ */
read_loop: LOOP
/* compute 2-metre offset */
SET @offset = 2.0 / v_metres_per_degree;
SET @left_lon = v_lon - @offset * SIN(RADIANS(v_course));
SET @left_lat = v_lat + @offset * COS(RADIANS(v_course));
SET @right_lon = v_lon + @offset * SIN(RADIANS(v_course));
SET @right_lat = v_lat - @offset * COS(RADIANS(v_course));
/* do we need a new segment? */
IF ABS(v_course - v_prev_course) > 10.0 THEN
/* finalise the current segment */
UPDATE temp_segments
SET polygon = create_segment_polygon(v_seg_id),
avg_course = ( SELECT AVG(course)
FROM precise_track_points
WHERE `timestamp`
BETWEEN v_start_time AND v_end_time ),
start_time = v_start_time,
end_time = v_end_time
WHERE seg_id = v_seg_id;
/* start a new segment */
SET v_seg_id = v_seg_id + 1;
SET v_start_time = v_time;
INSERT INTO temp_segments (seg_id) VALUES (v_seg_id);
END IF;
/* append points to the current segment */
INSERT INTO temp_left_points (seg_id, point)
VALUES (v_seg_id, ST_Point(@left_lon, @left_lat));
INSERT INTO temp_right_points (seg_id, point)
VALUES (v_seg_id, ST_Point(@right_lon, @right_lat));
SET v_end_time = v_time;
SET v_prev_lon = v_lon;
SET v_prev_lat = v_lat;
SET v_prev_course = v_course;
/* fetch the next record ----------------------------------- */
FETCH c_points
INTO v_id, v_lon, v_lat, v_course, v_time;
IF v_done THEN
LEAVE read_loop;
END IF;
END LOOP;
/* finalise last segment */
UPDATE temp_segments
SET polygon = create_segment_polygon(v_seg_id),
avg_course = ( SELECT AVG(course)
FROM precise_track_points
WHERE `timestamp`
BETWEEN v_start_time AND v_end_time ),
start_time = v_start_time,
end_time = v_end_time
WHERE seg_id = v_seg_id;
/* ------------------------------------------------------------
4) Merge adjacent / overlapping polygons
------------------------------------------------------------ */
WITH clusters AS (
SELECT t.*,
ST_ClusterDBSCAN(polygon, 5.0, 1) OVER () AS cluster_id
FROM temp_segments AS t
)
SELECT
ST_AsGeoJSON(ST_Union(polygon)) AS polygon_geojson,
AVG(avg_course) AS avg_course,
MIN(start_time) AS start_time,
MAX(end_time) AS end_time,
ST_Area(ST_Union(polygon)) AS area_sqm
FROM clusters
GROUP BY cluster_id;
/* ------------------------------------------------------------
5) Cleanup
------------------------------------------------------------ */
DROP TEMPORARY TABLE IF EXISTS temp_segments,
temp_left_points,
temp_right_points;
CLOSE c_points;
END //
DELIMITER ;
Key changes:
Created the missing temp tables (temp_left_points, temp_right_points).
Replaced duplicate INSERT with UPDATE.
Avoided naming collision in the function (p_seg_id vs column).
Back-ticked timestamp.
Moved the window function into a CTE so it is not in the GROUP BY.
Fixed geometry handling in create_segment_polygon.
3. Calling it
3.1 Plain MySQL
sql
CALL generate_track_polygons();
The procedure produces one result-set with columns