GeoAlchemy 2 Documentation¶
Using SQLAlchemy with Spatial Databases.
GeoAlchemy 2 provides extensions to SQLAlchemy for working with spatial databases.
GeoAlchemy 2 focuses on PostGIS. PostGIS 1.5, PostGIS 2 and PostGIS 3 are supported.
SpatiaLite is also supported, but using GeoAlchemy 2 with SpatiaLite requires some specific configuration on the application side. GeoAlchemy 2 works with SpatiaLite 4.3.0 and higher (except for alembic helpers that need SpatiaLite >= 5).
GeoAlchemy 2 aims to be simpler than its predecessor, GeoAlchemy. Simpler to use, and simpler to maintain.
The current version of this documentation applies to the version 0.12.1 of GeoAlchemy 2.
Requirements¶
GeoAlchemy 2 requires SQLAlchemy 1.4.
Installation¶
GeoAlchemy 2 is available on the Python Package Index. So it can be installed with the standard pip or easy_install tools.
What’s New in GeoAlchemy 2¶
- GeoAlchemy 2 supports PostGIS’
geometry
type, as well as thegeography
andraster
types. - The first series had its own namespace for spatial functions. With GeoAlchemy
2, spatial functions are called like any other SQLAlchemy function, using
func
, which is SQLAlchemy’s standard way of calling SQL functions. - GeoAlchemy 2 works with SQLAlchemy’s ORM, as well as with SQLAlchemy’s SQL Expression Language (a.k.a the SQLAlchemy Core). (This is thanks to SQLAlchemy’s new type-level comparator system.)
- GeoAlchemy 2 supports reflection of geometry and geography columns.
- GeoAlchemy 2 adds
to_shape
,from_shape
functions for a better integration with Shapely.
Migrate to GeoAlchemy 2¶
This section describes how to migrate an application from the first series of GeoAlchemy to GeoAlchemy 2.
Defining Geometry Columns¶
The first series has specific types like Point
, LineString
and
Polygon
. These are gone, the geoalchemy2.types.Geometry
type
should be used instead, and a geometry_type
can be passed to it.
So, for example, a polygon
column that used to be defined like this:
geom = Column(Polygon)
is now defined like this:
geom = Column(Geometry('POLYGON'))
This change is related to GeoAlchemy 2 supporting the geoalchemy2.types.Geography type.
Calling Spatial Functions¶
The first series has its own namespace/object for calling spatial
functions, namely geoalchemy.functions
. With GeoAlchemy 2,
SQLAlchemy’s func
object should be used.
For example, the expression
functions.buffer(functions.centroid(box), 10, 2)
would be rewritten to this with GeoAlchemy 2:
func.ST_Buffer(func.ST_Centroid(box), 10, 2)
Also, as the previous example hinted it, the names of spatial functions are now
all prefixed with ST_
. (This is to be consistent with PostGIS and the
SQL-MM
standard.) The ST_
prefix should be used even when applying
spatial functions to columns, geoalchemy2.elements.WKTElement
,
or geoalchemy2.elements.WKTElement
objects:
Lake.geom.ST_Buffer(10, 2)
lake_table.c.geom.ST_Buffer(10, 2)
lake.geom.ST_Buffer(10, 2)
WKB and WKT Elements¶
The first series has classes like PersistentSpatialElement
,
PGPersistentSpatialElement
, WKTSpatialElement
.
They’re all gone, and replaced by two classes only:
geoalchemy2.elements.WKTElement
and
geoalchemy2.elements.WKBElement
.
geoalchemy2.elements.WKTElement
is to be used in expressions
where a geometry with a specific SRID should be specified. For example:
Lake.geom.ST_Touches(WKTElement('POINT(1 1)', srid=4326))
If no SRID need be specified, a string can used directly:
Lake.geom.ST_Touches('POINT(1 1)')
geoalchemy2.elements.WKTElement
literally replaces the first series’WKTSpatialElement
.geoalchemy2.elements.WKBElement
is the type into which GeoAlchemy 2 converts geometry values read from the database.For example, the
geom
attributes ofLake
objects loaded from the database would be references togeoalchemy2.elements.WKBElement
objects. This class replaces the first series’PersistentSpatialElement
classes.
See the Migrate to GeoAlchemy 2 page for details on how to migrate a GeoAlchemy application to GeoAlchemy 2.
Tutorials¶
GeoAlchemy 2 works with both SQLAlchemy’s Object Relational Mapping (ORM) and SQL Expression Language. This documentation provides a tutorial for each system. If you’re new to GeoAlchemy 2 start with this.
ORM Tutorial¶
(This tutorial is greatly inspired by the SQLAlchemy ORM Tutorial, which is recommended reading, eventually.)
GeoAlchemy does not provide an Object Relational Mapper (ORM), but works well with the SQLAlchemy ORM. This tutorial shows how to use the SQLAlchemy ORM with spatial tables, using GeoAlchemy.
Connect to the DB¶
For this tutorial we will use a PostGIS 2 database. To connect we use
SQLAlchemy’s create_engine()
function:
>>> from sqlalchemy import create_engine
>>> engine = create_engine('postgresql://gis:gis@localhost/gis', echo=True)
In this example the name of the database, the database user, and the database
password, is gis
.
The echo
flag is a shortcut to setting up SQLAlchemy logging, which is
accomplished via Python’s standard logging module. With it is enabled, we’ll
see all the generated SQL produced.
The return value of create_engine
is an Engine
object, which
represents the core interface to the database.
Declare a Mapping¶
When using the ORM, the configurational process starts by describing the
database tables we’ll be dealing with, and then by defining our own classes
which will be mapped to those tables. In modern SQLAlchemy, these two tasks are
usually performed together, using a system known as Declarative
, which
allows us to create classes that include directives to describe the actual
database table they will be mapped to.
>>> from sqlalchemy.ext.declarative import declarative_base
>>> from sqlalchemy import Column, Integer, String
>>> from geoalchemy2 import Geometry
>>>
>>> Base = declarative_base()
>>>
>>> class Lake(Base):
... __tablename__ = 'lake'
... id = Column(Integer, primary_key=True)
... name = Column(String)
... geom = Column(Geometry('POLYGON'))
The Lake
class establishes details about the table being mapped, including
the name of the table denoted by __tablename__
, and three columns id
,
name
, and geom
. The id
column will be the primary key of the table.
The geom
column is a geoalchemy2.types.Geometry
column whose
geometry_type
is POLYGON
.
Create the Table in the Database¶
The Lake
class has a corresponding Table
object representing
the database table. This Table
object was created automatically
by SQLAlchemy, it is referenced to by the Lake.__table__
property:
>>> Lake.__table__
Table('lake', MetaData(bind=None), Column('id', Integer(), table=<lake>,
primary_key=True, nullable=False), Column('name', String(), table=<lake>),
Column('geom', Polygon(srid=4326), table=<lake>), schema=None)
To create the lake
table in the database:
>>> Lake.__table__.create(engine)
If we wanted to drop the table we’d use:
>>> Lake.__table__.drop(engine)
Create an Instance of the Mapped Class¶
With the mapping declared, we can create a Lake
object:
>>> lake = Lake(name='Majeur', geom='POLYGON((0 0,1 0,1 1,0 1,0 0))')
>>> lake.geom
'POLYGON((0 0,1 0,1 1,0 1,0 0))'
>>> str(lake.id)
'None'
A WKT is passed to the Lake
constructor for its geometry. This WKT
represents the shape of our lake. Since we have not yet told SQLAlchemy
to persist the lake
object, its id
is None
.
The EWKT (Extended WKT) format is also supported. So, for example, if the
spatial reference system for the geometry column were 4326
, the string
SRID=4326;POLYGON((0 0,1 0,1,0 1,0 0))
could be used as the geometry
representation.
Create a Session¶
The ORM interacts with the database through a Session
. Let’s
create a Session
class:
>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)
This custom-made Session
class will create new Session
objects which
are bound to our database. Then, whenever we need to have a conversation with
the database, we instantiate a Session
:
>>> session = Session()
The above Session
is associated with our PostgreSQL Engine
, but
it hasn’t opened any connection yet.
Add New Objects¶
To persist our Lake
object, we add()
it to the Session
:
>>> session.add(lake)
At this point the lake
object has been added to the Session
, but no SQL
has been issued to the database. The object is in a pending state. To persist
the object a flush or commit operation must occur (commit implies flush):
>>> session.commit()
We can now query the database for Majeur
:
>>> our_lake = session.query(Lake).filter_by(name='Majeur').first()
>>> our_lake.name
u'Majeur'
>>> our_lake.geom
<WKBElement at 0x9af594c; '0103000000010000000500000000000000000000000000000000000000000000000000f03f0000000000000000000000000000f03f000000000000f03f0000000000000000000000000000f03f00000000000000000000000000000000'>
>>> our_lake.id
1
our_lake.geom
is a geoalchemy2.elements.WKBElement
, which a type
provided by GeoAlchemy. geoalchemy2.elements.WKBElement
wraps a WKB
value returned by the database.
Let’s add more lakes:
>>> session.add_all([
... Lake(name='Garde', geom='POLYGON((1 0,3 0,3 2,1 2,1 0))'),
... Lake(name='Orta', geom='POLYGON((3 0,6 0,6 3,3 3,3 0))')
... ])
>>> session.commit()
Query¶
A Query
object is created using the query()
function on Session
.
For example here’s a Query
that loads Lake
instances ordered by
their names:
>>> query = session.query(Lake).order_by(Lake.name)
Any Query
is iterable:
>>> for lake in query:
... print lake.name
...
Garde
Majeur
Orta
Another way to execute the query and get a list of Lake
objects involves
calling all()
on the Query
:
>>> lakes = session.query(Lake).order_by(Lake.name).all()
The SQLAlchemy ORM Tutorial’s Querying section provides more examples of queries.
Make Spatial Queries¶
Using spatial filters in SQL SELECT queries is very common. Such queries are
performed by using spatial relationship functions, or operators, in the
WHERE
clause of the SQL query.
For example, to find the Lake
s that contain the point POINT(4 1)
,
we can use this Query
:
>>> from sqlalchemy import func
>>> query = session.query(Lake).filter(
... func.ST_Contains(Lake.geom, 'POINT(4 1)'))
...
>>> for lake in query:
... print lake.name
...
Orta
GeoAlchemy allows rewriting this Query
more concisely:
>>> query = session.query(Lake).filter(Lake.geom.ST_Contains('POINT(4 1)'))
>>> for lake in query:
... print lake.name
...
Orta
Here the ST_Contains
function is applied to the Lake.geom
column
property. In that case the column property is actually passed to the function,
as its first argument.
Here’s another spatial filtering query, based on ST_Intersects
:
>>> query = session.query(Lake).filter(
... Lake.geom.ST_Intersects('LINESTRING(2 1,4 1)'))
...
>>> for lake in query:
... print lake.name
...
Garde
Orta
We can also apply relationship functions to
geoalchemy2.elements.WKBElement
. For example:
>>> lake = session.query(Lake).filter_by(name='Garde').one()
>>> print session.scalar(lake.geom.ST_Intersects('LINESTRING(2 1,4 1)'))
True
session.scalar
allows executing a clause and returning a scalar
value (a boolean value in this case).
The GeoAlchemy functions all start with ST_
. Operators are also called as
functions, but the function names don’t include the ST_
prefix. As an
example let’s use PostGIS’ &&
operator, which allows testing
whether the bounding boxes of geometries intersect. GeoAlchemy provides
the intersects
function for that:
>>> query = session.query
>>> query = session.query(Lake).filter(
... Lake.geom.intersects('LINESTRING(2 1,4 1)'))
...
>>> for lake in query:
... print lake.name
...
Garde
Orta
Set Spatial Relationships in the Model¶
Let’s assume that in addition to lake
we have another table, treasure
, that includes
treasure locations. And let’s say that we are interested in discovering the treasures hidden at the
bottom of lakes.
The Treasure
class is the following:
>>> class Treasure(Base):
... __tablename__ = 'treasure'
... id = Column(Integer, primary_key=True)
... geom = Column(Geometry('POINT'))
We can now add a relationship
to the Lake
table to automatically load the treasures
contained by each lake:
>>> from sqlalchemy.orm import relationship, backref
>>> class Lake(Base):
... __tablename__ = 'lake'
... id = Column(Integer, primary_key=True)
... name = Column(String)
... geom = Column(Geometry('POLYGON'))
... treasures = relationship(
... 'Treasure',
... primaryjoin='func.ST_Contains(foreign(Lake.geom), Treasure.geom).as_comparison(1, 2)',
... backref=backref('lake', uselist=False),
... viewonly=True,
... uselist=True,
... )
Note the use of the as_comparison
function. It is required for using an SQL function
(ST_Contains
here) in a primaryjoin
condition. This only works with SQLAlchemy 1.3, as the
as_comparison
function did not exist before that version. See the Custom operators based on SQL function
section of the SQLAlchemy documentation for more information.
Some information on the parameters used for configuring this relationship
:
backref
is used to provide the name of property to be placed on the class that handles this relationship in the other direction, namelyTreasure
;viewonly=True
specifies that the relationship is used only for loading objects, and not for persistence operations;uselist=True
indicates that the property should be loaded as a list, as opposed to a scalar.
Also, note that the treasures
property on lake
objects (and the lake
property on
treasure
objects) is loaded “lazily” when the property is first accessed. Another loading
strategy may be configured in the relationship
. For example you’d use lazy='joined'
for
related items to be loaded “eagerly” in the same query as that of the parent, using a JOIN
or
LEFT OUTER JOIN
.
See the Relationships API section of the
SQLAlchemy documentation for more detail on the relationship
function, and all the parameters that
can be used to configure it.
Use Other Spatial Functions¶
Here’s a Query
that calculates the areas of buffers for our lakes:
>>> from sqlalchemy import func
>>> query = session.query(Lake.name,
... func.ST_Area(func.ST_Buffer(Lake.geom, 2)) \
... .label('bufferarea'))
>>> for row in query:
... print '%s: %f' % (row.name, row.bufferarea)
...
Majeur: 21.485781
Garde: 32.485781
Orta: 45.485781
This Query
applies the PostGIS ST_Buffer
function to the geometry
column of every row of the lake
table. The return value is a list of rows,
where each row is actually a tuple of two values: the lake name, and the area
of a buffer of the lake. Each tuple is actually an SQLAlchemy KeyedTuple
object, which provides property type accessors.
Again, the Query
can written more concisely:
>>> query = session.query(Lake.name,
... Lake.geom.ST_Buffer(2).ST_Area().label('bufferarea'))
>>> for row in query:
... print '%s: %f' % (row.name, row.bufferarea)
...
Majeur: 21.485781
Garde: 32.485781
Orta: 45.485781
Obviously, processing and measurement functions can also be used in WHERE
clauses. For example:
>>> lake = session.query(Lake).filter(
... Lake.geom.ST_Buffer(2).ST_Area() > 33).one()
...
>>> print lake.name
Orta
And, like any other functions supported by GeoAlchemy, processing and
measurement functions can be applied to
geoalchemy2.elements.WKBElement
. For example:
>>> lake = session.query(Lake).filter_by(name='Majeur').one()
>>> bufferarea = session.scalar(lake.geom.ST_Buffer(2).ST_Area())
>>> print '%s: %f' % (lake.name, bufferarea)
Majeur: 21.485781
Majeur: 21.485781
Use Raster functions¶
A few functions (like ST_Transform(), ST_Union(), ST_SnapToGrid(), …) can be
used on both geoalchemy2.types.Geometry
and geoalchemy2.types.Raster
types. In GeoAlchemy2, these functions are only defined for
Geometry
as it can not be defined for several types at the
same time. Thus using these functions on Raster
requires
minor tweaking to enforce the type by passing the type_=Raster argument to the
function:
>>> query = session.query(Lake.raster.ST_Transform(2154, type_=Raster))
Further Reference¶
- Spatial Functions Reference: Spatial Functions
- Spatial Operators Reference: Spatial Operators
- Elements Reference: Elements
Core Tutorial¶
(This tutorial is greatly inspired from the SQLAlchemy SQL Expression Language Tutorial, which is recommended reading, eventually.)
This tutorial shows how to use the SQLAlchemy Expression Language (a.k.a. SQLAlchemy Core) with GeoAlchemy. As defined by the SQLAlchemy documentation itself, in contrast to the ORM’s domain-centric mode of usage, the SQL Expression Language provides a schema-centric usage paradigm.
Connect to the DB¶
For this tutorial we will use a PostGIS 2 database. To connect we use
SQLAlchemy’s create_engine()
function:
>>> from sqlalchemy import create_engine
>>> engine = create_engine('postgresql://gis:gis@localhost/gis', echo=True)
In this example the name of the database, the database user, and the database
password, is gis
.
The echo
flag is a shortcut to setting up SQLAlchemy logging, which is
accomplished via Python’s standard logging module. With it is enabled, we’ll
see all the generated SQL produced.
The return value of create_engine
is an Engine
object, which
respresents the core interface to the database.
Define a Table¶
The very first object that we need to create is a Table
. Here
we create a lake_table
object, which will correspond to the
lake
table in the database:
>>> from sqlalchemy import Table, Column, Integer, String, MetaData
>>> from geoalchemy2 import Geometry
>>>
>>> metadata = MetaData()
>>> lake_table = Table('lake', metadata,
... Column('id', Integer, primary_key=True),
... Column('name', String),
... Column('geom', Geometry('POLYGON'))
... )
This table is composed of three columns, id
, name
and geom
. The
geom
column is a geoalchemy2.types.Geometry
column whose
geometry_type
is POLYGON
.
Any Table
object is added to a MetaData
object, which is a catalog of
Table
objects (and other related objects).
Create the Table¶
With our Table
being defined we’re ready (to have SQLAlchemy)
create it in the database:
>>> lake_table.create(engine)
Calling create_all()
on metadata
would have worked equally well:
>>> metadata.create_all(engine)
In that case every Table
that’s referenced to by metadata
would be
created in the database. The metadata
object includes one Table
here,
our now well-known lake_table
object.
Reflecting tables¶
The reflection system of SQLAlchemy can be
used on tables containing geoalchemy2.types.Geometry
or
geoalchemy2.types.Geography
columns. In this case, the type must be imported to
be registered into SQLAlchemy, even if it is not used explicitly.
>>> from geoalchemy2 import Geometry # <= not used but must be imported
>>> from sqlalchemy import create_engine, MetaData
>>> engine = create_engine("postgresql://myuser:mypass@mydb.host.tld/mydbname")
>>> meta = MetaData()
>>> meta.reflect(bind=engine)
Insertions¶
We want to insert records into the lake
table. For that we need to create
an Insert
object. SQLAlchemy provides multiple constructs for creating an
Insert
object, here’s one:
>>> ins = lake_table.insert()
>>> str(ins)
INSERT INTO lake (id, name, geom) VALUES (:id, :name, ST_GeomFromEWKT(:geom))
The geom
column being a Geometry
column, the :geom
bind value is
wrapped in a ST_GeomFromEWKT
call.
To limit the columns named in the INSERT
query the values()
method
can be used:
>>> ins = lake_table.insert().values(name='Majeur',
... geom='POLYGON((0 0,1 0,1 1,0 1,0 0))')
...
>>> str(ins)
INSERT INTO lake (name, geom) VALUES (:name, ST_GeomFromEWKT(:geom))
Tip
The string representation of the SQL expression does not include the
data placed in values
. We got named bind parameters instead. To
view the data we can get a compiled form of the expression, and ask
for its params
:
>>> ins.compile.params()
{'geom': 'POLYGON((0 0,1 0,1 1,0 1,0 0))', 'name': 'Majeur'}
Up to now we’ve created an INSERT
query but we haven’t sent this query to
the database yet. Before being able to send it to the database we need
a database Connection
. We can get a Connection
from the Engine
object we created earlier:
>>> conn = engine.connect()
We’re now ready to execute our INSERT
statement:
>>> result = conn.execute(ins)
This is what the logging system should output:
INSERT INTO lake (name, geom) VALUES (%(name)s, ST_GeomFromEWKT(%(geom)s)) RETURNING lake.id
{'geom': 'POLYGON((0 0,1 0,1 1,0 1,0 0))', 'name': 'Majeur'}
COMMIT
The value returned by conn.execute()
, stored in result
, is
a sqlalchemy.engine.ResultProxy
object. In the case of an INSERT
we can
get the primary key value which was generated from our statement:
>>> result.inserted_primary_key
[1]
Instead of using values()
to specify our INSERT
data, we can send
the data to the execute()
method on Connection
. So we could rewrite
things as follows:
>>> conn.execute(lake_table.insert(),
... name='Majeur', geom='POLYGON((0 0,1 0,1 1,0 1,0 0))')
Now let’s use another form, allowing to insert multiple rows at once:
>>> conn.execute(lake_table.insert(), [
... {'name': 'Garde', 'geom': 'POLYGON((1 0,3 0,3 2,1 2,1 0))'},
... {'name': 'Orta', 'geom': 'POLYGON((3 0,6 0,6 3,3 3,3 0))'}
... ])
...
Tip
In the above examples the geometries are specified as WKT strings. Specifying them as EWKT strings is also supported.
Selections¶
Inserting involved creating an Insert
object, so it’d come to no surprise
that Selecting involves creating a Select
object. The primary construct to
generate SELECT
statements is SQLAlchemy`s select()
function:
>>> from sqlalchemy.sql import select
>>> s = select([lake_table])
>>> str(s)
SELECT lake.id, lake.name, ST_AsEWKB(lake.geom) AS geom FROM lake
The geom
column being a Geometry
it is wrapped in a ST_AsEWKB
call when specified as a column in a SELECT
statement.
We can now execute the statement and look at the results:
>>> result = conn.execute(s)
>>> for row in result:
... print 'name:', row['name'], '; geom:', row['geom'].desc
...
name: Majeur ; geom: 0103...
name: Garde ; geom: 0103...
name: Orta ; geom: 0103...
row['geom']
is a geoalchemy2.types.WKBElement
instance. In this
example we just get an hexadecimal representation of the geometry’s WKB value
using the desc
property.
Spatial Query¶
As spatial database users executing spatial queries is of a great interest to us. There comes GeoAlchemy!
Spatial relationship¶
Using spatial filters in SQL SELECT queries is very common. Such queries are
performed by using spatial relationship functions, or operators, in the
WHERE
clause of the SQL query.
For example, to find lakes that contain the point POINT(4 1)
,
we can use this:
>>> from sqlalchemy import func
>>> s = select([lake_table],
func.ST_Contains(lake_table.c.geom, 'POINT(4 1)'))
>>> str(s)
SELECT lake.id, lake.name, ST_AsEWKB(lake.geom) AS geom FROM lake WHERE ST_Contains(lake.geom, :param_1)
>>> result = conn.execute(s)
>>> for row in result:
... print 'name:', row['name'], '; geom:', row['geom'].desc
...
name: Orta ; geom: 0103...
GeoAlchemy allows rewriting this more concisely:
>>> s = select([lake_table], lake_table.c.geom.ST_Contains('POINT(4 1)'))
>>> str(s)
SELECT lake.id, lake.name, ST_AsEWKB(lake.geom) AS geom FROM lake WHERE ST_Contains(lake.geom, :param_1)
Here the ST_Contains
function is applied to lake.c.geom
. And the
generated SQL the lake.geom
column is actually passed to the
ST_Contains
function as the first argument.
Here’s another spatial query, based on ST_Intersects
:
>>> s = select([lake_table],
... lake_table.c.geom.ST_Intersects('LINESTRING(2 1,4 1)'))
>>> result = conn.execute(s)
>>> for row in result:
... print 'name:', row['name'], '; geom:', row['geom'].desc
...
name: Garde ; geom: 0103...
name: Orta ; geom: 0103...
This query selects lakes whose geometries intersect ``LINESTRING(2 1,4 1)``.
The GeoAlchemy functions all start with ST_
. Operators are also called as
functions, but the names of operator functions don’t include the ST_
prefix.
As an example let’s use PostGIS’ &&
operator, which allows testing
whether the bounding boxes of geometries intersect. GeoAlchemy provides the
intersects
function for that:
>>> s = select([lake_table],
... lake_table.c.geom.intersects('LINESTRING(2 1,4 1)'))
>>> result = conn.execute(s)
>>> for row in result:
... print 'name:', row['name'], '; geom:', row['geom'].desc
...
name: Garde ; geom: 0103...
name: Orta ; geom: 0103...
Processing and Measurement¶
Here’s a Select
that calculates the areas of buffers for our lakes:
>>> s = select([lake_table.c.name,
func.ST_Area(
lake_table.c.geom.ST_Buffer(2)).label('bufferarea')])
>>> str(s)
SELECT lake.name, ST_Area(ST_Buffer(lake.geom, %(param_1)s)) AS bufferarea FROM lake
>>> result = conn.execute(s)
>>> for row in result:
... print '%s: %f' % (row['name'], row['bufferarea'])
Majeur: 21.485781
Garde: 32.485781
Orta: 45.485781
Obviously, processing and measurement functions can also be used in WHERE
clauses. For example:
>>> s = select([lake_table.c.name],
lake_table.c.geom.ST_Buffer(2).ST_Area() > 33)
>>> str(s)
SELECT lake.name FROM lake WHERE ST_Area(ST_Buffer(lake.geom, :param_1)) > :ST_Area_1
>>> result = conn.execute(s)
>>> for row in result:
... print row['name']
Orta
And, like any other functions supported by GeoAlchemy, processing and
measurement functions can be applied to
geoalchemy2.elements.WKBElement
. For example:
>>> s = select([lake_table], lake_table.c.name == 'Majeur')
>>> result = conn.execute(s)
>>> lake = result.fetchone()
>>> bufferarea = conn.scalar(lake[lake_table.c.geom].ST_Buffer(2).ST_Area())
>>> print '%s: %f' % (lake['name'], bufferarea)
Majeur: 21.485781
Use Raster functions¶
A few functions (like ST_Transform(), ST_Union(), ST_SnapToGrid(), …) can be
used on both geoalchemy2.types.Geometry
and geoalchemy2.types.Raster
types. In GeoAlchemy2, these functions are only defined for
Geometry
as it can not be defined for several types at the
same time. Thus using these functions on Raster
requires
minor tweaking to enforce the type by passing the type_=Raster argument to the
function:
>>> s = select([func.ST_Transform(
lake_table.c.raster,
2154,
type_=Raster)
.label('transformed_raster')])
Further Reference¶
- Spatial Functions Reference: Spatial Functions
- Spatial Operators Reference: Spatial Operators
- Elements Reference: Elements
SpatiaLite Tutorial¶
GeoAlchemy 2’s main target is PostGIS. But GeoAlchemy 2 also supports SpatiaLite, the spatial extension to SQLite. This tutorial describes how to use GeoAlchemy 2 with SpatiaLite. It’s based on the ORM Tutorial, which you may want to read first.
Connect to the DB¶
Just like when using PostGIS connecting to a SpatiaLite database requires an Engine
. This is how
you create one for SpatiaLite:
>>> from sqlalchemy import create_engine
>>> from sqlalchemy.event import listen
>>>
>>> def load_spatialite(dbapi_conn, connection_record):
... dbapi_conn.enable_load_extension(True)
... dbapi_conn.load_extension('/usr/lib/x86_64-linux-gnu/mod_spatialite.so')
...
>>>
>>> engine = create_engine('sqlite:///gis.db', echo=True)
>>> listen(engine, 'connect', load_spatialite)
The call to create_engine
creates an engine bound to the database file gis.db
. After that
a connect
listener is registered on the engine. The listener is responsible for loading the
SpatiaLite extension, which is a necessary operation for using SpatiaLite through SQL.
At this point you can test that you are able to connect to the database:
>> conn = engine.connect()
2018-05-30 17:12:02,675 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2018-05-30 17:12:02,676 INFO sqlalchemy.engine.base.Engine ()
2018-05-30 17:12:02,676 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2018-05-30 17:12:02,676 INFO sqlalchemy.engine.base.Engine ()
You can also check that the gis.db
SQLite database file was created on the file system.
One additional step is required for using SpatiaLite: create the geometry_columns
and
spatial_ref_sys
metadata tables. This is done by calling SpatiaLite’s InitSpatialMetaData
function:
>>> from sqlalchemy.sql import select, func
>>>
>>> conn.execute(select([func.InitSpatialMetaData()]))
Note that this operation may take some time the first time it is executed for a database. When
InitSpatialMetaData
is executed again it will report an error:
InitSpatiaMetaData() error:"table spatial_ref_sys already exists"
You can safely ignore that error.
Before going further we can close the current connection:
>>> conn.close()
Declare a Mapping¶
Now that we have a working connection we can go ahead and create a mapping between a Python class and a database table.
>>> from sqlalchemy.ext.declarative import declarative_base
>>> from sqlalchemy import Column, Integer, String
>>> from geoalchemy2 import Geometry
>>>
>>> Base = declarative_base()
>>>
>>> class Lake(Base):
... __tablename__ = 'lake'
... id = Column(Integer, primary_key=True)
... name = Column(String)
... geom = Column(Geometry(geometry_type='POLYGON', management=True))
This basically works in the way as with PostGIS. The difference is the management
argument that must be set to True
.
Setting management
to True
indicates that the AddGeometryColumn
and
DiscardGeometryColumn
management functions will be used for the creation and removal of the
geometry column. This is required with SpatiaLite.
Create the Table in the Database¶
We can now create the lake
table in the gis.db
database:
>>> Lake.__table__.create(engine)
If we wanted to drop the table we’d use:
>>> Lake.__table__.drop(engine)
There’s nothing specific to SpatiaLite here.
Create a Session¶
When using the SQLAlchemy ORM the ORM interacts with the database through a Session
.
>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)
>>> session = Session()
The session is associated with our SpatiaLite Engine
. Again, there’s nothing
specific to SpatiaLite here.
Add New Objects¶
We can now create and insert new Lake
objects into the database, the same way we’d
do it using GeoAlchemy 2 with PostGIS.
>>> lake = Lake(name='Majeur', geom='POLYGON((0 0,1 0,1 1,0 1,0 0))')
>>> session.add(lake)
>>> session.commit()
We can now query the database for Majeur
:
>>> our_lake = session.query(Lake).filter_by(name='Majeur').first()
>>> our_lake.name
u'Majeur'
>>> our_lake.geom
<WKBElement at 0x9af594c; '0103000000010000000500000000000000000000000000000000000000000000000000f03f0000000000000000000000000000f03f000000000000f03f0000000000000000000000000000f03f00000000000000000000000000000000'>
>>> our_lake.id
1
Let’s add more lakes:
>>> session.add_all([
... Lake(name='Garde', geom='POLYGON((1 0,3 0,3 2,1 2,1 0))'),
... Lake(name='Orta', geom='POLYGON((3 0,6 0,6 3,3 3,3 0))')
... ])
>>> session.commit()
Query¶
Let’s make a simple, non-spatial, query:
>>> query = session.query(Lake).order_by(Lake.name)
>>> for lake in query:
... print(lake.name)
...
Garde
Majeur
Orta
Now a spatial query:
>>> from geolachemy2 import WKTElement
>>> query = session.query(Lake).filter(
... func.ST_Contains(Lake.geom, WKTElement('POINT(4 1)')))
...
>>> for lake in query:
... print(lake.name)
...
Orta
Here’s another spatial query, using ST_Intersects
this time:
>>> query = session.query(Lake).filter(
... Lake.geom.ST_Intersects(WKTElement('LINESTRING(2 1,4 1)')))
...
>>> for lake in query:
... print(lake.name)
...
Garde
Orta
We can also apply relationship functions to geoalchemy2.elements.WKBElement
. For example:
>>> lake = session.query(Lake).filter_by(name='Garde').one()
>>> print(session.scalar(lake.geom.ST_Intersects(WKTElement('LINESTRING(2 1,4 1)'))))
1
session.scalar
allows executing a clause and returning a scalar value (an integer value in this
case).
The value 1
indicates that the lake “Garde” does intersects the LINESTRING(2 1,4 1)
geometry. See the SpatiaLite SQL functions reference list for more information.
Function mapping¶
Several functions have different names in SpatiaLite than in PostGIS. The GeoAlchemy 2 package is based on the PostGIS syntax but it is possible to automatically translate the queries into SpatiaLite ones. For example, the function ST_GeomFromEWKT is automatically translated into GeomFromEWKT. Unfortunately, only a few functions are automatically mapped (the ones internally used by GeoAlchemy 2). Nevertheless, it is possible to define new mappings in order to translate the queries automatically. Here is an example to register a mapping for the ST_Buffer function:
>>> geoalchemy2.functions.register_sqlite_mapping(
... {'ST_Buffer': 'Buffer'}
... )
After this command, all ST_Buffer calls in the queries will be translated to Buffer calls when the query is executed on a SQLite DB.
A more complex example is provided for when the PostGIS function should be mapped depending on the given parameters. For example, the ST_Buffer function can actually be translate into either the Buffer function or the SingleSidedBuffer function (only when side=right or side=left is passed). See the Function translation for specific dialect example in the gallery.
Further Reference¶
- GeoAlchemy 2 ORM Tutotial: ORM Tutorial
- GeoAlchemy 2 Spatial Functions Reference: Spatial Functions
- GeoAlchemy 2 Spatial Operators Reference: Spatial Operators
- GeoAlchemy 2 Elements Reference: Elements
- SpatiaLite 4.3.0 SQL functions reference list
Gallery¶
Gallery¶
Note
Click here to download the full example code
Automatically use a function at insert or select¶
Sometimes the application wants to apply a function in an insert or in a select.
For example, the application might need the geometry with lat/lon coordinates while they
are projected in the DB. To avoid having to always tweak the query with a
ST_Transform()
, it is possible to define a TypeDecorator
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import func from sqlalchemy import text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import TypeDecorator from geoalchemy2 import Geometry from geoalchemy2 import shape # Tests imports from tests import test_only_with_dialects metadata = MetaData() Base = declarative_base(metadata=metadata) class TransformedGeometry(TypeDecorator): """This class is used to insert a ST_Transform() in each insert or select.""" impl = Geometry cache_ok = True def __init__(self, db_srid, app_srid, **kwargs): kwargs["srid"] = db_srid super().__init__(**kwargs) self.app_srid = app_srid self.db_srid = db_srid def column_expression(self, col): """The column_expression() method is overridden to set the correct type. This is needed so that the returned element will also be decorated. In this case we don't want to transform it again afterwards so we set the same SRID to both the ``db_srid`` and ``app_srid`` arguments. Without this the SRID of the WKBElement would be wrong. """ return getattr(func, self.impl.as_binary)( func.ST_Transform(col, self.app_srid), type_=self.__class__(db_srid=self.app_srid, app_srid=self.app_srid) ) def bind_expression(self, bindvalue): return func.ST_Transform( self.impl.bind_expression(bindvalue), self.db_srid, type_=self, ) class ThreeDGeometry(TypeDecorator): """This class is used to insert a ST_Force3D() in each insert.""" impl = Geometry cache_ok = True def column_expression(self, col): """The column_expression() method is overridden to set the correct type. This is not needed in this example but it is needed if one wants to override other methods of the TypeDecorator class, like ``process_result_value()`` for example. """ return getattr(func, self.impl.as_binary)(col, type_=self) def bind_expression(self, bindvalue): return func.ST_Force3D( self.impl.bind_expression(bindvalue), type=self, ) class Point(Base): __tablename__ = "point" id = Column(Integer, primary_key=True) raw_geom = Column(Geometry(srid=4326, geometry_type="POINT")) geom = Column( TransformedGeometry( db_srid=2154, app_srid=4326, geometry_type="POINT")) three_d_geom = Column( ThreeDGeometry(srid=4326, geometry_type="POINTZ", dimension=3)) def check_wkb(wkb, x, y): pt = shape.to_shape(wkb) assert round(pt.x, 5) == x assert round(pt.y, 5) == y @test_only_with_dialects("postgresql") class TestTypeDecorator(): def _create_one_point(self, session, conn): metadata.drop_all(conn, checkfirst=True) metadata.create_all(conn) # Create new point instance p = Point() p.raw_geom = "SRID=4326;POINT(5 45)" p.geom = "SRID=4326;POINT(5 45)" p.three_d_geom = "SRID=4326;POINT(5 45)" # Insert 2D geometry into 3D column # Insert point session.add(p) session.flush() session.expire(p) return p.id def test_transform(self, session, conn): self._create_one_point(session, conn) # Query the point and check the result pt = session.query(Point).one() assert pt.id == 1 assert pt.raw_geom.srid == 4326 check_wkb(pt.raw_geom, 5, 45) assert pt.geom.srid == 4326 check_wkb(pt.geom, 5, 45) # Check that the data is correct in DB using raw query q = text("SELECT id, ST_AsEWKT(geom) AS geom FROM point;") res_q = session.execute(q).fetchone() assert res_q.id == 1 assert res_q.geom == "SRID=2154;POINT(857581.899319668 6435414.7478354)" # Compare geom, raw_geom with auto transform and explicit transform pt_trans = session.query( Point, Point.raw_geom, func.ST_Transform(Point.raw_geom, 2154).label("trans"), ).one() assert pt_trans[0].id == 1 assert pt_trans[0].geom.srid == 4326 check_wkb(pt_trans[0].geom, 5, 45) assert pt_trans[0].raw_geom.srid == 4326 check_wkb(pt_trans[0].raw_geom, 5, 45) assert pt_trans[1].srid == 4326 check_wkb(pt_trans[1], 5, 45) assert pt_trans[2].srid == 2154 check_wkb(pt_trans[2], 857581.89932, 6435414.74784) def test_force_3d(self, session, conn): self._create_one_point(session, conn) # Query the point and check the result pt = session.query(Point).one() assert pt.id == 1 assert pt.three_d_geom.srid == 4326 assert pt.three_d_geom.desc.lower() == ( '01010000a0e6100000000000000000144000000000008046400000000000000000') |
Note
Click here to download the full example code
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 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | from sqlalchemy import Column from sqlalchemy import Float from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import Table from sqlalchemy import bindparam from sqlalchemy import func from geoalchemy2 import Geometry from geoalchemy2.shape import to_shape # Tests imports from tests import select from tests import test_only_with_dialects metadata = MetaData() table = Table( "inserts", metadata, Column("id", Integer, primary_key=True), Column("geom", Geometry("LINESTRING", 4326)), Column("distance", Float), ) @test_only_with_dialects("postgresql") class TestLengthAtInsert(): def test_query(self, conn): metadata.drop_all(conn, checkfirst=True) metadata.create_all(conn) # Define geometries to insert values = [ {"ewkt": "SRID=4326;LINESTRING(0 0, 1 0)"}, {"ewkt": "SRID=4326;LINESTRING(0 0, 0 1)"} ] # Define the query to compute distance (without spheroid) distance = func.ST_Length(func.ST_GeomFromText(bindparam("ewkt")), False) i = table.insert() i = i.values(geom=bindparam("ewkt"), distance=distance) # Execute the query with values as parameters conn.execute(i, values) # Check the result q = select([table]) res = conn.execute(q).fetchall() # Check results assert len(res) == 2 r1 = res[0] assert r1[0] == 1 assert r1[1].srid == 4326 assert to_shape(r1[1]).wkt == "LINESTRING (0 0, 1 0)" assert round(r1[2]) == 111195 r2 = res[1] assert r2[0] == 2 assert r2[1].srid == 4326 assert to_shape(r2[1]).wkt == "LINESTRING (0 0, 0 1)" assert round(r2[2]) == 111195 |
Note
Click here to download the full example code
Decipher Raster¶
The RasterElement objects store the Raster data in WKB form. When using rasters it is usually better to convert them into TIFF, PNG, JPEG or whatever. Nevertheless, it is possible to decipher the WKB to get a 2D list of values. This example uses SQLAlchemy ORM queries.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | import binascii import struct import pytest from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base from geoalchemy2 import Raster from geoalchemy2 import WKTElement # Tests imports from tests import test_only_with_dialects metadata = MetaData() Base = declarative_base(metadata=metadata) class Ocean(Base): __tablename__ = 'ocean' id = Column(Integer, primary_key=True) rast = Column(Raster) def __init__(self, rast): self.rast = rast def _format_e(endianness, struct_format): return _ENDIANNESS[endianness] + struct_format def wkbHeader(raw): # Function to decipher the WKB header # See http://trac.osgeo.org/postgis/browser/trunk/raster/doc/RFC2-WellKnownBinaryFormat header = {} header['endianness'] = struct.unpack('b', raw[0:1])[0] e = header['endianness'] header['version'] = struct.unpack(_format_e(e, 'H'), raw[1:3])[0] header['nbands'] = struct.unpack(_format_e(e, 'H'), raw[3:5])[0] header['scaleX'] = struct.unpack(_format_e(e, 'd'), raw[5:13])[0] header['scaleY'] = struct.unpack(_format_e(e, 'd'), raw[13:21])[0] header['ipX'] = struct.unpack(_format_e(e, 'd'), raw[21:29])[0] header['ipY'] = struct.unpack(_format_e(e, 'd'), raw[29:37])[0] header['skewX'] = struct.unpack(_format_e(e, 'd'), raw[37:45])[0] header['skewY'] = struct.unpack(_format_e(e, 'd'), raw[45:53])[0] header['srid'] = struct.unpack(_format_e(e, 'i'), raw[53:57])[0] header['width'] = struct.unpack(_format_e(e, 'H'), raw[57:59])[0] header['height'] = struct.unpack(_format_e(e, 'H'), raw[59:61])[0] return header def read_band(data, offset, pixtype, height, width, endianness=1): ptype, _, psize = _PTYPE[pixtype] pix_data = data[offset + 1: offset + 1 + width * height * psize] band = [ [ struct.unpack(_format_e(endianness, ptype), pix_data[ (i * width + j) * psize: (i * width + j + 1) * psize ])[0] for j in range(width) ] for i in range(height) ] return band def read_band_numpy(data, offset, pixtype, height, width, endianness=1): import numpy as np # noqa _, dtype, psize = _PTYPE[pixtype] dt = np.dtype(dtype) dt = dt.newbyteorder(_ENDIANNESS[endianness]) band = np.frombuffer(data, dtype=dtype, count=height * width, offset=offset + 1) band = (np.reshape(band, ((height, width)))) return band _PTYPE = { 0: ['?', '?', 1], 1: ['B', 'B', 1], 2: ['B', 'B', 1], 3: ['b', 'b', 1], 4: ['B', 'B', 1], 5: ['h', 'i2', 2], 6: ['H', 'u2', 2], 7: ['i', 'i4', 4], 8: ['I', 'u4', 4], 10: ['f', 'f4', 4], 11: ['d', 'f8', 8], } _ENDIANNESS = { 0: '>', 1: '<', } def wkbImage(raster_data, use_numpy=False): """Function to decipher the WKB raster data""" # Get binary data raw = binascii.unhexlify(raster_data) # Read header h = wkbHeader(bytes(raw)) e = h["endianness"] img = [] # array to store image bands offset = 61 # header raw length in bytes band_size = h['width'] * h['height'] # number of pixels in each band for i in range(h['nbands']): # Determine pixtype for this band pixtype = struct.unpack(_format_e(e, 'b'), raw[offset: offset + 1])[0] - 64 # Read data with either pure Python or Numpy if use_numpy: band = read_band_numpy( raw, offset, pixtype, h['height'], h['width']) else: band = read_band( raw, offset, pixtype, h['height'], h['width']) # Store the result img.append(band) offset = offset + 2 + band_size return img @test_only_with_dialects("postgresql") class TestDecipherRaster(): @pytest.mark.parametrize("pixel_type", [ '1BB', '2BUI', '4BUI', '8BSI', '8BUI', '16BSI', '16BUI', '32BSI', '32BUI', '32BF', '64BF' ]) def test_decipher_raster(self, pixel_type, session, conn): """Create a raster and decipher it""" metadata.drop_all(conn, checkfirst=True) metadata.create_all(conn) # Create a new raster polygon = WKTElement('POLYGON((0 0,1 1,0 1,0 0))', srid=4326) o = Ocean(polygon.ST_AsRaster(5, 6, pixel_type)) session.add(o) session.flush() # Decipher data from each raster image = wkbImage(o.rast.data) # Define expected result expected = [ [0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0] ] # Check results band = image[0] assert band == expected |
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 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import func from sqlalchemy.ext.declarative import declarative_base from geoalchemy2 import Geometry # Tests imports from tests import select Base = declarative_base() class RawGeometry(Geometry): """This class is used to remove the 'ST_AsEWKB()'' function from select queries""" def column_expression(self, col): return col class Point(Base): __tablename__ = "point" id = Column(Integer, primary_key=True) geom = Column(Geometry(srid=4326, geometry_type="POINT")) raw_geom = Column( RawGeometry(srid=4326, geometry_type="POINT")) def test_no_wrapping(): # Select all columns select_query = select([Point]) # Check that the 'geom' column is wrapped by 'ST_AsEWKB()' and that the column # 'raw_geom' is not. assert str(select_query) == ( "SELECT point.id, ST_AsEWKB(point.geom) AS geom, point.raw_geom \n" "FROM point" ) def test_func_no_wrapping(): # Select query with function select_query = select([ func.ST_Buffer(Point.geom), # with wrapping (default behavior) func.ST_Buffer(Point.geom, type_=Geometry), # with wrapping func.ST_Buffer(Point.geom, type_=RawGeometry) # without wrapping ]) # Check the query assert str(select_query) == ( "SELECT " "ST_AsEWKB(ST_Buffer(point.geom)) AS \"ST_Buffer_1\", " "ST_AsEWKB(ST_Buffer(point.geom)) AS \"ST_Buffer_2\", " "ST_Buffer(point.geom) AS \"ST_Buffer_3\" \n" "FROM point" ) |
Note
Click here to download the full example code
Function translation for specific dialect¶
Some functions have different names depending on the dialect. But sometimes one function in one dialect can be mapped to several other functions in another dialect, depending on the arguments passed. For example, the ST_Buffer function in PostgreSQL can translate into 2 functions in SQLite:
if the buffer is two-sided (symmetric), the PostgreSQL function:
ST_Buffer(the_table.geom, 10)
should become in SQLite:
Buffer(the_table.geom, 10)
if the buffer is one-sided, the PostgreSQL function:
ST_Buffer(the_table.geom, 10, 'side=right')
should become in SQLite:
SingleSidedBuffer(the_table.geom, 10, 0)
This case is much more complicated than just mapping a function name and we show here how to deal with it.
This example uses SQLAlchemy core queries.
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | from sqlalchemy import MetaData from sqlalchemy import func from sqlalchemy.ext.compiler import compiles from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.expression import BindParameter from geoalchemy2 import WKTElement from geoalchemy2 import functions # Tests imports from tests import format_wkt from tests import select metadata = MetaData() Base = declarative_base(metadata=metadata) def _compile_buffer_default(element, compiler, **kw): """Compile the element in the default case (no specific dialect). This function should not be needed for SQLAlchemy >= 1.1. """ return '{}({})'.format('ST_Buffer', compiler.process(element.clauses, **kw)) def _compile_buffer_sqlite(element, compiler, **kw): """Compile the element for the SQLite dialect.""" # Get the side parameters compiled = compiler.process(element.clauses, **kw) side_params = [ i for i in element.clauses if isinstance(i, BindParameter) and 'side' in str(i.value) ] if side_params: side_param = side_params[0] if 'right' in side_param.value: # If the given side is 'right', we translate the value into 0 and switch to the sided # function side_param.value = 0 element.identifier = 'SingleSidedBuffer' elif 'left' in side_param.value: # If the given side is 'left', we translate the value into 1 and switch to the sided # function side_param.value = 1 element.identifier = 'SingleSidedBuffer' if element.identifier == 'ST_Buffer': # If the identifier is still the default ST_Buffer we switch to the SpatiaLite function element.identifier = 'Buffer' # If there is no side parameter or if the side value is 'both', we use the default function return '{}({})'.format(element.identifier, compiled) # Register the specific compilation rules compiles(functions.ST_Buffer)(_compile_buffer_default) compiles(functions.ST_Buffer, 'sqlite')(_compile_buffer_sqlite) def test_specific_compilation(conn): # Build a query with a sided buffer query = select([ func.ST_AsText( func.ST_Buffer(WKTElement('LINESTRING(0 0, 1 0)', srid=4326), 1, 'side=left') ) ]) # Check the compiled query: the sided buffer should appear only in the SQLite query compiled_query = str(query.compile(dialect=conn.dialect)) if conn.dialect.name == 'sqlite': assert 'SingleSidedBuffer' in compiled_query assert 'ST_Buffer' not in compiled_query else: assert 'SingleSidedBuffer' not in compiled_query assert 'ST_Buffer' in compiled_query # Check the actual result of the query res = conn.execute(query).scalar() assert format_wkt(res) == 'POLYGON((1 0,0 0,0 1,1 1,1 0))' # Build a query with symmetric buffer to check nothing was broken query = select([ func.ST_AsText( func.ST_Buffer(WKTElement('LINESTRING(0 0, 1 0)', srid=4326), 1) ) ]) # Check the compiled query: the sided buffer should never appear in the query compiled_query = str(query.compile(dialect=conn.dialect)) assert 'SingleSidedBuffer' not in compiled_query if conn.dialect.name == 'sqlite': assert 'ST_Buffer' not in compiled_query assert 'Buffer' in compiled_query else: assert 'ST_Buffer' in compiled_query # Check the actual result of the query res = conn.execute(query).scalar() assert format_wkt(res) != 'POLYGON((1 0,0 0,0 1,1 1,1 0))' assert format_wkt(res).startswith('POLYGON((1 1,1') |
Note
Click here to download the full example code
Reproject a Raster using ST_Transform¶
The ST_Transform() function (and a few others like ST_SnapToGrid()) can be used on both Geometry and Raster types. In GeoAlchemy2, this function is only defined for Geometry as it can not be defined for several types at the same time. Thus using this function on Raster requires minor tweaking.
This example uses both SQLAlchemy core and ORM queries.
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import Table from sqlalchemy import func from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Query from geoalchemy2 import Geometry from geoalchemy2 import Raster # Tests imports from tests import select metadata = MetaData() Base = declarative_base(metadata=metadata) table = Table( "raster_table", metadata, Column("id", Integer, primary_key=True), Column("geom", Geometry("POLYGON", 4326)), Column("rast", Raster()), ) class RasterTable(Base): __tablename__ = 'raster_table_orm' id = Column(Integer, primary_key=True) geom = Column(Geometry("POLYGON", 4326)) rast = Column(Raster()) def __init__(self, rast): self.rast = rast def test_transform_core(): # Define the transform query for both the geometry and the raster in a naive way wrong_query = select([ func.ST_Transform(table.c.geom, 2154), func.ST_Transform(table.c.rast, 2154) ]) # Check the query assert str(wrong_query) == ( "SELECT " "ST_AsEWKB(" "ST_Transform(raster_table.geom, :ST_Transform_2)) AS \"ST_Transform_1\", " "ST_AsEWKB(" # <= Note that the raster is processed as a Geometry here "ST_Transform(raster_table.rast, :ST_Transform_4)) AS \"ST_Transform_3\" \n" "FROM raster_table" ) # Define the transform query for both the geometry and the raster in the correct way correct_query = select([ func.ST_Transform(table.c.geom, 2154), func.ST_Transform(table.c.rast, 2154, type_=Raster) ]) # Check the query assert str(correct_query) == ( "SELECT " "ST_AsEWKB(" "ST_Transform(raster_table.geom, :ST_Transform_2)) AS \"ST_Transform_1\", " "raster(" # <= This time the raster is correctly processed as a Raster "ST_Transform(raster_table.rast, :ST_Transform_4)) AS \"ST_Transform_3\" \n" "FROM raster_table" ) def test_transform_ORM(): # Define the transform query for both the geometry and the raster in a naive way wrong_query = Query([ RasterTable.geom.ST_Transform(2154), RasterTable.rast.ST_Transform(2154) ]) # Check the query assert str(wrong_query) == ( "SELECT " "ST_AsEWKB(" "ST_Transform(raster_table_orm.geom, :ST_Transform_2)) AS \"ST_Transform_1\", " "ST_AsEWKB(" # <= Note that the raster is processed as a Geometry here "ST_Transform(raster_table_orm.rast, :ST_Transform_4)) AS \"ST_Transform_3\" \n" "FROM raster_table_orm" ) # Define the transform query for both the geometry and the raster in the correct way correct_query = Query([ RasterTable.geom.ST_Transform(2154), RasterTable.rast.ST_Transform(2154, type_=Raster) ]) # Check the query assert str(correct_query) == ( "SELECT " "ST_AsEWKB(" "ST_Transform(raster_table_orm.geom, :ST_Transform_2)) AS \"ST_Transform_1\", " "raster(" # <= This time the raster is correctly processed as a Raster "ST_Transform(raster_table_orm.rast, :ST_Transform_4)) AS \"ST_Transform_3\" \n" "FROM raster_table_orm" ) |
Note
Click here to download the full example code
Use CompositeType¶
Some functions return composite types. This example shows how to deal with this kind of functions.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | import pytest from pkg_resources import parse_version from sqlalchemy import Column from sqlalchemy import Float from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import __version__ as SA_VERSION from sqlalchemy.ext.declarative import declarative_base from geoalchemy2 import Raster from geoalchemy2 import WKTElement from geoalchemy2.functions import GenericFunction from geoalchemy2.types import CompositeType # Tests imports from tests import select from tests import test_only_with_dialects class SummaryStatsCustomType(CompositeType): """Define the composite type returned by the function ST_SummaryStatsAgg.""" typemap = { 'count': Integer, 'sum': Float, 'mean': Float, 'stddev': Float, 'min': Float, 'max': Float, } cache_ok = True class ST_SummaryStatsAgg(GenericFunction): type = SummaryStatsCustomType # Set a specific identifier to not override the actual ST_SummaryStatsAgg function identifier = "ST_SummaryStatsAgg_custom" inherit_cache = True metadata = MetaData() Base = declarative_base(metadata=metadata) class Ocean(Base): __tablename__ = 'ocean' id = Column(Integer, primary_key=True) rast = Column(Raster) def __init__(self, rast): self.rast = rast @test_only_with_dialects("postgresql") class TestSTSummaryStatsAgg(): @pytest.mark.skipif( parse_version(SA_VERSION) < parse_version("1.4"), reason="requires SQLAlchely>1.4", ) def test_st_summary_stats_agg(self, session, conn): metadata.drop_all(conn, checkfirst=True) metadata.create_all(conn) # Create a new raster polygon = WKTElement('POLYGON((0 0,1 1,0 1,0 0))', srid=4326) o = Ocean(polygon.ST_AsRaster(5, 6)) session.add(o) session.flush() # Define the query to compute stats stats_agg = select([ Ocean.rast.ST_SummaryStatsAgg_custom(1, True, 1).label("stats") ]) stats_agg_alias = stats_agg.alias("stats_agg") # Use these stats query = select([ stats_agg_alias.c.stats.count.label("count"), stats_agg_alias.c.stats.sum.label("sum"), stats_agg_alias.c.stats.mean.label("mean"), stats_agg_alias.c.stats.stddev.label("stddev"), stats_agg_alias.c.stats.min.label("min"), stats_agg_alias.c.stats.max.label("max") ]) # Check the query assert str(query.compile(dialect=session.bind.dialect)) == ( "SELECT " "(stats_agg.stats).count AS count, " "(stats_agg.stats).sum AS sum, " "(stats_agg.stats).mean AS mean, " "(stats_agg.stats).stddev AS stddev, " "(stats_agg.stats).min AS min, " "(stats_agg.stats).max AS max \n" "FROM (" "SELECT " "ST_SummaryStatsAgg(" "ocean.rast, " "%(ST_SummaryStatsAgg_1)s, %(ST_SummaryStatsAgg_2)s, %(ST_SummaryStatsAgg_3)s" ") AS stats \n" "FROM ocean) AS stats_agg" ) # Execute the query res = session.execute(query).fetchall() # Check the result assert res == [(15, 15.0, 1.0, 0.0, 1.0, 1.0)] |
The Gallery page shows examples of the GeoAlchemy 2’s functionalities.
Use with Alembic¶
Use Alembic with GeoAlchemy 2¶
The Alembic package is a lightweight database migration tool which is able to automatically detect the table column types.
Interactions between Alembic and GeoAlchemy 2¶
Interactions between some features of Alembic and GeoAlchemy 2 may lead to errors in migration
scripts, especially when using the --autogenerate
feature of Alembic with the
spatial_index=True
feature of GeoAlchemy 2. In this case, the following errors occur:
- the migration script miss the relevant imports from
geoalchemy2
. - the migration script will create the indexes of the spatial columns after the table is created, but these indexes are already automatically created during table creation, which will lead to an error.
For example, suppose the following table is defined:
class Lake(Base):
__tablename__ = 'lake'
id = Column(Integer, primary_key=True)
geom = Column(
Geometry(
geometry_type='LINESTRING',
srid=4326,
spatial_index=True,
)
)
Then the command alembic revision --autogenerate -m "Create new table"
will create the
following migration script:
"""Create new table
Revision ID: <rev_id>
Revises: <down_rev_id>
Create Date: <date>
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "<rev_id>"
down_revision = "<down_rev_id>"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"lake",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column(
"geom",
geoalchemy2.types.Geometry(
geometry_type="LINESTRING",
srid=4326,
from_text="ST_GeomFromEWKT",
name="geometry",
),
nullable=True,
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
"idx_lake_geom",
"lake",
["geom"],
unique=False,
postgresql_using="gist",
postgresql_ops={},
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(
"idx_lake_geom",
table_name="lake",
postgresql_using="gist",
postgresql_ops={},
)
op.drop_table("lake")
# ### end Alembic commands ###
In this case, we have to do the following changes to make it work:
- add the missing import
from geoalchemy2 import Geometry
. - remove the
create_index
statement in theupgrade()
function. - remove the
drop_index
statement in thedowngrade()
function.
Helpers¶
In order to make the use of Alembic easier, a few helpers are provided in
geoalchemy2.alembic_helpers. These helpers can be used in the env.py
file used by Alembic, like in the following example:
# ...
from geoalchemy2.alembic_helpers import include_object
from geoalchemy2.alembic_helpers import render_item
# ...
def run_migrations_offline():
# ...
context.configure(
# ...
process_revision_directives=alembic_helpers.writer,
render_item=alembic_helpers.render_item,
)
# ...
def run_migrations_online():
# ...
context.configure(
# ...
process_revision_directives=alembic_helpers.writer,
render_item=alembic_helpers.render_item,
)
# ...
After running the alembic
command, the migration script should be properly generated and should
not need to be manually edited.
Dealing with custom types¶
With SQLAlchemy
, users are able to define custom types, as shown in
Automatically use a function at insert or select. In this case, you can refer to the
dedicated page of Alembic’s documentation
for the details.
A simple solution for this case is to create a new render_item
function to add specific imports
for these custom types. For example, if your custom type is called TheCustomType
and is defined
in my_package.custom_types
, you just have to edit the env.py
file like the following:
# ...
from geoalchemy2.alembic_helpers import include_object
from geoalchemy2.alembic_helpers import render_item as spatial_render_item
from my_package.custom_types import TheCustomType
# ...
def render_item(obj_type, obj, autogen_context):
"""Apply custom rendering for selected items."""
spatial_type = spatial_render_item(obj_type, obj, autogen_context)
if spatial_type:
return spatial_type
# For the custom type
if obj_type == 'type' and isinstance(obj, TheCustomType):
import_name = obj.__class__.__name__
autogen_context.imports.add(f"from my_package.custom_types import {import_name}")
return "%r" % obj
# default rendering for other objects
return False
def run_migrations_offline():
# ...
context.configure(
# ...
process_revision_directives=alembic_helpers.writer,
render_item=render_item,
)
# ...
def run_migrations_online():
# ...
context.configure(
# ...
process_revision_directives=alembic_helpers.writer,
render_item=render_item,
)
# ...
Then the proper imports will be automatically added in the migration scripts.
Dialects¶
Some dialects (like SQLite) require some specific management to alter columns or tables. In this
case, other dedicated helpers are provided to handle this. For example, if one wants to add and drop
columns in a SQLite database, the SpatiaLite extension should be loaded when the engine connects,
thus the env.py
file should look like the following:
from geoalchemy2.alembic_helpers import load_spatialite
from geoalchemy2.alembic_helpers import writer
def run_migrations_offline():
# ...
context.configure(
# ...
process_revision_directives=writer,
render_item=alembic_helpers.render_item,
)
# ...
def run_migrations_online():
# ...
if connectable.dialect.name == "sqlite":
# Load the SpatiaLite extension when the engine connects to the DB
listen(connectable, 'connect', load_spatialite)
with connectable.connect() as connection:
# ...
context.configure(
# ...
process_revision_directives=writer,
render_item=alembic_helpers.render_item,
)
# ...
The GeoAlchemy 2 package is compatible with the migration tool Alembic. The Use Alembic with GeoAlchemy 2 page provides more details on this topic.
Reference Documentation¶
Types¶
This module defines the geoalchemy2.types.Geometry
,
geoalchemy2.types.Geography
, and geoalchemy2.types.Raster
classes, that are used when defining geometry, geography and raster
columns/properties in models.
Reference¶
-
class
geoalchemy2.types.
CompositeType
[source]¶ Bases:
sqlalchemy.sql.type_api.UserDefinedType
A wrapper for
geoalchemy2.elements.CompositeElement
, that can be used as the return type in PostgreSQL functions that return composite values.This is used as the base class of
geoalchemy2.types.GeometryDump
.-
typemap
= {}¶ Dictionary used for defining the content types and their corresponding keys. Set in subclasses.
-
-
class
geoalchemy2.types.
Geography
(geometry_type='GEOMETRY', srid=-1, dimension=2, spatial_index=True, use_N_D_index=False, management=False, use_typmod=None, from_text=None, name=None, nullable=True, _spatial_index_reflected=None)[source]¶ Bases:
geoalchemy2.types._GISType
The Geography type.
Creating a geography column is done like this:
Column(Geography(geometry_type='POINT', srid=4326))
See
geoalchemy2.types._GISType
for the list of arguments that can be passed to the constructor.-
ElementType
¶ alias of
geoalchemy2.elements.WKBElement
-
as_binary
= 'ST_AsBinary'¶ The “as binary” function to use. Used by the parent class’
column_expression
method.
-
cache_ok
= False¶ Disable cache for this type.
-
from_text
= 'ST_GeogFromText'¶ The
FromText
geography constructor. Used by the parent class’bind_expression
method.
-
name
= 'geography'¶ Type name used for defining geography columns in
CREATE TABLE
.
-
-
class
geoalchemy2.types.
Geometry
(geometry_type='GEOMETRY', srid=-1, dimension=2, spatial_index=True, use_N_D_index=False, management=False, use_typmod=None, from_text=None, name=None, nullable=True, _spatial_index_reflected=None)[source]¶ Bases:
geoalchemy2.types._GISType
The Geometry type.
Creating a geometry column is done like this:
Column(Geometry(geometry_type='POINT', srid=4326))
See
geoalchemy2.types._GISType
for the list of arguments that can be passed to the constructor.If
srid
is set then theWKBElement
objects resulting from queries will have that SRID, and, when constructing theWKBElement
objects, the SRID won’t be read from the data returned by the database. Ifsrid
is not set (meaning it’s-1
) then the SRID set inWKBElement
objects will be read from the data returned by the database.-
ElementType
¶ alias of
geoalchemy2.elements.WKBElement
-
as_binary
= 'ST_AsEWKB'¶ The “as binary” function to use. Used by the parent class’
column_expression
method.
-
cache_ok
= False¶ Disable cache for this type.
-
from_text
= 'ST_GeomFromEWKT'¶ The “from text” geometry constructor. Used by the parent class’
bind_expression
method.
-
name
= 'geometry'¶ Type name used for defining geometry columns in
CREATE TABLE
.
-
-
class
geoalchemy2.types.
GeometryDump
[source]¶ Bases:
geoalchemy2.types.CompositeType
The return type for functions like
ST_Dump
, consisting of a path and a geom field. You should normally never use this class directly.-
cache_ok
= True¶ Enable cache for this type.
-
typemap
= {'geom': <class 'geoalchemy2.types.Geometry'>, 'path': ARRAY(Integer())}¶ Dictionary defining the contents of a
geometry_dump
.
-
-
class
geoalchemy2.types.
Raster
(spatial_index=True, from_text=None, name=None, nullable=True)[source]¶ Bases:
geoalchemy2.types._GISType
The Raster column type.
Creating a raster column is done like this:
Column(Raster)
This class defines the
result_processor
method, so that raster values received from the database are converted togeoalchemy2.elements.RasterElement
objects.Parameters: spatial_index – Indicate if a spatial index should be created. Default is True
.-
ElementType
¶ alias of
geoalchemy2.elements.RasterElement
-
as_binary
= 'raster'¶ The “as binary” function to use. Used by the parent class’
column_expression
method.
-
cache_ok
= False¶ Disable cache for this type.
-
comparator_factory
¶
-
from_text
= 'raster'¶ The “from text” raster constructor. Used by the parent class’
bind_expression
method.
-
name
= 'raster'¶ Type name used for defining raster columns in
CREATE TABLE
.
-
-
class
geoalchemy2.types.
SummaryStats
[source]¶ Bases:
geoalchemy2.types.CompositeType
Define the composite type returned by the function ST_SummaryStatsAgg
-
cache_ok
= True¶ Enable cache for this type.
-
-
class
geoalchemy2.types.
_DummyGeometry
(geometry_type='GEOMETRY', srid=-1, dimension=2, spatial_index=True, use_N_D_index=False, management=False, use_typmod=None, from_text=None, name=None, nullable=True, _spatial_index_reflected=None)[source]¶ Bases:
geoalchemy2.types.Geometry
A dummy type only used with SQLite.
-
class
geoalchemy2.types.
_GISType
(geometry_type='GEOMETRY', srid=-1, dimension=2, spatial_index=True, use_N_D_index=False, management=False, use_typmod=None, from_text=None, name=None, nullable=True, _spatial_index_reflected=None)[source]¶ Bases:
sqlalchemy.sql.type_api.UserDefinedType
The base class for
geoalchemy2.types.Geometry
andgeoalchemy2.types.Geography
.This class defines
bind_expression
andcolumn_expression
methods that wrap column expressions inST_GeomFromEWKT
,ST_GeogFromText
, orST_AsEWKB
calls.This class also defines
result_processor
andbind_processor
methods. The function returned byresult_processor
converts WKB values received from the database togeoalchemy2.elements.WKBElement
objects. The function returned bybind_processor
convertsgeoalchemy2.elements.WKTElement
objects to EWKT strings.Parameters: - geometry_type –
The geometry type.
Possible values are:"GEOMETRY"
,"POINT"
,"LINESTRING"
,"POLYGON"
,"MULTIPOINT"
,"MULTILINESTRING"
,"MULTIPOLYGON"
,"GEOMETRYCOLLECTION"
,"CURVE"
,None
.
The latter is actually not supported with
geoalchemy2.types.Geography
.When set to
None
then no “geometry type” constraints will be attached to the geometry type declaration. UsingNone
here is not compatible with settingmanagement
toTrue
.Default is
"GEOMETRY"
. - srid – The SRID for this column. E.g. 4326. Default is
-1
. - dimension –
The dimension of the geometry. Default is
2
.With
management
set toTrue
, that is whenAddGeometryColumn
is used to add the geometry column, there are two constraints:- The
geometry_type
must not end with"ZM"
. This is due to PostGIS’AddGeometryColumn
failing with ZM geometry types. Instead the “simple” geometry type (e.g. POINT rather POINTZM) should be used withdimension
set to4
. - When the
geometry_type
ends with"Z"
or"M"
thendimension
must be set to3
.
With
management
set toFalse
(the default)dimension
is not taken into account, and the actual dimension is fully defined with thegeometry_type
. - The
- spatial_index – Indicate if a spatial index should be created. Default is
True
. - use_N_D_index – Use the N-D index instead of the standard 2-D index.
- management – Indicate if the
AddGeometryColumn
andDropGeometryColumn
managements functions should be called when adding and dropping the geometry column. Should be set toTrue
for PostGIS 1.x and SQLite. Default isFalse
. Note that this option has no effect forgeoalchemy2.types.Geography
. - use_typmod – By default PostgreSQL type modifiers are used to create the geometry
column. To use check constraints instead set
use_typmod
toFalse
. By default this option is not included in the call toAddGeometryColumn
. Note that this option is only taken into account ifmanagement
is set toTrue
and is only available for PostGIS 2.x.
-
as_binary
= None¶ The name of the “as binary” function for this type. Set in subclasses.
-
bind_expression
(bindvalue)[source]¶ Specific bind_expression that automatically adds a conversion function
-
bind_processor
(dialect)[source]¶ Specific bind_processor that automatically process spatial elements
-
cache_ok
= False¶ Disable cache for this type.
-
column_expression
(col)[source]¶ Specific column_expression that automatically adds a conversion function
-
comparator_factory
¶ alias of
geoalchemy2.comparator.Comparator
-
from_text
= None¶ The name of “from text” function for this type. Set in subclasses.
-
name
= None¶ Name used for defining the main geo type (geometry or geography) in CREATE TABLE statements. Set in subclasses.
- geometry_type –
Elements¶
-
class
geoalchemy2.elements.
HasFunction
[source]¶ Bases:
object
Base class used as a marker to know if a given element has a ‘geom_from’ function.
-
class
geoalchemy2.elements.
_SpatialElement
(data, srid=-1, extended=False)[source]¶ Bases:
geoalchemy2.elements.HasFunction
The base class for public spatial elements.
Parameters: - data – The first argument passed to the constructor is the data wrapped
by the
_SpatialElement
object being constructed. - srid – An integer representing the spatial reference system. E.g.
4326
. Default value is-1
, which means no/unknown reference system. - extended – A boolean indicating whether the extended format (EWKT or EWKB)
is used. Default is
False
.
- data – The first argument passed to the constructor is the data wrapped
by the
-
class
geoalchemy2.elements.
WKTElement
(data, srid=-1, extended=False)[source]¶ Bases:
geoalchemy2.elements._SpatialElement
Instances of this class wrap a WKT or EWKT value.
Usage examples:
wkt_element_1 = WKTElement('POINT(5 45)') wkt_element_2 = WKTElement('POINT(5 45)', srid=4326) wkt_element_3 = WKTElement('SRID=4326;POINT(5 45)', extended=True)
-
desc
¶ This element’s description string.
-
geom_from
= 'ST_GeomFromText'¶
-
geom_from_extended_version
= 'ST_GeomFromEWKT'¶
-
-
class
geoalchemy2.elements.
WKBElement
(data, srid=-1, extended=False)[source]¶ Bases:
geoalchemy2.elements._SpatialElement
Instances of this class wrap a WKB or EWKB value.
Geometry values read from the database are converted to instances of this type. In most cases you won’t need to create
WKBElement
instances yourself.If
extended
isTrue
andsrid
is-1
at construction time then the SRID will be read from the EWKB data.Note: you can create
WKBElement
objects from Shapely geometries using thegeoalchemy2.shape.from_shape()
function.-
desc
¶ This element’s description string.
-
geom_from
= 'ST_GeomFromWKB'¶
-
geom_from_extended_version
= 'ST_GeomFromEWKB'¶
-
-
class
geoalchemy2.elements.
RasterElement
(data)[source]¶ Bases:
geoalchemy2.elements._SpatialElement
Instances of this class wrap a
raster
value. Raster values read from the database are converted to instances of this type. In most cases you won’t need to createRasterElement
instances yourself.-
desc
¶ This element’s description string.
-
Spatial Functions¶
This module defines the GenericFunction
class, which is the base for
the implementation of spatial functions in GeoAlchemy. This module is also
where actual spatial functions are defined. Spatial functions supported by
GeoAlchemy are defined in this module. See GenericFunction
to know how
to create new spatial functions.
Note
By convention the names of spatial functions are prefixed by ST_
. This
is to be consistent with PostGIS’, which itself is based on the SQL-MM
standard.
Functions created by subclassing GenericFunction
can be called
in several ways:
By using the
func
object, which is the SQLAlchemy standard way of calling a function. For example, without the ORM:select([func.ST_Area(lake_table.c.geom)])
and with the ORM:
Session.query(func.ST_Area(Lake.geom))
By applying the function to a geometry column. For example, without the ORM:
select([lake_table.c.geom.ST_Area()])
and with the ORM:
Session.query(Lake.geom.ST_Area())
By applying the function to a
geoalchemy2.elements.WKBElement
object (geoalchemy2.elements.WKBElement
is the type into which GeoAlchemy converts geometry values read from the database), or to ageoalchemy2.elements.WKTElement
object. For example, without the ORM:conn.scalar(lake['geom'].ST_Area())
and with the ORM:
session.scalar(lake.geom.ST_Area())
Warning
A few functions (like ST_Transform(), ST_Union(), ST_SnapToGrid(), …) can be used on
several spatial types (geoalchemy2.types.Geometry
,
geoalchemy2.types.Geography
and / or geoalchemy2.types.Raster
types). In
GeoAlchemy2, these functions are only defined for the geoalchemy2.types.Geometry
type,
as it can not be defined for several types at the same time. Therefore, using these functions on
geoalchemy2.types.Geography
or geoalchemy2.types.Raster
requires minor
tweaking to enforce the type by passing the type_=Geography or type_=Raster argument to the
function:
s = select([func.ST_Transform(
lake_table.c.raster,
2154,
type_=Raster)
.label('transformed_raster')])
Reference¶
-
class
geoalchemy2.functions.
AddAuth
(*args, **kwargs)¶ Adds an authorization token to be used in the current transaction.
-
class
geoalchemy2.functions.
AddGeometryColumn
(*args, **kwargs)¶ Adds a geometry column to an existing table.
-
class
geoalchemy2.functions.
Box2D
(*args, **kwargs)¶ Returns a BOX2D representing the 2D extent of the geometry.
-
class
geoalchemy2.functions.
Box3D
(*args, **kwargs)¶ [geometry] Returns a BOX3D representing the 3D extent of the geometry. OR [raster] Returns the box 3d representation of the enclosing box of the raster.
-
class
geoalchemy2.functions.
CheckAuth
(*args, **kwargs)¶ Creates a trigger on a table to prevent/allow updates and deletes of rows based on authorization token.
-
class
geoalchemy2.functions.
DisableLongTransactions
(*args, **kwargs)¶ Disables long transaction support.
-
class
geoalchemy2.functions.
DropGeometryColumn
(*args, **kwargs)¶ Removes a geometry column from a spatial table.
-
class
geoalchemy2.functions.
DropGeometryTable
(*args, **kwargs)¶ Drops a table and all its references in geometry_columns.
-
class
geoalchemy2.functions.
EnableLongTransactions
(*args, **kwargs)¶ Enables long transaction support.
-
class
geoalchemy2.functions.
Find_SRID
(*args, **kwargs)¶ Returns the SRID defined for a geometry column.
-
class
geoalchemy2.functions.
GenericFunction
(*args, **kwargs)[source]¶ The base class for GeoAlchemy functions.
This class inherits from
sqlalchemy.sql.functions.GenericFunction
, so functions defined by subclassing this class can be given a fixed return type. For example, functions likeST_Buffer
andST_Envelope
have theirtype
attributes set togeoalchemy2.types.Geometry
.This class allows constructs like
Lake.geom.ST_Buffer(2)
. In that case theFunction
instance is bound to an expression (Lake.geom
here), and that expression is passed to the function when the function is actually called.If you need to use a function that GeoAlchemy does not provide you will certainly want to subclass this class. For example, if you need the
ST_TransScale
spatial function, which isn’t (currently) natively supported by GeoAlchemy, you will write this:from geoalchemy2 import Geometry from geoalchemy2.functions import GenericFunction class ST_TransScale(GenericFunction): name = 'ST_TransScale' type = Geometry
-
class
geoalchemy2.functions.
GeometryType
(*args, **kwargs)¶ Returns the type of a geometry as text.
-
class
geoalchemy2.functions.
LockRow
(*args, **kwargs)¶ Sets lock/authorization for a row in a table.
-
class
geoalchemy2.functions.
Populate_Geometry_Columns
(*args, **kwargs)¶ Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
-
class
geoalchemy2.functions.
PostGIS_AddBBox
(*args, **kwargs)¶ Add bounding box to the geometry.
see http://postgis.net/docs/PostGIS_AddBBox.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
PostGIS_DropBBox
(*args, **kwargs)¶ Drop the bounding box cache from the geometry.
see http://postgis.net/docs/PostGIS_DropBBox.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
PostGIS_Extensions_Upgrade
(*args, **kwargs)¶ Packages and upgrades postgis extensions (e.g. postgis_raster, postgis_topology, postgis_sfcgal) to latest available version.
-
class
geoalchemy2.functions.
PostGIS_Full_Version
(*args, **kwargs)¶ Reports full postgis version and build configuration infos.
-
class
geoalchemy2.functions.
PostGIS_GEOS_Version
(*args, **kwargs)¶ Returns the version number of the GEOS library.
-
class
geoalchemy2.functions.
PostGIS_HasBBox
(*args, **kwargs)¶ Returns TRUE if the bbox of this geometry is cached, FALSE otherwise.
-
class
geoalchemy2.functions.
PostGIS_LibXML_Version
(*args, **kwargs)¶ Returns the version number of the libxml2 library.
-
class
geoalchemy2.functions.
PostGIS_Lib_Build_Date
(*args, **kwargs)¶ Returns build date of the PostGIS library.
-
class
geoalchemy2.functions.
PostGIS_Lib_Version
(*args, **kwargs)¶ Returns the version number of the PostGIS library.
-
class
geoalchemy2.functions.
PostGIS_Liblwgeom_Version
(*args, **kwargs)¶ Returns the version number of the liblwgeom library. This should match the version of PostGIS.
-
class
geoalchemy2.functions.
PostGIS_PROJ_Version
(*args, **kwargs)¶ Returns the version number of the PROJ4 library.
-
class
geoalchemy2.functions.
PostGIS_Scripts_Build_Date
(*args, **kwargs)¶ Returns build date of the PostGIS scripts.
-
class
geoalchemy2.functions.
PostGIS_Scripts_Installed
(*args, **kwargs)¶ Returns version of the postgis scripts installed in this database.
-
class
geoalchemy2.functions.
PostGIS_Scripts_Released
(*args, **kwargs)¶ Returns the version number of the postgis.sql script released with the installed postgis lib.
-
class
geoalchemy2.functions.
PostGIS_Version
(*args, **kwargs)¶ Returns PostGIS version number and compile-time options.
-
class
geoalchemy2.functions.
PostGIS_Wagyu_Version
(*args, **kwargs)¶ Returns the version number of the internal Wagyu library.
-
class
geoalchemy2.functions.
ST_3DArea
(*args, **kwargs)¶ Computes area of 3D surface geometries. Will return 0 for solids.
-
class
geoalchemy2.functions.
ST_3DClosestPoint
(*args, **kwargs)¶ Returns the 3D point on g1 that is closest to g2. This is the first point of the 3D shortest line.
see http://postgis.net/docs/ST_3DClosestPoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_3DDFullyWithin
(*args, **kwargs)¶ Returns true if all of the 3D geometries are within the specified distance of one another.
-
class
geoalchemy2.functions.
ST_3DDWithin
(*args, **kwargs)¶ For 3d (z) geometry type Returns true if two geometries 3d distance is within number of units.
-
class
geoalchemy2.functions.
ST_3DDifference
(*args, **kwargs)¶ Perform 3D difference
see http://postgis.net/docs/ST_3DDifference.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_3DDistance
(*args, **kwargs)¶ Returns the 3D cartesian minimum distance (based on spatial ref) between two geometries in projected units.
-
class
geoalchemy2.functions.
ST_3DExtent
(*args, **kwargs)¶ an aggregate function that returns the 3D bounding box that bounds rows of geometries.
-
class
geoalchemy2.functions.
ST_3DIntersection
(*args, **kwargs)¶ Perform 3D intersection
see http://postgis.net/docs/ST_3DIntersection.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_3DIntersects
(*args, **kwargs)¶ Returns TRUE if the Geometries “spatially intersect” in 3D - only for points, linestrings, polygons, polyhedral surface (area).
-
class
geoalchemy2.functions.
ST_3DLength
(*args, **kwargs)¶ Returns the 3D length of a linear geometry.
-
class
geoalchemy2.functions.
ST_3DLineInterpolatePoint
(*args, **kwargs)¶ Returns a point interpolated along a line in 3D. Second argument is a float8 between 0 and 1 representing fraction of total length of linestring the point has to be located.
see http://postgis.net/docs/ST_3DLineInterpolatePoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_3DLongestLine
(*args, **kwargs)¶ Returns the 3D longest line between two geometries
see http://postgis.net/docs/ST_3DLongestLine.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_3DMakeBox
(*args, **kwargs)¶ Creates a BOX3D defined by two 3D point geometries.
-
class
geoalchemy2.functions.
ST_3DMaxDistance
(*args, **kwargs)¶ Returns the 3D cartesian maximum distance (based on spatial ref) between two geometries in projected units.
-
class
geoalchemy2.functions.
ST_3DPerimeter
(*args, **kwargs)¶ Returns the 3D perimeter of a polygonal geometry.
-
class
geoalchemy2.functions.
ST_3DShortestLine
(*args, **kwargs)¶ Returns the 3D shortest line between two geometries
see http://postgis.net/docs/ST_3DShortestLine.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_3DUnion
(*args, **kwargs)¶ Perform 3D union
see http://postgis.net/docs/ST_3DUnion.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_AddBand
(*args, **kwargs)¶ Returns a raster with the new band(s) of given type added with given initial value in the given index location. If no index is specified, the band is added to the end.
see http://postgis.net/docs/RT_ST_AddBand.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_AddMeasure
(*args, **kwargs)¶ Return a derived geometry with measure elements linearly interpolated between the start and end points.
see http://postgis.net/docs/ST_AddMeasure.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_AddPoint
(*args, **kwargs)¶ Add a point to a LineString.
see http://postgis.net/docs/ST_AddPoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Affine
(*args, **kwargs)¶ Apply a 3D affine transformation to a geometry.
see http://postgis.net/docs/ST_Affine.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Angle
(*args, **kwargs)¶ Returns the angle between 3 points, or between 2 vectors (4 points or 2 lines).
-
class
geoalchemy2.functions.
ST_ApproximateMedialAxis
(*args, **kwargs)¶ Compute the approximate medial axis of an areal geometry.
see http://postgis.net/docs/ST_ApproximateMedialAxis.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Area
(*args, **kwargs)¶ Returns the area of a polygonal geometry.
-
class
geoalchemy2.functions.
ST_AsBinary
(*args, **kwargs)¶ [gometry] Return the Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data. OR [raster] Return the Well-Known Binary (WKB) representation of the raster.
-
class
geoalchemy2.functions.
ST_AsEWKB
(*args, **kwargs)¶ Return the Well-Known Binary (WKB) representation of the geometry with SRID meta data.
-
class
geoalchemy2.functions.
ST_AsEWKT
(*args, **kwargs)¶ Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.
-
class
geoalchemy2.functions.
ST_AsEncodedPolyline
(*args, **kwargs)¶ Returns an Encoded Polyline from a LineString geometry.
-
class
geoalchemy2.functions.
ST_AsGDALRaster
(*args, **kwargs)¶ Return the raster tile in the designated GDAL Raster format. Raster formats are one of those supported by your compiled library. Use ST_GDALDrivers() to get a list of formats supported by your library.
-
class
geoalchemy2.functions.
ST_AsGML
(*args, **kwargs)¶ Return the geometry as a GML version 2 or 3 element.
-
class
geoalchemy2.functions.
ST_AsGeoJSON
(*args, **kwargs)[source]¶ Return the geometry as a GeoJSON “geometry” object, or the row as a GeoJSON feature” object (PostGIS 3 only). (Cf GeoJSON specifications RFC 7946). 2D and 3D Geometries are both supported. GeoJSON only support SFS 1.1 geometry types (no curve support for example). See https://postgis.net/docs/ST_AsGeoJSON.html
-
class
geoalchemy2.functions.
ST_AsGeobuf
(*args, **kwargs)¶ Return a Geobuf representation of a set of rows.
-
class
geoalchemy2.functions.
ST_AsHEXEWKB
(*args, **kwargs)¶ Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding.
-
class
geoalchemy2.functions.
ST_AsHexWKB
(*args, **kwargs)¶ Return the Well-Known Binary (WKB) in Hex representation of the raster.
-
class
geoalchemy2.functions.
ST_AsJPEG
(*args, **kwargs)¶ Return the raster tile selected bands as a single Joint Photographic Exports Group (JPEG) image (byte array). If no band is specified and 1 or more than 3 bands, then only the first band is used. If only 3 bands then all 3 bands are used and mapped to RGB.
-
class
geoalchemy2.functions.
ST_AsKML
(*args, **kwargs)¶ Return the geometry as a KML element. Several variants. Default version=2, default maxdecimaldigits=15
-
class
geoalchemy2.functions.
ST_AsLatLonText
(*args, **kwargs)¶ Return the Degrees, Minutes, Seconds representation of the given point.
-
class
geoalchemy2.functions.
ST_AsMVT
(*args, **kwargs)¶ Aggregate function returning a Mapbox Vector Tile representation of a set of rows.
-
class
geoalchemy2.functions.
ST_AsMVTGeom
(*args, **kwargs)¶ Transform a geometry into the coordinate space of a Mapbox Vector Tile.
see http://postgis.net/docs/ST_AsMVTGeom.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_AsPNG
(*args, **kwargs)¶ Return the raster tile selected bands as a single portable network graphics (PNG) image (byte array). If 1, 3, or 4 bands in raster and no bands are specified, then all bands are used. If more 2 or more than 4 bands and no bands specified, then only band 1 is used. Bands are mapped to RGB or RGBA space.
-
class
geoalchemy2.functions.
ST_AsRaster
(*args, **kwargs)¶ Converts a PostGIS geometry to a PostGIS raster.
see http://postgis.net/docs/RT_ST_AsRaster.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_AsSVG
(*args, **kwargs)¶ Returns SVG path data for a geometry.
-
class
geoalchemy2.functions.
ST_AsTIFF
(*args, **kwargs)¶ Return the raster selected bands as a single TIFF image (byte array). If no band is specified or any of specified bands does not exist in the raster, then will try to use all bands.
-
class
geoalchemy2.functions.
ST_AsTWKB
(*args, **kwargs)¶ Returns the geometry as TWKB, aka “Tiny Well-Known Binary”
-
class
geoalchemy2.functions.
ST_AsText
(*args, **kwargs)¶ Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.
-
class
geoalchemy2.functions.
ST_AsWKB
(*args, **kwargs)¶ Return the Well-Known Binary (WKB) representation of the raster.
-
class
geoalchemy2.functions.
ST_AsX3D
(*args, **kwargs)¶ Returns a Geometry in X3D xml node element format: ISO-IEC-19776-1.2-X3DEncodings-XML
-
class
geoalchemy2.functions.
ST_Aspect
(*args, **kwargs)¶ Returns the aspect (in degrees by default) of an elevation raster band. Useful for analyzing terrain.
see http://postgis.net/docs/RT_ST_Aspect.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Azimuth
(*args, **kwargs)¶ Returns the north-based azimuth as the angle in radians measured clockwise from the vertical on pointA to pointB.
-
class
geoalchemy2.functions.
ST_Band
(*args, **kwargs)¶ Returns one or more bands of an existing raster as a new raster. Useful for building new rasters from existing rasters.
see http://postgis.net/docs/RT_ST_Band.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_BandFileSize
(*args, **kwargs)¶ Returns the file size of a band stored in file system. If no bandnum specified, 1 is assumed.
-
class
geoalchemy2.functions.
ST_BandFileTimestamp
(*args, **kwargs)¶ Returns the file timestamp of a band stored in file system. If no bandnum specified, 1 is assumed.
-
class
geoalchemy2.functions.
ST_BandIsNoData
(*args, **kwargs)¶ Returns true if the band is filled with only nodata values.
-
class
geoalchemy2.functions.
ST_BandMetaData
(*args, **kwargs)¶ Returns basic meta data for a specific raster band. band num 1 is assumed if none-specified.
-
class
geoalchemy2.functions.
ST_BandNoDataValue
(*args, **kwargs)¶ Returns the value in a given band that represents no data. If no band num 1 is assumed.
-
class
geoalchemy2.functions.
ST_BandPath
(*args, **kwargs)¶ Returns system file path to a band stored in file system. If no bandnum specified, 1 is assumed.
-
class
geoalchemy2.functions.
ST_BandPixelType
(*args, **kwargs)¶ Returns the type of pixel for given band. If no bandnum specified, 1 is assumed.
-
class
geoalchemy2.functions.
ST_BdMPolyFromText
(*args, **kwargs)¶ Construct a MultiPolygon given an arbitrary collection of closed linestrings as a MultiLineString text representation Well-Known text representation.
see http://postgis.net/docs/ST_BdMPolyFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_BdPolyFromText
(*args, **kwargs)¶ Construct a Polygon given an arbitrary collection of closed linestrings as a MultiLineString Well-Known text representation.
see http://postgis.net/docs/ST_BdPolyFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Boundary
(*args, **kwargs)¶ Returns the boundary of a geometry.
see http://postgis.net/docs/ST_Boundary.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_BoundingDiagonal
(*args, **kwargs)¶ Returns the diagonal of a geometry’s bounding box.
see http://postgis.net/docs/ST_BoundingDiagonal.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Box2dFromGeoHash
(*args, **kwargs)¶ Return a BOX2D from a GeoHash string.
-
class
geoalchemy2.functions.
ST_Buffer
(*args, **kwargs)¶ - Returns a geometry covering all points within a given distance from the input geometry.
see http://postgis.net/docs/ST_Buffer.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
class
geoalchemy2.functions.
ST_BuildArea
(*args, **kwargs)¶ Creates an areal geometry formed by the constituent linework of given geometry
see http://postgis.net/docs/ST_BuildArea.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_CPAWithin
(*args, **kwargs)¶ Returns true if the closest point of approach of two trajectories is within the specified distance.
-
class
geoalchemy2.functions.
ST_Centroid
(*args, **kwargs)¶ Returns the geometric center of a geometry.
see http://postgis.net/docs/ST_Centroid.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ChaikinSmoothing
(*args, **kwargs)¶ Returns a “smoothed” version of the given geometry using the Chaikin algorithm
see http://postgis.net/docs/ST_ChaikinSmoothing.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Clip
(*args, **kwargs)¶ Returns the raster clipped by the input geometry. If band number not is specified, all bands are processed. If crop is not specified or TRUE, the output raster is cropped.
see http://postgis.net/docs/RT_ST_Clip.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_ClipByBox2D
(*args, **kwargs)¶ Returns the portion of a geometry falling within a rectangle.
see http://postgis.net/docs/ST_ClipByBox2D.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ClosestPoint
(*args, **kwargs)¶ Returns the 2D point on g1 that is closest to g2. This is the first point of the shortest line.
see http://postgis.net/docs/ST_ClosestPoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ClosestPointOfApproach
(*args, **kwargs)¶ Returns the measure at which points interpolated along two trajectories are closest.
-
class
geoalchemy2.functions.
ST_ClusterDBSCAN
(*args, **kwargs)¶ Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.
-
class
geoalchemy2.functions.
ST_ClusterIntersecting
(*args, **kwargs)¶ Aggregate function that clusters the input geometries into connected sets.
see http://postgis.net/docs/ST_ClusterIntersecting.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ClusterKMeans
(*args, **kwargs)¶ Window function that returns a cluster id for each input geometry using the K-means algorithm.
-
class
geoalchemy2.functions.
ST_ClusterWithin
(*args, **kwargs)¶ Aggregate function that clusters the input geometries by separation distance.
see http://postgis.net/docs/ST_ClusterWithin.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Collect
(*args, **kwargs)¶ Creates a GeometryCollection or Multi* geometry from a set of geometries.
see http://postgis.net/docs/ST_Collect.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_CollectionExtract
(*args, **kwargs)¶ Given a (multi)geometry, return a (multi)geometry consisting only of elements of the specified type.
see http://postgis.net/docs/ST_CollectionExtract.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_CollectionHomogenize
(*args, **kwargs)¶ Given a geometry collection, return the “simplest” representation of the contents.
see http://postgis.net/docs/ST_CollectionHomogenize.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ColorMap
(*args, **kwargs)¶ Creates a new raster of up to four 8BUI bands (grayscale, RGB, RGBA) from the source raster and a specified band. Band 1 is assumed if not specified.
see http://postgis.net/docs/RT_ST_ColorMap.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_ConcaveHull
(*args, **kwargs)¶ The concave hull of a geometry represents a possibly concave geometry that encloses all geometries within the set. You can think of it as shrink wrapping.
see http://postgis.net/docs/ST_ConcaveHull.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ConstrainedDelaunayTriangles
(*args, **kwargs)¶ Return a constrained Delaunay triangulation around the given input geometry.
see http://postgis.net/docs/ST_ConstrainedDelaunayTriangles.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Contains
(*args, **kwargs)¶ [geometry] Returns true if and only if no points of B lie in the exterior of A, and at least one point of the interior of B lies in the interior of A. OR [raster] Return true if no points of raster rastB lie in the exterior of raster rastA and at least one point of the interior of rastB lies in the interior of rastA.
-
class
geoalchemy2.functions.
ST_ContainsProperly
(*args, **kwargs)¶ [geometry] Returns true if B intersects the interior of A but not the boundary (or exterior). A does not contain properly itself, but does contain itself. OR [raster] Return true if rastB intersects the interior of rastA but not the boundary or exterior of rastA.
-
class
geoalchemy2.functions.
ST_ConvexHull
(*args, **kwargs)¶ [geometry] Computes the convex hull of a geometry. OR [raster] Return the convex hull geometry of the raster including pixel values equal to BandNoDataValue. For regular shaped and non-skewed rasters, this gives the same result as ST_Envelope so only useful for irregularly shaped or skewed rasters.
see http://postgis.net/docs/ST_ConvexHull.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_CoordDim
(*args, **kwargs)¶ Return the coordinate dimension of a geometry.
-
class
geoalchemy2.functions.
ST_Count
(*args, **kwargs)¶ Returns the number of pixels in a given band of a raster or raster coverage. If no band is specified defaults to band 1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the nodata value.
-
class
geoalchemy2.functions.
ST_CountAgg
(*args, **kwargs)¶ Aggregate. Returns the number of pixels in a given band of a set of rasters. If no band is specified defaults to band 1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the NODATA value.
-
class
geoalchemy2.functions.
ST_CoveredBy
(*args, **kwargs)¶ [geometry] Returns 1 (TRUE) if no point in Geometry/Geography A is outside Geometry/Geography B OR [raster] Return true if no points of raster rastA lie outside raster rastB.
-
class
geoalchemy2.functions.
ST_Covers
(*args, **kwargs)¶ [geometry] Returns 1 (TRUE) if no point in Geometry B is outside Geometry A OR [raster] Return true if no points of raster rastB lie outside raster rastA.
-
class
geoalchemy2.functions.
ST_Crosses
(*args, **kwargs)¶ Returns TRUE if the supplied geometries have some, but not all, interior points in common.
-
class
geoalchemy2.functions.
ST_CurveToLine
(*args, **kwargs)¶ Converts a CIRCULARSTRING/CURVEPOLYGON/MULTISURFACE to a LINESTRING/POLYGON/MULTIPOLYGON
see http://postgis.net/docs/ST_CurveToLine.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_DFullyWithin
(*args, **kwargs)¶ [geometry] Returns true if all of the geometries are within the specified distance of one another OR [raster] Return true if rasters rastA and rastB are fully within the specified distance of each other.
-
class
geoalchemy2.functions.
ST_DWithin
(*args, **kwargs)¶ [geometry] Returns true if the geometries are within the specified distance of one another. For geometry units are in those of spatial reference and for geography units are in meters and measurement is defaulted to use_spheroid=true (measure around spheroid), for faster check, use_spheroid=false to measure along sphere. OR [raster] Return true if rasters rastA and rastB are within the specified distance of each other.
-
class
geoalchemy2.functions.
ST_DelaunayTriangles
(*args, **kwargs)¶ Return a Delaunay triangulation around the given input points.
see http://postgis.net/docs/ST_DelaunayTriangles.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Difference
(*args, **kwargs)¶ Returns a geometry that represents that part of geometry A that does not intersect with geometry B.
see http://postgis.net/docs/ST_Difference.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Dimension
(*args, **kwargs)¶ Returns the topological dimension of a geometry.
-
class
geoalchemy2.functions.
ST_Disjoint
(*args, **kwargs)¶ [geometry] Returns TRUE if the Geometries do not “spatially intersect” - if they do not share any space together. OR [raster] Return true if raster rastA does not spatially intersect rastB.
-
class
geoalchemy2.functions.
ST_Distance
(*args, **kwargs)¶ Returns the distance between two geometry or geography values.
-
class
geoalchemy2.functions.
ST_DistanceCPA
(*args, **kwargs)¶ Returns the distance between the closest point of approach of two trajectories.
-
class
geoalchemy2.functions.
ST_DistanceSphere
(*args, **kwargs)¶ Returns minimum distance in meters between two lon/lat geometries using a spherical earth model.
-
class
geoalchemy2.functions.
ST_DistanceSpheroid
(*args, **kwargs)¶ Returns the minimum distance between two lon/lat geometries using a spheroidal earth model.
-
class
geoalchemy2.functions.
ST_Distance_Sphere
(*args, **kwargs)¶ Returns minimum distance in meters between two lon/lat geometries. Uses a spherical earth and radius of 6370986 meters. Faster than
ST_Distance_Spheroid
, but less accurate. PostGIS versions prior to 1.5 only implemented for points.
-
class
geoalchemy2.functions.
ST_Distinct4ma
(*args, **kwargs)¶ Raster processing function that calculates the number of unique pixel values in a neighborhood.
-
class
geoalchemy2.functions.
ST_Dump
(*args, **kwargs)¶ Returns a set of geometry_dump rows for the components of a geometry.
see http://postgis.net/docs/ST_Dump.html
Return type:
geoalchemy2.types.GeometryDump
.-
type
¶ alias of
geoalchemy2.types.GeometryDump
-
-
class
geoalchemy2.functions.
ST_DumpAsPolygons
(*args, **kwargs)¶ Returns a set of geomval (geom,val) rows, from a given raster band. If no band number is specified, band num defaults to 1.
-
class
geoalchemy2.functions.
ST_DumpPoints
(*args, **kwargs)¶ Returns a set of geometry_dump rows for the points in a geometry.
see http://postgis.net/docs/ST_DumpPoints.html
Return type:
geoalchemy2.types.GeometryDump
.-
type
¶ alias of
geoalchemy2.types.GeometryDump
-
-
class
geoalchemy2.functions.
ST_DumpRings
(*args, **kwargs)¶ Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.
see http://postgis.net/docs/ST_DumpRings.html
Return type:
geoalchemy2.types.GeometryDump
.-
type
¶ alias of
geoalchemy2.types.GeometryDump
-
-
class
geoalchemy2.functions.
ST_DumpValues
(*args, **kwargs)¶ Get the values of the specified band as a 2-dimension array.
-
class
geoalchemy2.functions.
ST_EndPoint
(*args, **kwargs)¶ Returns the last point of a LineString or CircularLineString.
see http://postgis.net/docs/ST_EndPoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Envelope
(*args, **kwargs)¶ [geometry] Returns a geometry representing the bounding box of a geometry. OR [raster] Returns the polygon representation of the extent of the raster.
see http://postgis.net/docs/ST_Envelope.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Equals
(*args, **kwargs)¶ Returns true if the given geometries represent the same geometry. Directionality is ignored.
-
class
geoalchemy2.functions.
ST_EstimatedExtent
(*args, **kwargs)¶ Return the ‘estimated’ extent of a spatial table.
-
class
geoalchemy2.functions.
ST_Expand
(*args, **kwargs)¶ Returns a bounding box expanded from another bounding box or a geometry.
see http://postgis.net/docs/ST_Expand.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Extent
(*args, **kwargs)¶ an aggregate function that returns the bounding box that bounds rows of geometries.
-
class
geoalchemy2.functions.
ST_ExteriorRing
(*args, **kwargs)¶ Returns a LineString representing the exterior ring of a Polygon.
see http://postgis.net/docs/ST_ExteriorRing.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Extrude
(*args, **kwargs)¶ Extrude a surface to a related volume
see http://postgis.net/docs/ST_Extrude.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_FilterByM
(*args, **kwargs)¶ Filters vertex points based on their m-value
see http://postgis.net/docs/ST_FilterByM.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_FlipCoordinates
(*args, **kwargs)¶ Returns a version of the given geometry with X and Y axis flipped. Useful for people who have built latitude/longitude features and need to fix them.
see http://postgis.net/docs/ST_FlipCoordinates.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Force2D
(*args, **kwargs)¶ Force the geometries into a “2-dimensional mode”.
see http://postgis.net/docs/ST_Force2D.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Force3D
(*args, **kwargs)¶ Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.
see http://postgis.net/docs/ST_Force_3D.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Force3DM
(*args, **kwargs)¶ Force the geometries into XYM mode.
see http://postgis.net/docs/ST_Force_3DZ.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Force3DZ
(*args, **kwargs)¶ Force the geometries into XYZ mode.
see http://postgis.net/docs/ST_Force_3DZ.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Force4D
(*args, **kwargs)¶ Force the geometries into XYZM mode.
see http://postgis.net/docs/ST_Force_4D.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ForceCollection
(*args, **kwargs)¶ Convert the geometry into a GEOMETRYCOLLECTION.
see http://postgis.net/docs/ST_Force_Collection.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ForceCurve
(*args, **kwargs)¶ Upcast a geometry into its curved type, if applicable.
see http://postgis.net/docs/ST_ForceCurve.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ForceLHR
(*args, **kwargs)¶ Force LHR orientation
see http://postgis.net/docs/ST_ForceLHR.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ForcePolygonCCW
(*args, **kwargs)¶ Orients all exterior rings counter-clockwise and all interior rings clockwise.
see http://postgis.net/docs/ST_ForcePolygonCCW.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ForcePolygonCW
(*args, **kwargs)¶ Orients all exterior rings clockwise and all interior rings counter-clockwise.
see http://postgis.net/docs/ST_ForcePolygonCW.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ForceRHR
(*args, **kwargs)¶ Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.
see http://postgis.net/docs/ST_ForceRHR.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ForceSFS
(*args, **kwargs)¶ Force the geometries to use SFS 1.1 geometry types only.
see http://postgis.net/docs/ST_ForceSFS.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_FrechetDistance
(*args, **kwargs)¶ Returns the Fréchet distance between two geometries.
-
class
geoalchemy2.functions.
ST_FromGDALRaster
(*args, **kwargs)¶ Returns a raster from a supported GDAL raster file.
see http://postgis.net/docs/RT_ST_FromGDALRaster.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_GMLToSQL
(*args, **kwargs)¶ Return a specified ST_Geometry value from GML representation. This is an alias name for ST_GeomFromGML
see http://postgis.net/docs/ST_GMLToSQL.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeneratePoints
(*args, **kwargs)¶ Converts a polygon or multi-polygon into a multi-point composed of randomly location points within the original areas.
see http://postgis.net/docs/ST_GeneratePoints.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeoHash
(*args, **kwargs)¶ Return a GeoHash representation of the geometry.
-
class
geoalchemy2.functions.
ST_GeoReference
(*args, **kwargs)¶ Returns the georeference meta data in GDAL or ESRI format as commonly seen in a world file. Default is GDAL.
-
class
geoalchemy2.functions.
ST_GeogFromText
(*args, **kwargs)¶ Return a specified geography value from Well-Known Text representation or extended (WKT).
see http://postgis.net/docs/ST_GeogFromText.html
Return type:
geoalchemy2.types.Geography
.-
type
¶ alias of
geoalchemy2.types.Geography
-
-
class
geoalchemy2.functions.
ST_GeogFromWKB
(*args, **kwargs)¶ Creates a geography instance from a Well-Known Binary geometry representation (WKB) or extended Well Known Binary (EWKB).
see http://postgis.net/docs/ST_GeogFromWKB.html
Return type:
geoalchemy2.types.Geography
.-
type
¶ alias of
geoalchemy2.types.Geography
-
-
class
geoalchemy2.functions.
ST_GeographyFromText
(*args, **kwargs)¶ Return a specified geography value from Well-Known Text representation or extended (WKT).
see http://postgis.net/docs/ST_GeographyFromText.html
Return type:
geoalchemy2.types.Geography
.-
type
¶ alias of
geoalchemy2.types.Geography
-
-
class
geoalchemy2.functions.
ST_GeomCollFromText
(*args, **kwargs)¶ Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.
see http://postgis.net/docs/ST_GeomCollFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromEWKB
(*args, **kwargs)¶ Return a specified ST_Geometry value from Extended Well-Known Binary representation (EWKB).
see http://postgis.net/docs/ST_GeomFromEWKB.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromEWKT
(*args, **kwargs)¶ Return a specified ST_Geometry value from Extended Well-Known Text representation (EWKT).
see http://postgis.net/docs/ST_GeomFromEWKT.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromGML
(*args, **kwargs)¶ Takes as input GML representation of geometry and outputs a PostGIS geometry object
see http://postgis.net/docs/ST_GeomFromGML.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromGeoHash
(*args, **kwargs)¶ Return a geometry from a GeoHash string.
see http://postgis.net/docs/ST_GeomFromGeoHash.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromGeoJSON
(*args, **kwargs)¶ Takes as input a geojson representation of a geometry and outputs a PostGIS geometry object
see http://postgis.net/docs/ST_GeomFromGeoJSON.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromKML
(*args, **kwargs)¶ Takes as input KML representation of geometry and outputs a PostGIS geometry object
see http://postgis.net/docs/ST_GeomFromKML.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromTWKB
(*args, **kwargs)¶ Creates a geometry instance from a TWKB (“Tiny Well-Known Binary”) geometry representation.
see http://postgis.net/docs/ST_GeomFromTWKB.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromText
(*args, **kwargs)¶ Return a specified ST_Geometry value from Well-Known Text representation (WKT).
see http://postgis.net/docs/ST_GeomFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeomFromWKB
(*args, **kwargs)¶ Creates a geometry instance from a Well-Known Binary geometry representation (WKB) and optional SRID.
see http://postgis.net/docs/ST_GeomFromWKB.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeometricMedian
(*args, **kwargs)¶ Returns the geometric median of a MultiPoint.
see http://postgis.net/docs/ST_GeometricMedian.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeometryFromText
(*args, **kwargs)¶ Return a specified ST_Geometry value from Well-Known Text representation (WKT). This is an alias name for ST_GeomFromText
see http://postgis.net/docs/ST_GeometryFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeometryN
(*args, **kwargs)¶ Return the Nth geometry element of a geometry collection.
see http://postgis.net/docs/ST_GeometryN.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_GeometryType
(*args, **kwargs)¶ Returns the SQL-MM type of a geometry as text.
-
class
geoalchemy2.functions.
ST_Grayscale
(*args, **kwargs)¶ Creates a new one-8BUI band raster from the source raster and specified bands representing Red, Green and Blue
see http://postgis.net/docs/RT_ST_Grayscale.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_HasArc
(*args, **kwargs)¶ Tests if a geometry contains a circular arc
-
class
geoalchemy2.functions.
ST_HasNoBand
(*args, **kwargs)¶ Returns true if there is no band with given band number. If no band number is specified, then band number 1 is assumed.
-
class
geoalchemy2.functions.
ST_HausdorffDistance
(*args, **kwargs)¶ Returns the Hausdorff distance between two geometries.
-
class
geoalchemy2.functions.
ST_Height
(*args, **kwargs)¶ Returns the height of the raster in pixels.
-
class
geoalchemy2.functions.
ST_HillShade
(*args, **kwargs)¶ Returns the hypothetical illumination of an elevation raster band using provided azimuth, altitude, brightness and scale inputs.
see http://postgis.net/docs/RT_ST_HillShade.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Histogram
(*args, **kwargs)¶ Returns a set of record summarizing a raster or raster coverage data distribution separate bin ranges. Number of bins are autocomputed if not specified.
-
class
geoalchemy2.functions.
ST_InteriorRingN
(*args, **kwargs)¶ Returns the Nth interior ring (hole) of a Polygon.
see http://postgis.net/docs/ST_InteriorRingN.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_InterpolatePoint
(*args, **kwargs)¶ Return the value of the measure dimension of a geometry at the point closed to the provided point.
-
class
geoalchemy2.functions.
ST_Intersection
(*args, **kwargs)¶ [geometry] (T) Returns a geometry that represents the shared portion of geomA and geomB. OR [raster] Returns a raster or a set of geometry-pixelvalue pairs representing the shared portion of two rasters or the geometrical intersection of a vectorization of the raster and a geometry.
see http://postgis.net/docs/ST_Intersection.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Intersects
(*args, **kwargs)¶ [geometry] Returns TRUE if the Geometries/Geography “spatially intersect in 2D” - (share any portion of space) and FALSE if they don’t (they are Disjoint). For geography tolerance is 0.00001 meters (so any points that close are considered to intersect) OR [raster] Return true if raster rastA spatially intersects raster rastB.
-
class
geoalchemy2.functions.
ST_InvDistWeight4ma
(*args, **kwargs)¶ Raster processing function that interpolates a pixel’s value from the pixel’s neighborhood.
-
class
geoalchemy2.functions.
ST_IsClosed
(*args, **kwargs)¶ Tests if a LineStrings’s start and end points are coincident. For a PolyhedralSurface tests if it is closed (volumetric).
-
class
geoalchemy2.functions.
ST_IsCollection
(*args, **kwargs)¶ Tests if a geometry is a geometry collection type.
-
class
geoalchemy2.functions.
ST_IsEmpty
(*args, **kwargs)¶ [geometry] Tests if a geometry is empty. OR [raster] Returns true if the raster is empty (width = 0 and height = 0). Otherwise, returns false.
-
class
geoalchemy2.functions.
ST_IsPlanar
(*args, **kwargs)¶ Check if a surface is or not planar
-
class
geoalchemy2.functions.
ST_IsPolygonCCW
(*args, **kwargs)¶ Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
-
class
geoalchemy2.functions.
ST_IsPolygonCW
(*args, **kwargs)¶ Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
-
class
geoalchemy2.functions.
ST_IsRing
(*args, **kwargs)¶ Tests if a LineString is closed and simple.
-
class
geoalchemy2.functions.
ST_IsSimple
(*args, **kwargs)¶ Tests if a geometry has no points of self-intersection or self-tangency.
-
class
geoalchemy2.functions.
ST_IsSolid
(*args, **kwargs)¶ Test if the geometry is a solid. No validity check is performed.
-
class
geoalchemy2.functions.
ST_IsValid
(*args, **kwargs)¶ Tests if a geometry is well-formed in 2D.
-
class
geoalchemy2.functions.
ST_IsValidDetail
(*args, **kwargs)¶ Returns a valid_detail row stating if a geometry is valid, and if not a reason why and a location.
-
class
geoalchemy2.functions.
ST_IsValidReason
(*args, **kwargs)¶ Returns text stating if a geometry is valid, or a reason for invalidity.
-
class
geoalchemy2.functions.
ST_IsValidTrajectory
(*args, **kwargs)¶ Returns true if the geometry is a valid trajectory.
-
class
geoalchemy2.functions.
ST_Length
(*args, **kwargs)¶ Returns the 2D length of a linear geometry.
-
class
geoalchemy2.functions.
ST_Length2D
(*args, **kwargs)¶ Returns the 2D length of a linear geometry. Alias for ST_Length
-
class
geoalchemy2.functions.
ST_LengthSpheroid
(*args, **kwargs)¶ Returns the 2D or 3D length/perimeter of a lon/lat geometry on a spheroid.
-
class
geoalchemy2.functions.
ST_LineCrossingDirection
(*args, **kwargs)¶ Given 2 linestrings, returns a number between -3 and 3 denoting what kind of crossing behavior. 0 is no crossing.
-
class
geoalchemy2.functions.
ST_LineFromEncodedPolyline
(*args, **kwargs)¶ Creates a LineString from an Encoded Polyline.
see http://postgis.net/docs/ST_LineFromEncodedPolyline.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LineFromMultiPoint
(*args, **kwargs)¶ Creates a LineString from a MultiPoint geometry.
see http://postgis.net/docs/ST_LineFromMultiPoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LineFromText
(*args, **kwargs)¶ Makes a Geometry from WKT representation with the given SRID. If SRID is not given, it defaults to 0.
see http://postgis.net/docs/ST_LineFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LineFromWKB
(*args, **kwargs)¶ Makes a LINESTRING from WKB with the given SRID
see http://postgis.net/docs/ST_LineFromWKB.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LineInterpolatePoint
(*args, **kwargs)¶ Returns a point interpolated along a line. Second argument is a float8 between 0 and 1 representing fraction of total length of linestring the point has to be located.
see http://postgis.net/docs/ST_LineInterpolatePoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LineInterpolatePoints
(*args, **kwargs)¶ Returns one or more points interpolated along a line.
see http://postgis.net/docs/ST_LineInterpolatePoints.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LineLocatePoint
(*args, **kwargs)¶ Returns a float between 0 and 1 representing the location of the closest point on LineString to the given Point, as a fraction of total 2d line length.
-
class
geoalchemy2.functions.
ST_LineMerge
(*args, **kwargs)¶ Return a (set of) LineString(s) formed by sewing together a MULTILINESTRING.
see http://postgis.net/docs/ST_LineMerge.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LineSubstring
(*args, **kwargs)¶ Return a linestring being a substring of the input one starting and ending at the given fractions of total 2d length. Second and third arguments are float8 values between 0 and 1.
see http://postgis.net/docs/ST_LineSubstring.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LineToCurve
(*args, **kwargs)¶ Converts a LINESTRING/POLYGON to a CIRCULARSTRING, CURVEPOLYGON
see http://postgis.net/docs/ST_LineToCurve.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LinestringFromWKB
(*args, **kwargs)¶ Makes a geometry from WKB with the given SRID.
see http://postgis.net/docs/ST_LinestringFromWKB.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LocateAlong
(*args, **kwargs)¶ Return a derived geometry collection value with elements that match the specified measure. Polygonal elements are not supported.
see http://postgis.net/docs/ST_LocateAlong.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LocateBetween
(*args, **kwargs)¶ Return a derived geometry collection value with elements that match the specified range of measures inclusively.
see http://postgis.net/docs/ST_LocateBetween.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LocateBetweenElevations
(*args, **kwargs)¶ Return a derived geometry (collection) value with elements that intersect the specified range of elevations inclusively.
see http://postgis.net/docs/ST_LocateBetweenElevations.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_LongestLine
(*args, **kwargs)¶ Returns the 2D longest line between two geometries.
see http://postgis.net/docs/ST_LongestLine.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_M
(*args, **kwargs)¶ Returns the M coordinate of a Point.
-
class
geoalchemy2.functions.
ST_MLineFromText
(*args, **kwargs)¶ Return a specified ST_MultiLineString value from WKT representation.
see http://postgis.net/docs/ST_MLineFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MPointFromText
(*args, **kwargs)¶ Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
see http://postgis.net/docs/ST_MPointFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MPolyFromText
(*args, **kwargs)¶ Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
see http://postgis.net/docs/ST_MPolyFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MakeBox2D
(*args, **kwargs)¶ Creates a BOX2D defined by two 2D point geometries.
-
class
geoalchemy2.functions.
ST_MakeEmptyCoverage
(*args, **kwargs)¶ Cover georeferenced area with a grid of empty raster tiles.
see http://postgis.net/docs/RT_ST_MakeEmptyCoverage.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_MakeEmptyRaster
(*args, **kwargs)¶ Returns an empty raster (having no bands) of given dimensions (width & height), upperleft X and Y, pixel size and rotation (scalex, scaley, skewx & skewy) and reference system (srid). If a raster is passed in, returns a new raster with the same size, alignment and SRID. If srid is left out, the spatial ref is set to unknown (0).
see http://postgis.net/docs/RT_ST_MakeEmptyRaster.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_MakeEnvelope
(*args, **kwargs)¶ Creates a rectangular Polygon from minimum and maximum coordinates.
see http://postgis.net/docs/ST_MakeEnvelope.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MakeLine
(*args, **kwargs)¶ Creates a Linestring from Point, MultiPoint, or LineString geometries.
see http://postgis.net/docs/ST_MakeLine.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MakePoint
(*args, **kwargs)¶ Creates a 2D, 3DZ or 4D Point.
see http://postgis.net/docs/ST_MakePoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MakePointM
(*args, **kwargs)¶ Creates a Point from X, Y and M values.
see http://postgis.net/docs/ST_MakePointM.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MakePolygon
(*args, **kwargs)¶ Creates a Polygon from a shell and optional list of holes.
see http://postgis.net/docs/ST_MakePolygon.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MakeSolid
(*args, **kwargs)¶ Cast the geometry into a solid. No check is performed. To obtain a valid solid, the input geometry must be a closed Polyhedral Surface or a closed TIN.
see http://postgis.net/docs/ST_MakeSolid.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MakeValid
(*args, **kwargs)¶ Attempts to make an invalid geometry valid without losing vertices.
see http://postgis.net/docs/ST_MakeValid.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MapAlgebra
(*args, **kwargs)¶ [raster] Callback function version - Returns a one-band raster given one or more input rasters, band indexes and one user-specified callback function. OR [raster] Expression version - Returns a one-band raster given one or two input rasters, band indexes and one or more user-specified SQL expressions.
-
class
geoalchemy2.functions.
ST_MapAlgebraExpr
(*args, **kwargs)¶ [raster] 1 raster band version: Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation on the input raster band and of pixeltype provided. Band 1 is assumed if no band is specified. OR [raster] 2 raster band version: Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation on the two input raster bands and of pixeltype provided. band 1 of each raster is assumed if no band numbers are specified. The resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first raster and have its extent defined by the “extenttype” parameter. Values for “extenttype” can be: INTERSECTION, UNION, FIRST, SECOND.
see http://postgis.net/docs/RT_ST_MapAlgebraExpr.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_MapAlgebraFct
(*args, **kwargs)¶ [raster] 1 band version - Creates a new one band raster formed by applying a valid PostgreSQL function on the input raster band and of pixeltype prodived. Band 1 is assumed if no band is specified. OR [raster] 2 band version - Creates a new one band raster formed by applying a valid PostgreSQL function on the 2 input raster bands and of pixeltype prodived. Band 1 is assumed if no band is specified. Extent type defaults to INTERSECTION if not specified.
see http://postgis.net/docs/RT_ST_MapAlgebraFct.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_MapAlgebraFctNgb
(*args, **kwargs)¶ 1-band version: Map Algebra Nearest Neighbor using user-defined PostgreSQL function. Return a raster which values are the result of a PLPGSQL user function involving a neighborhood of values from the input raster band.
see http://postgis.net/docs/RT_ST_MapAlgebraFctNgb.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Max4ma
(*args, **kwargs)¶ Raster processing function that calculates the maximum pixel value in a neighborhood.
-
class
geoalchemy2.functions.
ST_MaxDistance
(*args, **kwargs)¶ Returns the 2D largest distance between two geometries in projected units.
-
class
geoalchemy2.functions.
ST_Mean4ma
(*args, **kwargs)¶ Raster processing function that calculates the mean pixel value in a neighborhood.
-
class
geoalchemy2.functions.
ST_MemSize
(*args, **kwargs)¶ [geometry] Returns the amount of memory space a geometry takes. OR [raster] Returns the amount of space (in bytes) the raster takes.
-
class
geoalchemy2.functions.
ST_MemUnion
(*args, **kwargs)¶ Same as ST_Union, only memory-friendly (uses less memory and more processor time).
see http://postgis.net/docs/ST_MemUnion.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MetaData
(*args, **kwargs)¶ Returns basic meta data about a raster object such as pixel size, rotation (skew), upper, lower left, etc.
-
class
geoalchemy2.functions.
ST_Min4ma
(*args, **kwargs)¶ Raster processing function that calculates the minimum pixel value in a neighborhood.
-
class
geoalchemy2.functions.
ST_MinConvexHull
(*args, **kwargs)¶ Return the convex hull geometry of the raster excluding NODATA pixels.
see http://postgis.net/docs/RT_ST_MinConvexHull.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MinDist4ma
(*args, **kwargs)¶ Raster processing function that returns the minimum distance (in number of pixels) between the pixel of interest and a neighboring pixel with value.
-
class
geoalchemy2.functions.
ST_MinPossibleValue
(*args, **kwargs)¶ Returns the minimum value this pixeltype can store.
-
class
geoalchemy2.functions.
ST_MinimumBoundingCircle
(*args, **kwargs)¶ Returns the smallest circle polygon that can fully contain a geometry. Default uses 48 segments per quarter circle.
see http://postgis.net/docs/ST_MinimumBoundingCircle.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MinimumBoundingRadius
(*args, **kwargs)¶ Returns the center point and radius of the smallest circle that can fully contain a geometry.
-
class
geoalchemy2.functions.
ST_MinimumClearance
(*args, **kwargs)¶ Returns the minimum clearance of a geometry, a measure of a geometry’s robustness.
-
class
geoalchemy2.functions.
ST_MinimumClearanceLine
(*args, **kwargs)¶ Returns the two-point LineString spanning a geometry’s minimum clearance.
see http://postgis.net/docs/ST_MinimumClearanceLine.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_MinkowskiSum
(*args, **kwargs)¶ Performs Minkowski sum
see http://postgis.net/docs/ST_MinkowskiSum.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Multi
(*args, **kwargs)¶ Return the geometry as a MULTI* geometry.
see http://postgis.net/docs/ST_Multi.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_NDims
(*args, **kwargs)¶ Returns the coordinate dimension of a geometry.
-
class
geoalchemy2.functions.
ST_NPoints
(*args, **kwargs)¶ Returns the number of points (vertices) in a geometry.
-
class
geoalchemy2.functions.
ST_NRings
(*args, **kwargs)¶ Returns the number of rings in a polygonal geometry.
-
class
geoalchemy2.functions.
ST_NearestValue
(*args, **kwargs)¶ Returns the nearest non-NODATA value of a given band’s pixel specified by a columnx and rowy or a geometric point expressed in the same spatial reference coordinate system as the raster.
-
class
geoalchemy2.functions.
ST_Neighborhood
(*args, **kwargs)¶ Returns a 2-D double precision array of the non-NODATA values around a given band’s pixel specified by either a columnX and rowY or a geometric point expressed in the same spatial reference coordinate system as the raster.
-
class
geoalchemy2.functions.
ST_Node
(*args, **kwargs)¶ Node a set of linestrings.
see http://postgis.net/docs/ST_Node.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Normalize
(*args, **kwargs)¶ Return the geometry in its canonical form.
see http://postgis.net/docs/ST_Normalize.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_NotSameAlignmentReason
(*args, **kwargs)¶ Returns text stating if rasters are aligned and if not aligned, a reason why.
see http://postgis.net/docs/RT_ST_NotSameAlignmentReason.html
-
class
geoalchemy2.functions.
ST_NumBands
(*args, **kwargs)¶ Returns the number of bands in the raster object.
-
class
geoalchemy2.functions.
ST_NumGeometries
(*args, **kwargs)¶ Returns the number of elements in a geometry collection.
-
class
geoalchemy2.functions.
ST_NumInteriorRing
(*args, **kwargs)¶ Returns the number of interior rings (holes) of a Polygon. Aias for ST_NumInteriorRings
-
class
geoalchemy2.functions.
ST_NumInteriorRings
(*args, **kwargs)¶ Returns the number of interior rings (holes) of a Polygon.
-
class
geoalchemy2.functions.
ST_NumPatches
(*args, **kwargs)¶ Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries.
-
class
geoalchemy2.functions.
ST_NumPoints
(*args, **kwargs)¶ Returns the number of points in a LineString or CircularString.
-
class
geoalchemy2.functions.
ST_OffsetCurve
(*args, **kwargs)¶ Return an offset line at a given distance and side from an input line. Useful for computing parallel lines about a center line
see http://postgis.net/docs/ST_OffsetCurve.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_OrderingEquals
(*args, **kwargs)¶ Returns true if the given geometries represent the same geometry and points are in the same directional order.
-
class
geoalchemy2.functions.
ST_Orientation
(*args, **kwargs)¶ Determine surface orientation
-
class
geoalchemy2.functions.
ST_OrientedEnvelope
(*args, **kwargs)¶ Returns a minimum rotated rectangle enclosing a geometry.
see http://postgis.net/docs/ST_OrientedEnvelope.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Overlaps
(*args, **kwargs)¶ [geometry] Returns TRUE if the Geometries share space, are of the same dimension, but are not completely contained by each other. OR [raster] Return true if raster rastA and rastB intersect but one does not completely contain the other.
-
class
geoalchemy2.functions.
ST_PatchN
(*args, **kwargs)¶ Returns the Nth geometry (face) of a PolyhedralSurface.
see http://postgis.net/docs/ST_PatchN.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Perimeter
(*args, **kwargs)¶ Returns the length of the boundary of a polygonal geometry or geography.
-
class
geoalchemy2.functions.
ST_Perimeter2D
(*args, **kwargs)¶ Returns the 2D perimeter of a polygonal geometry. Alias for ST_Perimeter.
-
class
geoalchemy2.functions.
ST_PixelAsCentroid
(*args, **kwargs)¶ Returns the centroid (point geometry) of the area represented by a pixel.
see http://postgis.net/docs/RT_ST_PixelAsCentroid.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PixelAsCentroids
(*args, **kwargs)¶ Returns the centroid (point geometry) for each pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel. The point geometry is the centroid of the area represented by a pixel.
-
class
geoalchemy2.functions.
ST_PixelAsPoint
(*args, **kwargs)¶ Returns a point geometry of the pixel’s upper-left corner.
see http://postgis.net/docs/RT_ST_PixelAsPoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PixelAsPoints
(*args, **kwargs)¶ Returns a point geometry for each pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel. The coordinates of the point geometry are of the pixel’s upper-left corner.
-
class
geoalchemy2.functions.
ST_PixelAsPolygon
(*args, **kwargs)¶ Returns the polygon geometry that bounds the pixel for a particular row and column.
see http://postgis.net/docs/RT_ST_PixelAsPolygon.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PixelAsPolygons
(*args, **kwargs)¶ Returns the polygon geometry that bounds every pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel.
-
class
geoalchemy2.functions.
ST_PixelHeight
(*args, **kwargs)¶ Returns the pixel height in geometric units of the spatial reference system.
-
class
geoalchemy2.functions.
ST_PixelOfValue
(*args, **kwargs)¶ Get the columnx, rowy coordinates of the pixel whose value equals the search value.
-
class
geoalchemy2.functions.
ST_PixelWidth
(*args, **kwargs)¶ Returns the pixel width in geometric units of the spatial reference system.
-
class
geoalchemy2.functions.
ST_Point
(*args, **kwargs)¶ Creates a Point with the given coordinate values. Alias for ST_MakePoint.
see http://postgis.net/docs/ST_Point.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PointFromGeoHash
(*args, **kwargs)¶ Return a point from a GeoHash string.
see http://postgis.net/docs/ST_PointFromGeoHash.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PointFromText
(*args, **kwargs)¶ Makes a point Geometry from WKT with the given SRID. If SRID is not given, it defaults to unknown.
see http://postgis.net/docs/ST_PointFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PointFromWKB
(*args, **kwargs)¶ Makes a geometry from WKB with the given SRID
see http://postgis.net/docs/ST_PointFromWKB.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PointInsideCircle
(*args, **kwargs)¶ Is the point geometry inside the circle defined by center_x, center_y, radius
-
class
geoalchemy2.functions.
ST_PointN
(*args, **kwargs)¶ Returns the Nth point in the first LineString or circular LineString in a geometry.
see http://postgis.net/docs/ST_PointN.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PointOnSurface
(*args, **kwargs)¶ Returns a POINT guaranteed to lie on the surface.
see http://postgis.net/docs/ST_PointOnSurface.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Points
(*args, **kwargs)¶ Returns a MultiPoint containing all the coordinates of a geometry.
see http://postgis.net/docs/ST_Points.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Polygon
(*args, **kwargs)¶ [geometry] Creates a Polygon from a LineString with a specified SRID. OR [raster] Returns a multipolygon geometry formed by the union of pixels that have a pixel value that is not no data value. If no band number is specified, band num defaults to 1.
see http://postgis.net/docs/ST_Polygon.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_PolygonFromText
(*args, **kwargs)¶ Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
see http://postgis.net/docs/ST_PolygonFromText.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Polygonize
(*args, **kwargs)¶ Aggregate. Creates a GeometryCollection containing possible polygons formed from the constituent linework of a set of geometries.
see http://postgis.net/docs/ST_Polygonize.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Project
(*args, **kwargs)¶ Returns a point projected from a start point by a distance and bearing (azimuth).
see http://postgis.net/docs/ST_Project.html
Return type:
geoalchemy2.types.Geography
.-
type
¶ alias of
geoalchemy2.types.Geography
-
-
class
geoalchemy2.functions.
ST_Quantile
(*args, **kwargs)¶ Compute quantiles for a raster or raster table coverage in the context of the sample or population. Thus, a value could be examined to be at the raster’s 25%, 50%, 75% percentile.
-
class
geoalchemy2.functions.
ST_QuantizeCoordinates
(*args, **kwargs)¶ Sets least significant bits of coordinates to zero
see http://postgis.net/docs/ST_QuantizeCoordinates.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Range4ma
(*args, **kwargs)¶ Raster processing function that calculates the range of pixel values in a neighborhood.
-
class
geoalchemy2.functions.
ST_RastFromHexWKB
(*args, **kwargs)¶ Return a raster value from a Hex representation of Well-Known Binary (WKB) raster.
see http://postgis.net/docs/RT_ST_RastFromHexWKB.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_RastFromWKB
(*args, **kwargs)¶ Return a raster value from a Well-Known Binary (WKB) raster.
see http://postgis.net/docs/RT_ST_RastFromWKB.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_RasterToWorldCoord
(*args, **kwargs)¶ Returns the raster’s upper left corner as geometric X and Y (longitude and latitude) given a column and row. Column and row starts at 1.
-
class
geoalchemy2.functions.
ST_RasterToWorldCoordX
(*args, **kwargs)¶ Returns the geometric X coordinate upper left of a raster, column and row. Numbering of columns and rows starts at 1.
-
class
geoalchemy2.functions.
ST_RasterToWorldCoordY
(*args, **kwargs)¶ Returns the geometric Y coordinate upper left corner of a raster, column and row. Numbering of columns and rows starts at 1.
-
class
geoalchemy2.functions.
ST_Reclass
(*args, **kwargs)¶ Creates a new raster composed of band types reclassified from original. The nband is the band to be changed. If nband is not specified assumed to be 1. All other bands are returned unchanged. Use case: convert a 16BUI band to a 8BUI and so forth for simpler rendering as viewable formats.
see http://postgis.net/docs/RT_ST_Reclass.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Relate
(*args, **kwargs)¶ Returns true if this Geometry is spatially related to anotherGeometry, by testing for intersections between the Interior, Boundary and Exterior of the two geometries as specified by the values in the intersectionMatrixPattern. If no intersectionMatrixPattern is passed in, then returns the maximum intersectionMatrixPattern that relates the 2 geometries.
-
class
geoalchemy2.functions.
ST_RelateMatch
(*args, **kwargs)¶ Returns true if intersectionMattrixPattern1 implies intersectionMatrixPattern2
-
class
geoalchemy2.functions.
ST_RemovePoint
(*args, **kwargs)¶ Remove point from a linestring.
see http://postgis.net/docs/ST_RemovePoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_RemoveRepeatedPoints
(*args, **kwargs)¶ Returns a version of the given geometry with duplicated points removed.
see http://postgis.net/docs/ST_RemoveRepeatedPoints.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Resample
(*args, **kwargs)¶ Resample a raster using a specified resampling algorithm, new dimensions, an arbitrary grid corner and a set of raster georeferencing attributes defined or borrowed from another raster.
see http://postgis.net/docs/RT_ST_Resample.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Rescale
(*args, **kwargs)¶ Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is NearestNeighbor.
see http://postgis.net/docs/RT_ST_Rescale.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Resize
(*args, **kwargs)¶ Resize a raster to a new width/height
see http://postgis.net/docs/RT_ST_Resize.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Reskew
(*args, **kwargs)¶ Resample a raster by adjusting only its skew (or rotation parameters). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is NearestNeighbor.
see http://postgis.net/docs/RT_ST_Reskew.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Retile
(*args, **kwargs)¶ Return a set of configured tiles from an arbitrarily tiled raster coverage.
see http://postgis.net/docs/RT_ST_Retile.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Reverse
(*args, **kwargs)¶ Return the geometry with vertex order reversed.
see http://postgis.net/docs/ST_Reverse.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Rotate
(*args, **kwargs)¶ Rotates a geometry about an origin point.
see http://postgis.net/docs/ST_Rotate.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_RotateX
(*args, **kwargs)¶ Rotates a geometry about the X axis.
see http://postgis.net/docs/ST_RotateX.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_RotateY
(*args, **kwargs)¶ Rotates a geometry about the Y axis.
see http://postgis.net/docs/ST_RotateY.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_RotateZ
(*args, **kwargs)¶ Rotates a geometry about the Z axis.
see http://postgis.net/docs/ST_RotateZ.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Rotation
(*args, **kwargs)¶ Returns the rotation of the raster in radian.
-
class
geoalchemy2.functions.
ST_Roughness
(*args, **kwargs)¶ Returns a raster with the calculated “roughness” of a DEM.
see http://postgis.net/docs/RT_ST_Roughness.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SRID
(*args, **kwargs)¶ [geometry] Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. OR [raster] Returns the spatial reference identifier of the raster as defined in spatial_ref_sys table.
-
class
geoalchemy2.functions.
ST_SameAlignment
(*args, **kwargs)¶ Returns true if rasters have same skew, scale, spatial ref, and offset (pixels can be put on same grid without cutting into pixels) and false if they don’t with notice detailing issue.
-
class
geoalchemy2.functions.
ST_Scale
(*args, **kwargs)¶ Scales a geometry by given factors.
see http://postgis.net/docs/ST_Scale.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ScaleX
(*args, **kwargs)¶ Returns the X component of the pixel width in units of coordinate reference system.
-
class
geoalchemy2.functions.
ST_ScaleY
(*args, **kwargs)¶ Returns the Y component of the pixel height in units of coordinate reference system.
-
class
geoalchemy2.functions.
ST_Segmentize
(*args, **kwargs)¶ Return a modified geometry/geography having no segment longer than the given distance.
see http://postgis.net/docs/ST_Segmentize.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SetBandIndex
(*args, **kwargs)¶ Update the external band number of an out-db band
see http://postgis.net/docs/RT_ST_SetBandIndex.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetBandIsNoData
(*args, **kwargs)¶ Sets the isnodata flag of the band to TRUE.
see http://postgis.net/docs/RT_ST_SetBandIsNoData.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetBandNoDataValue
(*args, **kwargs)¶ Sets the value for the given band that represents no data. Band 1 is assumed if no band is specified. To mark a band as having no nodata value, set the nodata value = NULL.
see http://postgis.net/docs/RT_ST_SetBandNoDataValue.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetBandPath
(*args, **kwargs)¶ Update the external path and band number of an out-db band
see http://postgis.net/docs/RT_ST_SetBandPath.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetEffectiveArea
(*args, **kwargs)¶ Sets the effective area for each vertex, storing the value in the M ordinate. A simplified geometry can then be generated by filtering on the M ordinate.
see http://postgis.net/docs/ST_SetEffectiveArea.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SetGeoReference
(*args, **kwargs)¶ Set Georeference 6 georeference parameters in a single call. Numbers should be separated by white space. Accepts inputs in GDAL or ESRI format. Default is GDAL.
see http://postgis.net/docs/RT_ST_SetGeoReference.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetPoint
(*args, **kwargs)¶ Replace point of a linestring with a given point.
see http://postgis.net/docs/ST_SetPoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SetRotation
(*args, **kwargs)¶ Set the rotation of the raster in radian.
see http://postgis.net/docs/RT_ST_SetRotation.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetSRID
(*args, **kwargs)¶ [geometry] Set the SRID on a geometry to a particular integer value. OR [raster] Sets the SRID of a raster to a particular integer srid defined in the spatial_ref_sys table.
see http://postgis.net/docs/ST_SetSRID.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SetScale
(*args, **kwargs)¶ Sets the X and Y size of pixels in units of coordinate reference system. Number units/pixel width/height.
see http://postgis.net/docs/RT_ST_SetScale.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetSkew
(*args, **kwargs)¶ Sets the georeference X and Y skew (or rotation parameter). If only one is passed in, sets X and Y to the same value.
see http://postgis.net/docs/RT_ST_SetSkew.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetUpperLeft
(*args, **kwargs)¶ Sets the value of the upper left corner of the pixel of the raster to projected X and Y coordinates.
see http://postgis.net/docs/RT_ST_SetUpperLeft.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetValue
(*args, **kwargs)¶ Returns modified raster resulting from setting the value of a given band in a given columnx, rowy pixel or the pixels that intersect a particular geometry. Band numbers start at 1 and assumed to be 1 if not specified.
see http://postgis.net/docs/RT_ST_SetValue.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_SetValues
(*args, **kwargs)¶ Returns modified raster resulting from setting the values of a given band.
see http://postgis.net/docs/RT_ST_SetValues.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
Returns a collection containing paths shared by the two input linestrings/multilinestrings.
see http://postgis.net/docs/ST_SharedPaths.html
Return type:
geoalchemy2.types.Geometry
.alias of
geoalchemy2.types.Geometry
-
class
geoalchemy2.functions.
ST_ShiftLongitude
(*args, **kwargs)¶ Toggle geometry coordinates between -180..180 and 0..360 ranges.
see http://postgis.net/docs/ST_Shift_Longitude.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_ShortestLine
(*args, **kwargs)¶ Returns the 2D shortest line between two geometries
see http://postgis.net/docs/ST_ShortestLine.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Simplify
(*args, **kwargs)¶ Returns a “simplified” version of the given geometry using the Douglas-Peucker algorithm.
see http://postgis.net/docs/ST_Simplify.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SimplifyPreserveTopology
(*args, **kwargs)¶ Returns a “simplified” version of the given geometry using the Douglas-Peucker algorithm. Will avoid creating derived geometries (polygons in particular) that are invalid.
see http://postgis.net/docs/ST_SimplifyPreserveTopology.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SimplifyVW
(*args, **kwargs)¶ Returns a “simplified” version of the given geometry using the Visvalingam-Whyatt algorithm
see http://postgis.net/docs/ST_SimplifyVW.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SkewX
(*args, **kwargs)¶ Returns the georeference X skew (or rotation parameter).
-
class
geoalchemy2.functions.
ST_SkewY
(*args, **kwargs)¶ Returns the georeference Y skew (or rotation parameter).
-
class
geoalchemy2.functions.
ST_Slope
(*args, **kwargs)¶ Returns the slope (in degrees by default) of an elevation raster band. Useful for analyzing terrain.
see http://postgis.net/docs/RT_ST_Slope.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Snap
(*args, **kwargs)¶ Snap segments and vertices of input geometry to vertices of a reference geometry.
see http://postgis.net/docs/ST_Snap.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SnapToGrid
(*args, **kwargs)¶ [geometry] Snap all points of the input geometry to a regular grid. OR [raster] Resample a raster by snapping it to a grid. New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is NearestNeighbor.
see http://postgis.net/docs/ST_SnapToGrid.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Split
(*args, **kwargs)¶ Returns a collection of geometries resulting by splitting a geometry.
see http://postgis.net/docs/ST_Split.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_StartPoint
(*args, **kwargs)¶ Returns the first point of a LineString.
see http://postgis.net/docs/ST_StartPoint.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_StdDev4ma
(*args, **kwargs)¶ Raster processing function that calculates the standard deviation of pixel values in a neighborhood.
-
class
geoalchemy2.functions.
ST_StraightSkeleton
(*args, **kwargs)¶ Compute a straight skeleton from a geometry
see http://postgis.net/docs/ST_StraightSkeleton.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Subdivide
(*args, **kwargs)¶ Returns a set of geometry where no geometry in the set has more than the specified number of vertices.
see http://postgis.net/docs/ST_Subdivide.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Sum4ma
(*args, **kwargs)¶ Raster processing function that calculates the sum of all pixel values in a neighborhood.
-
class
geoalchemy2.functions.
ST_Summary
(*args, **kwargs)¶ [geometry] Returns a text summary of the contents of a geometry. OR [raster] Returns a text summary of the contents of the raster.
-
class
geoalchemy2.functions.
ST_SummaryStats
(*args, **kwargs)¶ Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. Band 1 is assumed is no band is specified.
-
class
geoalchemy2.functions.
ST_SummaryStatsAgg
(*args, **kwargs)¶ Aggregate. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a set of raster. Band 1 is assumed is no band is specified.
see http://postgis.net/docs/RT_ST_SummaryStatsAgg.html
Return type:
geoalchemy2.types.SummaryStats
.-
type
¶ alias of
geoalchemy2.types.SummaryStats
-
-
class
geoalchemy2.functions.
ST_SwapOrdinates
(*args, **kwargs)¶ Returns a version of the given geometry with given ordinate values swapped.
see http://postgis.net/docs/ST_SwapOrdinates.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_SymDifference
(*args, **kwargs)¶ Returns a geometry that represents the portions of A and B that do not intersect. It is called a symmetric difference because ST_SymDifference(A,B) = ST_SymDifference(B,A).
see http://postgis.net/docs/ST_SymDifference.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_TPI
(*args, **kwargs)¶ Returns a raster with the calculated Topographic Position Index.
see http://postgis.net/docs/RT_ST_TPI.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_TRI
(*args, **kwargs)¶ Returns a raster with the calculated Terrain Ruggedness Index.
see http://postgis.net/docs/RT_ST_TRI.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_Tesselate
(*args, **kwargs)¶ Perform surface Tessellation of a polygon or polyhedralsurface and returns as a TIN or collection of TINS
see http://postgis.net/docs/ST_Tesselate.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Tile
(*args, **kwargs)¶ Returns a set of rasters resulting from the split of the input raster based upon the desired dimensions of the output rasters.
see http://postgis.net/docs/RT_ST_Tile.html
Return type:
geoalchemy2.types.Raster
.-
type
¶ alias of
geoalchemy2.types.Raster
-
-
class
geoalchemy2.functions.
ST_TileEnvelope
(*args, **kwargs)¶ Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
see http://postgis.net/docs/ST_TileEnvelope.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Touches
(*args, **kwargs)¶ [geometry] Returns TRUE if the geometries have at least one point in common, but their interiors do not intersect. OR [raster] Return true if raster rastA and rastB have at least one point in common but their interiors do not intersect.
-
class
geoalchemy2.functions.
ST_TransScale
(*args, **kwargs)¶ Translates and scales a geometry by given offsets and factors.
see http://postgis.net/docs/ST_TransScale.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Transform
(*args, **kwargs)¶ [geometry] Return a new geometry with its coordinates transformed to a different spatial reference system. OR [raster] Reprojects a raster in a known spatial reference system to another known spatial reference system using specified resampling algorithm. Options are NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos defaulting to NearestNeighbor.
see http://postgis.net/docs/ST_Transform.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Translate
(*args, **kwargs)¶ Translates a geometry by given offsets.
see http://postgis.net/docs/ST_Translate.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_UnaryUnion
(*args, **kwargs)¶ Like ST_Union, but working at the geometry component level.
see http://postgis.net/docs/ST_UnaryUnion.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Union
(*args, **kwargs)¶ [geometry] Returns a geometry that represents the point set union of the Geometries. OR [raster] Returns the union of a set of raster tiles into a single raster composed of 1 or more bands.
see http://postgis.net/docs/ST_Union.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_UpperLeftX
(*args, **kwargs)¶ Returns the upper left X coordinate of raster in projected spatial ref.
-
class
geoalchemy2.functions.
ST_UpperLeftY
(*args, **kwargs)¶ Returns the upper left Y coordinate of raster in projected spatial ref.
-
class
geoalchemy2.functions.
ST_Value
(*args, **kwargs)¶ Returns the value of a given band in a given columnx, rowy pixel or at a particular geometric point. Band numbers start at 1 and assumed to be 1 if not specified. If exclude_nodata_value is set to false, then all pixels include nodata pixels are considered to intersect and return value. If exclude_nodata_value is not passed in then reads it from metadata of raster.
-
class
geoalchemy2.functions.
ST_ValueCount
(*args, **kwargs)¶ Returns a set of records containing a pixel band value and count of the number of pixels in a given band of a raster (or a raster coverage) that have a given set of values. If no band is specified defaults to band 1. By default nodata value pixels are not counted. and all other values in the pixel are output and pixel band values are rounded to the nearest integer.
-
class
geoalchemy2.functions.
ST_Volume
(*args, **kwargs)¶ Computes the volume of a 3D solid. If applied to surface (even closed) geometries will return 0.
-
class
geoalchemy2.functions.
ST_VoronoiLines
(*args, **kwargs)¶ Returns the boundaries between the cells of the Voronoi diagram constructed from the vertices of a geometry.
see http://postgis.net/docs/ST_VoronoiLines.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_VoronoiPolygons
(*args, **kwargs)¶ Returns the cells of the Voronoi diagram constructed from the vertices of a geometry.
see http://postgis.net/docs/ST_VoronoiPolygons.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_WKBToSQL
(*args, **kwargs)¶ Return a specified ST_Geometry value from Well-Known Binary representation (WKB). This is an alias name for ST_GeomFromWKB that takes no srid
see http://postgis.net/docs/ST_WKBToSQL.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_WKTToSQL
(*args, **kwargs)¶ Return a specified ST_Geometry value from Well-Known Text representation (WKT). This is an alias name for ST_GeomFromText
see http://postgis.net/docs/ST_WKTToSQL.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_Width
(*args, **kwargs)¶ Returns the width of the raster in pixels.
-
class
geoalchemy2.functions.
ST_Within
(*args, **kwargs)¶ [geometry] Returns true if the geometry A is completely inside geometry B OR [raster] Return true if no points of raster rastA lie in the exterior of raster rastB and at least one point of the interior of rastA lies in the interior of rastB.
-
class
geoalchemy2.functions.
ST_WorldToRasterCoord
(*args, **kwargs)¶ Returns the upper left corner as column and row given geometric X and Y (longitude and latitude) or a point geometry expressed in the spatial reference coordinate system of the raster.
-
class
geoalchemy2.functions.
ST_WorldToRasterCoordX
(*args, **kwargs)¶ Returns the column in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw) represented in world spatial reference system of raster.
-
class
geoalchemy2.functions.
ST_WorldToRasterCoordY
(*args, **kwargs)¶ Returns the row in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw) represented in world spatial reference system of raster.
-
class
geoalchemy2.functions.
ST_WrapX
(*args, **kwargs)¶ Wrap a geometry around an X value.
see http://postgis.net/docs/ST_WrapX.html
Return type:
geoalchemy2.types.Geometry
.-
type
¶ alias of
geoalchemy2.types.Geometry
-
-
class
geoalchemy2.functions.
ST_X
(*args, **kwargs)¶ Returns the X coordinate of a Point.
-
class
geoalchemy2.functions.
ST_XMax
(*args, **kwargs)¶ Returns the X maxima of a 2D or 3D bounding box or a geometry.
-
class
geoalchemy2.functions.
ST_XMin
(*args, **kwargs)¶ Returns the X minima of a 2D or 3D bounding box or a geometry.
-
class
geoalchemy2.functions.
ST_Y
(*args, **kwargs)¶ Returns the Y coordinate of a Point.
-
class
geoalchemy2.functions.
ST_YMax
(*args, **kwargs)¶ Returns the Y maxima of a 2D or 3D bounding box or a geometry.
-
class
geoalchemy2.functions.
ST_YMin
(*args, **kwargs)¶ Returns the Y minima of a 2D or 3D bounding box or a geometry.
-
class
geoalchemy2.functions.
ST_Z
(*args, **kwargs)¶ Returns the Z coordinate of a Point.
-
class
geoalchemy2.functions.
ST_ZMax
(*args, **kwargs)¶ Returns the Z maxima of a 2D or 3D bounding box or a geometry.
-
class
geoalchemy2.functions.
ST_ZMin
(*args, **kwargs)¶ Returns the Z minima of a 2D or 3D bounding box or a geometry.
-
class
geoalchemy2.functions.
ST_Zmflag
(*args, **kwargs)¶ Returns a code indicating the ZM coordinate dimension of a geometry.
-
class
geoalchemy2.functions.
UnlockRows
(*args, **kwargs)¶ Removes all locks held by an authorization token.
-
class
geoalchemy2.functions.
UpdateGeometrySRID
(*args, **kwargs)¶ Updates the SRID of all features in a geometry column, and the table metadata.
-
class
geoalchemy2.functions.
postgis_sfcgal_version
(*args, **kwargs)¶ Returns the version of SFCGAL in use
Spatial Operators¶
This module defines a Comparator
class for use with geometry and geography
objects. This is where spatial operators, like &&
, &<
, are defined.
Spatial operators very often apply to the bounding boxes of geometries. For
example, geom1 && geom2
indicates if geom1’s bounding box intersects
geom2’s.
Examples
Select the objects whose bounding boxes are to the left of the
bounding box of POLYGON((-5 45,5 45,5 -45,-5 -45,-5 45))
:
select([table]).where(table.c.geom.to_left(
'POLYGON((-5 45,5 45,5 -45,-5 -45,-5 45))'))
The <<
and >>
operators are a bit specific, because they have
corresponding Python operator (__lshift__
and __rshift__
). The
above SELECT
expression can thus be rewritten like this:
select([table]).where(
table.c.geom << 'POLYGON((-5 45,5 45,5 -45,-5 -45,-5 45))')
Operators can also be used when using the ORM. For example:
Session.query(Cls).filter(
Cls.geom << 'POLYGON((-5 45,5 45,5 -45,-5 -45,-5 45))')
Now some other examples with the <#>
operator.
Select the ten objects that are the closest to POINT(0 0)
(typical
closed neighbors problem):
select([table]).order_by(table.c.geom.distance_box('POINT(0 0)')).limit(10)
Using the ORM:
Session.query(Cls).order_by(Cls.geom.distance_box('POINT(0 0)')).limit(10)
Reference¶
-
class
geoalchemy2.comparator.
BaseComparator
(expr)[source]¶ Bases:
sqlalchemy.sql.type_api.Comparator
A custom comparator base class. It adds the ability to call spatial functions on columns that use this kind of comparator. It also defines functions that map to operators supported by
Geometry
,Geography
andRaster
columns.This comparator is used by the
geoalchemy2.types.Raster
.-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
geoalchemy2.comparator.
Comparator
(expr)[source]¶ Bases:
geoalchemy2.comparator.BaseComparator
A custom comparator class. Used in
geoalchemy2.types.Geometry
andgeoalchemy2.types.Geography
.This is where spatial operators like
<<
and<->
are defined.-
__lshift__
(other)[source]¶ The
<<
operator. A’s BBOX is strictly to the left of B’s. Same asto_left
, so:table.c.geom << 'POINT(1 2)'
is the same as:
table.c.geom.to_left('POINT(1 2)')
-
__rshift__
(other)[source]¶ The
>>
operator. A’s BBOX is strictly to the left of B’s. Same as to_`right`, so:table.c.geom >> 'POINT(1 2)'
is the same as:
table.c.geom.to_right('POINT(1 2)')
-
Shapely Integration¶
This module provides utility functions for integrating with Shapely.
Note
As GeoAlchemy 2 itself has no dependency on Shapely, applications using functions of this module have to ensure that Shapely is available.
-
geoalchemy2.shape.
from_shape
(shape, srid=-1, extended=False)[source]¶ Function to convert a Shapely geometry to a
geoalchemy2.types.WKBElement
.Parameters: - srid – An integer representing the spatial reference system. E.g.
4326
. Default value is-1
, which means no/unknown reference system. - extended – A boolean to switch between WKB and EWKB. Default value is False.
Example:
from shapely.geometry import Point wkb_element = from_shape(Point(5, 45), srid=4326) ewkb_element = from_shape(Point(5, 45), srid=4326, extended=True)
- srid – An integer representing the spatial reference system. E.g.
Alembic helpers¶
Some helpers to use with Alembic migration tool.
-
class
geoalchemy2.alembic_helpers.
AddGeospatialColumnOp
(table_name: str, column: Column, schema: Optional[str] = None, **kw)[source]¶ Bases:
alembic.operations.ops.AddColumnOp
Add a Geospatial Column in an Alembic migration context. This methodology originates from: https://alembic.sqlalchemy.org/en/latest/api/operations.html#operation-plugins
-
classmethod
add_geospatial_column
(operations, table_name, column, schema=None)[source]¶ This method is proxied on the
Operations
class, via theOperations.add_geospatial_column()
method.
-
classmethod
-
class
geoalchemy2.alembic_helpers.
CreateGeospatialIndexOp
(index_name: str, table_name: str, columns: Sequence[Union[str, TextClause, ColumnElement[Any]]], schema: Optional[str] = None, unique: bool = False, **kw)[source]¶ Bases:
alembic.operations.ops.CreateIndexOp
-
classmethod
batch_create_geospatial_index
(operations, index_name, columns, **kw)[source]¶ This method is proxied on the
BatchOperations
class, via theBatchOperations.create_geospatial_index()
method.
-
classmethod
-
class
geoalchemy2.alembic_helpers.
CreateGeospatialTableOp
(table_name: str, columns: Sequence[Union[Column, Constraint]], schema: Optional[str] = None, _namespace_metadata: Optional[MetaData] = None, _constraints_included: bool = False, **kw)[source]¶ Bases:
alembic.operations.ops.CreateTableOp
Create a Geospatial Table in an Alembic migration context. This methodology originates from: https://alembic.sqlalchemy.org/en/latest/api/operations.html#operation-plugins
-
class
geoalchemy2.alembic_helpers.
DropGeospatialColumnOp
(table_name: str, column_name: str, schema: Optional[str] = None, _reverse: Optional[AddColumnOp] = None, **kw)[source]¶ Bases:
alembic.operations.ops.DropColumnOp
Drop a Geospatial Column in an Alembic migration context.
-
classmethod
batch_drop_geospatial_column
(operations, column_name, **kw)[source]¶ This method is proxied on the
BatchOperations
class, via theBatchOperations.drop_geospatial_column()
method.
-
classmethod
-
class
geoalchemy2.alembic_helpers.
DropGeospatialIndexOp
(*args, column_name, **kwargs)[source]¶ Bases:
alembic.operations.ops.DropIndexOp
-
classmethod
batch_drop_geospatial_index
(operations, index_name, **kw)[source]¶ This method is proxied on the
BatchOperations
class, via theBatchOperations.drop_geospatial_index()
method.
-
classmethod
-
class
geoalchemy2.alembic_helpers.
DropGeospatialTableOp
(table_name: str, schema: Optional[str] = None, table_kw: Optional[MutableMapping[Any, Any]] = None, _reverse: Optional[CreateTableOp] = None)[source]¶ Bases:
alembic.operations.ops.DropTableOp
-
geoalchemy2.alembic_helpers.
add_geo_column
(context, revision, op)[source]¶ Replace the default AddColumnOp by a geospatial-specific one.
-
geoalchemy2.alembic_helpers.
add_geospatial_column
(operations, operation)[source]¶ Handle the actual column addition according to the dialect backend.
Parameters: - operations – Operations object from alembic base, defining high level migration operations.
- operation – AddGeospatialColumnOp call, with attributes for table_name, column_name, column_type, and optional keywords.
-
geoalchemy2.alembic_helpers.
create_geo_index
(context, revision, op)[source]¶ Replace the default CreateIndexOp by a geospatial-specific one.
-
geoalchemy2.alembic_helpers.
create_geo_table
(context, revision, op)[source]¶ Replace the default CreateTableOp by a geospatial-specific one.
-
geoalchemy2.alembic_helpers.
create_geospatial_index
(operations, operation)[source]¶ Handle the actual index creation according to the dialect backend.
Parameters: - operations – Operations object from alembic base, defining high level migration operations.
- operation – CreateGeospatialIndexOp call, with attributes for table_name, column_name, column_type, and optional keywords.
-
geoalchemy2.alembic_helpers.
create_geospatial_table
(operations, operation)[source]¶ Handle the actual table creation according to the dialect backend.
Parameters: - operations – Operations object from alembic base, defining high level migration operations.
- operation – CreateGeospatialTableOp call, with attributes for table_name, column_name, column_type, and optional keywords.
-
geoalchemy2.alembic_helpers.
drop_geo_column
(context, revision, op)[source]¶ Replace the default DropColumnOp by a geospatial-specific one.
-
geoalchemy2.alembic_helpers.
drop_geo_index
(context, revision, op)[source]¶ Replace the default DropIndexOp by a geospatial-specific one.
-
geoalchemy2.alembic_helpers.
drop_geo_table
(context, revision, op)[source]¶ Replace the default DropTableOp by a geospatial-specific one.
-
geoalchemy2.alembic_helpers.
drop_geospatial_column
(operations, operation)[source]¶ Handle the actual column removal according to the dialect backend.
Parameters: - operations – Operations object from alembic base, defining high level migration operations.
- operation – AddGeospatialColumnOp call, with attributes for table_name, column_name, column_type, and optional keywords.
-
geoalchemy2.alembic_helpers.
drop_geospatial_index
(operations, operation)[source]¶ Handle the actual index drop according to the dialect backend.
Parameters: - operations – Operations object from alembic base, defining high level migration operations.
- operation – DropGeospatialIndexOp call, with attributes for table_name, column_name, column_type, and optional keywords.
-
geoalchemy2.alembic_helpers.
drop_geospatial_table
(operations, operation)[source]¶ Handle the actual table removal according to the dialect backend.
Parameters: - operations – Operations object from alembic base, defining high level migration operations.
- operation – DropGeospatialTableOp call, with attributes for table_name, column_name, column_type, and optional keywords.
-
geoalchemy2.alembic_helpers.
render_add_geo_column
(autogen_context, op)[source]¶ Render the add_geospatial_column operation in migration script.
-
geoalchemy2.alembic_helpers.
render_create_geo_index
(autogen_context, op)[source]¶ Render the create_geospatial_index operation in migration script.
-
geoalchemy2.alembic_helpers.
render_create_geo_table
(autogen_context, op)[source]¶ Render the create_geospatial_table operation in migration script.
-
geoalchemy2.alembic_helpers.
render_drop_geo_column
(autogen_context, op)[source]¶ Render the drop_geospatial_column operation in migration script.
-
geoalchemy2.alembic_helpers.
render_drop_geo_index
(autogen_context, op)[source]¶ Render the drop_geospatial_index operation in migration script.
-
geoalchemy2.alembic_helpers.
render_drop_geo_table
(autogen_context, op)[source]¶ Render the drop_geospatial_table operation in migration script.
-
geoalchemy2.alembic_helpers.
render_item
(obj_type, obj, autogen_context)[source]¶ Add proper imports for spatial types.
Development¶
The code is available on GitHub: https://github.com/geoalchemy/geoalchemy2.
Contributors:
- Adrien Berchet (https://github.com/adrien-berchet)
- Éric Lemoine (https://github.com/elemoine)
- Dolf Andringa (https://github.com/dolfandringa)
- Frédéric Junod, Camptocamp SA (https://github.com/fredj)
- ijl (https://github.com/ijl)
- Loïc Gasser (https://github.com/loicgasser)
- Marcel Radischat (https://github.com/quiqua)
- rapto (https://github.com/rapto)
- Serge Bouchut (https://github.com/SergeBouchut)
- Tobias Bieniek (https://github.com/Turbo87)
- Tom Payne (https://github.com/twpayne)
Many thanks to Mike Bayer for his guidance and support! He also fostered the birth of GeoAlchemy 2.