Note
Go to the end to download the full example code.
Disable wrapping in selectΒΆ
If the application wants to build queries with GeoAlchemy 2 and gets them as strings, the wrapping of geometry columns with a ST_AsEWKB() function might be annoying. In this case it is possible to disable this wrapping. This example uses SQLAlchemy ORM queries.
10 from sqlalchemy import Column
11 from sqlalchemy import Integer
12 from sqlalchemy import func
13 from sqlalchemy import select
14 from sqlalchemy.orm import declarative_base
15
16 from geoalchemy2 import Geometry
17
18 Base = declarative_base()
19
20
21 class RawGeometry(Geometry):
22 """This class is used to remove the 'ST_AsEWKB()'' function from select queries"""
23
24 def column_expression(self, col):
25 return col
26
27
28 class Point(Base): # type: ignore
29 __tablename__ = "point"
30 id = Column(Integer, primary_key=True)
31 geom = Column(Geometry(srid=4326, geometry_type="POINT"))
32 raw_geom = Column(RawGeometry(srid=4326, geometry_type="POINT"))
33
34
35 def test_no_wrapping():
36 # Select all columns
37 select_query = select(Point)
38
39 # Check that the 'geom' column is wrapped by 'ST_AsEWKB()' and that the column
40 # 'raw_geom' is not.
41 assert str(select_query) == (
42 "SELECT point.id, ST_AsEWKB(point.geom) AS geom, point.raw_geom \nFROM point"
43 )
44
45
46 def test_func_no_wrapping():
47 # Select query with function
48 select_query = select(
49 func.ST_Buffer(Point.geom), # with wrapping (default behavior)
50 func.ST_Buffer(Point.geom, type_=Geometry), # with wrapping
51 func.ST_Buffer(Point.geom, type_=RawGeometry), # without wrapping
52 )
53
54 # Check the query
55 assert str(select_query) == (
56 "SELECT "
57 'ST_AsEWKB(ST_Buffer(point.geom)) AS "ST_Buffer_1", '
58 'ST_AsEWKB(ST_Buffer(point.geom)) AS "ST_Buffer_2", '
59 'ST_Buffer(point.geom) AS "ST_Buffer_3" \n'
60 "FROM point"
61 )