[postgis-devel] An any spatial type that works for geometry / geography
Regina Obe
lr at pcorp.us
Tue Jan 31 12:17:10 PST 2023
We've had this issue for a long time that many functions that can work just
as easily for geography require geography to be cast to geometry to use
them.
This we've been discussing on #Postgis irc what to do.
There have been the usual suspects bandied about for years:
1) Just define the functions for geography -- this balloons our list of
functions, making it hard to browse the list in psql/pgadmin and also adds
technical debt, way more redundant functions to wade thru and patch in our
scripts.
2) Define an autocast from geography to geometry - this causes much
unpredicatability.
Note we already have an autocast from geometry -> geography, but that is
less of a concern
Since if a geometry is not in spheroidal spatial ref, the autocast fails.
The geography would just silently pass and do an unexpected horrible thing
that wouldn't be discovered until some plane crashes.
My final thought is the cleanest way to do this is with an anypostgisvector
or some such thing and for select functions that underlying logic is the
same for both planar and spheroidal, would allow either in.
Right now I can test the theory out by for example,
Defining a st_pointn variant
CREATE OR REPLACE FUNCTION test_st_pointn(anyelement,integer)
RETURNS anyelement
LANGUAGE 'c'
COST 50
IMMUTABLE STRICT PARALLEL SAFE
AS '$libdir/postgis-3', 'LWGEOM_pointn_linestring';
And with that, I can do
SELECT test_st_pointn(ST_GeomFromText('LINESTRING(1 2, 3 4, 5 6)'),1); ->
returns a geometry
SELECT test_st_pointn(ST_GeogFromText('LINESTRING(1 2, 3 4, 5 6)'),1); ->
returns a geography
The only thing I don't like about the above, is then it will also match any
gibberish like
SELECT test_st_pointn('hello there'::text,1);
ERROR: Unknown geometry type: 231 - Invalid typeSQL state: XX000
Or
SELECT test_st_pointn(ST_AsGeoJSON(ST_GeomFromText('LINESTRING(1 2, 3 4, 5
6)')),1);
ERROR: Unknown geometry type: 1920226149 - Invalid type
SQL state: XX000
But hey, at least it returns an error.
So perhaps just using the anyelement type for these cases isn't horrible
especially if we've tested in the face of dangerous inputs.
The only downside of this, is it would require dropping our geometry type
functions that under the plumbing should call the same for geography and
replacing with an anyelement type.
I'm not sure how hard it would be to create our own type that just targets
geometry and geography. That I think would be cleaner if it's not too much
trouble.
Anyone see issues with this idea?
Thanks,
Regina
More information about the postgis-devel
mailing list