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.orm 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):  # type: ignore
    31     __tablename__ = "point"
    32     id = Column(Integer, primary_key=True)
    33     geom = Column(Geometry(srid=4326, geometry_type="POINT"))
    34     raw_geom = Column(RawGeometry(srid=4326, geometry_type="POINT"))
    35
    36
    37 def test_no_wrapping():
    38     # Select all columns
    39     select_query = select([Point])
    40
    41     # Check that the 'geom' column is wrapped by 'ST_AsEWKB()' and that the column
    42     # 'raw_geom' is not.
    43     assert str(select_query) == (
    44         "SELECT point.id, ST_AsEWKB(point.geom) AS geom, point.raw_geom \nFROM point"
    45     )
    46
    47
    48 def test_func_no_wrapping():
    49     # Select query with function
    50     select_query = select(
    51         [
    52             func.ST_Buffer(Point.geom),  # with wrapping (default behavior)
    53             func.ST_Buffer(Point.geom, type_=Geometry),  # with wrapping
    54             func.ST_Buffer(Point.geom, type_=RawGeometry),  # without wrapping
    55         ]
    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     )

Gallery generated by Sphinx-Gallery