1
votes

This has been driving me nuts for the past 2 hours:

I'm trying to query for overlapping polygons. This works nicely with PostGIS-functions, but i'm having a hard time in writing this query with SQLAlchemy.

The proper SQL-Query is:

SELECT id FROM track WHERE ST_Overlaps(
  (
    SELECT ST_GeomFromText(
      'POLYGON((
        16.15 47.25, 
        16.15 46.57, 
        13.85 46.57, 
        13.85 47.25, 
        16.15 47.25
      ))', 
    4326)
  ), 
  track.extent
);

(track.extent is a column that holds polygons in geo-format, ST_GeomFromText() creates the polygon i'm comparing them to)

I'm using ORM and my python-code looks like this so far:

viewport = select([func.ST_GeomFromText(('POLYGON(( \
  16.15 47.25, \
  16.15 46.57, \
  13.85 46.57, \
  13.85 47.25, \
  16.15 47.25))' \
  ,4326))])

DBSession.query(Track.id).filter( \
  func.ST_Overlaps(viewport, Track.extent)).all()

The code above is interpreted by SQLAlchemy as the following SQL-Query:

SELECT track.id AS track_id FROM track, 
(SELECT ST_GeomFromText('
  POLYGON((
    16.15 47.25, 
    16.15 46.57, 
    13.85 46.57, 
    13.85 47.25, 
    16.15 47.25
  ))', 
  4326) AS "ST_GeomFromText_1"
) 
WHERE ST_Overlaps(
  (
    SELECT ST_GeomFromText(
      'POLYGON((
        16.15 47.25, 
        16.15 46.57, 
        13.85 46.57, 
        13.85 47.25, 
        16.15 47.25
      ))', 
      4326) AS "ST_GeomFromText_1"
    ), 
  track.extent
);

which yields in an ERROR:

 ProgrammingError: (ProgrammingError) subquery in FROM must have an alias
 LINE 2: FROM track, (SELECT ST_GeomFromText('POLYGON((16.15759034023...
                     ^
 HINT:  For example, FROM (SELECT ...) [AS] foo.

How can i tell sqlalchemy to either get rid of the unnecessary viewport-subquery in the FROM-clause or add an alias to the viewport-query?

1
Why do you need a subquery in the first place? Can't you just do viewport = func.ST_GeomFromText(...) or does that not work? - univerio
@univerio no, that's not working - also in SQL the function needs to be called with SELECT, calling the function without SELECT gives a syntax error - Christian Benke

1 Answers

1
votes

I believe you are looking for the .label() construct:

viewport = select([func.ST_GeomFromText(...)]).label("viewport")

Then, putting that in the WHERE clause does not also put it in the FROM clause:

str(session.query(Track.id).filter(func.ST_Overlaps(viewport, Track.extent))
# 'SELECT track.id AS track_id \nFROM track \nWHERE ST_Overlaps((SELECT ST_GeomFromText(...) AS "ST_GeomFromText_1"), track.extent)'