| 1 |
""" |
| 2 |
This object provides quoting for GEOS geometries into PostgreSQL/PostGIS. |
| 3 |
""" |
| 4 |
|
| 5 |
from django.contrib.gis.db.backends.postgis.pgraster import to_pgraster |
| 6 |
from django.contrib.gis.geos import GEOSGeometry |
| 7 |
from django.db.backends.postgresql.psycopg_any import sql |
| 8 |
|
| 9 |
|
| 10 |
class PostGISAdapter: |
| 11 |
def __init__(self, obj, geography=False): |
| 12 |
""" |
| 13 |
Initialize on the spatial object. |
| 14 |
""" |
| 15 |
self.is_geometry = isinstance(obj, (GEOSGeometry, PostGISAdapter)) |
| 16 |
|
| 17 |
# Getting the WKB (in string form, to allow easy pickling of |
| 18 |
# the adaptor) and the SRID from the geometry or raster. |
| 19 |
if self.is_geometry: |
| 20 |
self.ewkb = bytes(obj.ewkb) |
| 21 |
else: |
| 22 |
self.ewkb = to_pgraster(obj) |
| 23 |
|
| 24 |
self.srid = obj.srid |
| 25 |
self.geography = geography |
| 26 |
|
| 27 |
def __conform__(self, proto): |
| 28 |
"""Does the given protocol conform to what Psycopg2 expects?""" |
| 29 |
from psycopg2.extensions import ISQLQuote |
| 30 |
|
| 31 |
if proto == ISQLQuote: |
| 32 |
return self |
| 33 |
else: |
| 34 |
raise Exception( |
| 35 |
"Error implementing psycopg2 protocol. Is psycopg2 installed?" |
| 36 |
) |
| 37 |
|
| 38 |
def __eq__(self, other): |
| 39 |
return isinstance(other, PostGISAdapter) and self.ewkb == other.ewkb |
| 40 |
|
| 41 |
def __hash__(self): |
| 42 |
return hash(self.ewkb) |
| 43 |
|
| 44 |
def __str__(self): |
| 45 |
return self.getquoted().decode() |
| 46 |
|
| 47 |
@classmethod |
| 48 |
def _fix_polygon(cls, poly): |
| 49 |
return poly |
| 50 |
|
| 51 |
def getquoted(self): |
| 52 |
""" |
| 53 |
Return a properly quoted string for use in PostgreSQL/PostGIS. |
| 54 |
""" |
| 55 |
if self.is_geometry: |
| 56 |
# Psycopg will figure out whether to use E'\\000' or '\000'. |
| 57 |
return b"%s(%s)" % ( |
| 58 |
b"ST_GeogFromWKB" if self.geography else b"ST_GeomFromEWKB", |
| 59 |
sql.quote(self.ewkb).encode(), |
| 60 |
) |
| 61 |
else: |
| 62 |
# For rasters, add explicit type cast to WKB string. |
| 63 |
return b"'%s'::raster" % self.ewkb.hex().encode() |