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.
11 from sqlalchemy import Column
12 from sqlalchemy import Integer
13 from sqlalchemy import func
14 from sqlalchemy.orm import declarative_base
15
16 from geoalchemy2 import Geometry
17
18 # Tests imports
19 from tests import select
20
21 Base = declarative_base()
22
23
24 class RawGeometry(Geometry):
25 """This class is used to remove the 'ST_AsEWKB()'' function from select queries"""
26
27 def column_expression(self, col):
28 return col
29
30
31 class Point(Base): # type: ignore
32 __tablename__ = "point"
33 id = Column(Integer, primary_key=True)
34 geom = Column(Geometry(srid=4326, geometry_type="POINT"))
35 raw_geom = Column(RawGeometry(srid=4326, geometry_type="POINT"))
36
37
38 def test_no_wrapping():
39 # Select all columns
40 select_query = select([Point])
41
42 # Check that the 'geom' column is wrapped by 'ST_AsEWKB()' and that the column
43 # 'raw_geom' is not.
44 assert str(select_query) == (
45 "SELECT point.id, ST_AsEWKB(point.geom) AS geom, point.raw_geom \nFROM point"
46 )
47
48
49 def test_func_no_wrapping():
50 # Select query with function
51 select_query = select(
52 [
53 func.ST_Buffer(Point.geom), # with wrapping (default behavior)
54 func.ST_Buffer(Point.geom, type_=Geometry), # with wrapping
55 func.ST_Buffer(Point.geom, type_=RawGeometry), # without wrapping
56 ]
57 )
58
59 # Check the query
60 assert str(select_query) == (
61 "SELECT "
62 'ST_AsEWKB(ST_Buffer(point.geom)) AS "ST_Buffer_1", '
63 'ST_AsEWKB(ST_Buffer(point.geom)) AS "ST_Buffer_2", '
64 'ST_Buffer(point.geom) AS "ST_Buffer_3" \n'
65 "FROM point"
66 )