Compute length on insertΒΆ

It is possible to insert a geometry and ask PostgreSQL to compute its length at the same time. This example uses SQLAlchemy core queries.

 9 from sqlalchemy import Column
10 from sqlalchemy import Float
11 from sqlalchemy import Integer
12 from sqlalchemy import MetaData
13 from sqlalchemy import Table
14 from sqlalchemy import bindparam
15 from sqlalchemy import func
16
17 from geoalchemy2 import Geometry
18 from geoalchemy2.shape import to_shape
19
20 # Tests imports
21 from tests import select
22
23 metadata = MetaData()
24
25 table = Table(
26     "inserts",
27     metadata,
28     Column("id", Integer, primary_key=True),
29     Column("geom", Geometry("LINESTRING", 4326)),
30     Column("distance", Float),
31 )
32
33
34 class TestLengthAtInsert:
35     def test_query(self, conn):
36         metadata.drop_all(conn, checkfirst=True)
37         metadata.create_all(conn)
38
39         # Define geometries to insert
40         values = [
41             {"ewkt": "SRID=4326;LINESTRING(0 0, 1 0)"},
42             {"ewkt": "SRID=4326;LINESTRING(0 0, 0 1)"},
43         ]
44
45         # Define the query to compute distance (without spheroid)
46         distance = func.ST_Length(func.ST_GeomFromEWKT(bindparam("ewkt")), False)
47
48         i = table.insert()
49         i = i.values(geom=bindparam("ewkt"), distance=distance)
50
51         # Execute the query with values as parameters
52         conn.execute(i, values)
53
54         # Check the result
55         q = select([table])
56         res = conn.execute(q).fetchall()
57
58         # Check results
59         assert len(res) == 2
60
61         r1 = res[0]
62         assert r1[0] == 1
63         assert r1[1].srid == 4326
64         assert to_shape(r1[1]).wkt == "LINESTRING (0 0, 1 0)"
65         assert round(r1[2]) == 111195
66
67         r2 = res[1]
68         assert r2[0] == 2
69         assert r2[1].srid == 4326
70         assert to_shape(r2[1]).wkt == "LINESTRING (0 0, 0 1)"
71         assert round(r2[2]) == 111195

Gallery generated by Sphinx-Gallery