Search code examples
mysqlsqltriggersspatial-index

TRIGGER based on spatial data


I have a table called pano_raw that has 3 columns lat, lng, and latlng.

lat and lng are just decimals (10,3) and latlng is a spatial index of type POINT.

This is an example statement that would update the database based on lat and lng.

INSERT INTO pano_raw (latlng) VALUES( GeomFromText( 'POINT(-72.34 32.45)' ));

I'm trying to create a trigger based off the statement above, that will automatically update the column when I update lat and lng separately. It's a pain updating the spatial data column everytime with SQL since the query is specialized. It's much easier to just write a trigger (in theory) that will update when I write a simple decimal value to the table.

The problem I'm having is with the syntax. Here's my best (2 hour shot at it).

SET @sql := CONCAT('POINT(',pano_raw.lng,' ',pano_raw.lat,')');

CREATE TRIGGER trig_pano_raw BEFORE INSERT ON pano_raw
FOR EACH ROW
BEGIN
    SET pano_raw.latlng = GeomFromText( @sql ) );
END;
CREATE TRIGGER trig_pano_raw BEFORE UPDATE ON pano_raw
FOR EACH ROW
BEGIN
    SET pano_raw.latlng = GeomFromText( @sql ) );
END;

I would really appreciate help getting this working.


Solution

  • This doesn't work?

    CREATE TRIGGER trig_pano_raw BEFORE INSERT ON pano_raw
    FOR EACH ROW
    BEGIN
        SET NEW.latlng = PointFromWKB( POINT( NEW.lat, NEW.lng ) );
    END;
    

    Regarding the Update trigger, note that

    • 1st, it has to have a different name and

    • 2nd, you may want to check which field is updated, like this:

    update trigger

    DELIMITER $$
    CREATE TRIGGER trig_Update_pano_raw BEFORE UPDATE ON pano_raw
    FOR EACH ROW
    BEGIN
        IF ((NEW.lat != OLD.lat) OR (NEW.lng != OLD.lng))
        THEN
            SET NEW.latlng = PointFromWKB( POINT( NEW.lat, NEW.lng ) );
        ELSEIF (NEW.latlng != OLD.latlng)
        THEN
            BEGIN
                SET NEW.lat = X(NEW.latlng);
                SET NEW.lng = Y(NEW.latlng);
            END;
        END IF;
    END;$$
    DELIMITER ;