Note
Click here 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.ext.declarative import declarative_base
14
15 from geoalchemy2 import Geometry
16
17 # Tests imports
18 from tests import select
19
20 Base = declarative_base()
21
22
23 class RawGeometry(Geometry):
24 """This class is used to remove the 'ST_AsEWKB()'' function from select queries"""
25
26 def column_expression(self, col):
27 return col
28
29
30 class Point(Base):
31 __tablename__ = "point"
32 id = Column(Integer, primary_key=True)
33 geom = Column(Geometry(srid=4326, geometry_type="POINT"))
34 raw_geom = Column(
35 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 \n"
46 "FROM point"
47 )
48
49
50 def test_func_no_wrapping():
51 # Select query with function
52 select_query = select([
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 # Check the query
59 assert str(select_query) == (
60 "SELECT "
61 "ST_AsEWKB(ST_Buffer(point.geom)) AS \"ST_Buffer_1\", "
62 "ST_AsEWKB(ST_Buffer(point.geom)) AS \"ST_Buffer_2\", "
63 "ST_Buffer(point.geom) AS \"ST_Buffer_3\" \n"
64 "FROM point"
65 )