I have a fair bit of experience with Postgres and PostGIS running queries and scripts, but no experience creating functions. I feel like what I want to achieve is rather more complex than the examples I've seen so I'm hoping someone can help me out.
I'm creating a web application that allows users to update lot boundary records stored in a spatial table based on the intersection with a polygon drawn on a map and some values entered into a form. I don't know if there is a way of storing a subset of database records in an array and iterating over it, updating each record in turn, or if I have to run separate update scripts within the function. I'm also not sure if its possible to pass in a table name as an argument to a function, as I'd like to just run the function and have it work on different tables.
If I would create a function that would do all the things I wanted it to do by simply running a bunch of separate UPDATE scripts, it might look like the following (function not actually tested):
CREATE OR REPLACE FUNCTION updateLots(wkt_geom text, tablename varchar(25), landuse varchar(25), density NUMERIC(4,1))
RETURNs VOID AS
$$
BEGIN
UPDATE [tablename] SET landuse = [landuse] WHERE ST_Intersection(geom, GeomFromWKT([wkt_geom], 3857));
UPDATE [tablename] SET density = [density] WHERE ST_Intersection(geom, GeomFromWKT([wkt_geom], 3857)) WHERE landuse = 'Residential';
UPDATE [tablename] SET density = NULL WHERE ST_Intersection(geom, GeomFromWKT([wkt_geom], 3857)) WHERE landuse != 'Residential';
UPDATE [tablename] SET yield = area / 10000 * [density] WHERE ST_Intersection(geom, GeomFromWKT([wkt_geom], 3857));
END;
$$
LANGUAGE plpgsql;
While this approach would save me from running several nested database scripts from the server, it seems inefficient and Postgres will not accept tablename as an argument as is. Hence I'm wondering the following 2 things:
- Is there a way to create a subset of a table based on the spatial intersection with a provided geometry and iterate over each record, performing the necessary updates? If yes, how might this function be specified?
- Can I provide a table name as an argument to a function?
I'm not sure of the best way to proceed, so if someone can tell me if what I want to do is possible and if so get me started with specifying a function I'd be very appreciative.
Cheers.