From 2fecf99ade208e3a80958ee4fc28ff62549c575b Mon Sep 17 00:00:00 2001 From: Florian Apolloner Date: Fri, 2 Dec 2022 09:43:18 +0100 Subject: [PATCH] Refs #33308 -- Made PostGISAdapter do not use psycopg2's Binary(). --- .../gis/db/backends/postgis/adapter.py | 20 +++++++++---------- .../gis/db/backends/postgis/pgraster.py | 3 +-- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/django/contrib/gis/db/backends/postgis/adapter.py b/django/contrib/gis/db/backends/postgis/adapter.py index 20b0327d5c..19d3a60492 100644 --- a/django/contrib/gis/db/backends/postgis/adapter.py +++ b/django/contrib/gis/db/backends/postgis/adapter.py @@ -1,7 +1,7 @@ """ This object provides quoting for GEOS geometries into PostgreSQL/PostGIS. """ -from psycopg2 import Binary +from psycopg2 import extensions from psycopg2.extensions import ISQLQuote from django.contrib.gis.db.backends.postgis.pgraster import to_pgraster @@ -19,7 +19,6 @@ class PostGISAdapter: # the adaptor) and the SRID from the geometry or raster. if self.is_geometry: self.ewkb = bytes(obj.ewkb) - self._adapter = Binary(self.ewkb) else: self.ewkb = to_pgraster(obj) @@ -48,13 +47,12 @@ class PostGISAdapter: def _fix_polygon(cls, poly): return poly - def prepare(self, conn): - """ - This method allows escaping the binary in the style required by the - server's `standard_conforming_string` setting. - """ - if self.is_geometry: - self._adapter.prepare(conn) + def _quote(self, value): + adapted = extensions.adapt(value) + if hasattr(adapted, "encoding"): + adapted.encoding = "utf8" + # getquoted() returns a quoted bytestring of the adapted value. + return adapted.getquoted().decode() def getquoted(self): """ @@ -64,8 +62,8 @@ class PostGISAdapter: # Psycopg will figure out whether to use E'\\000' or '\000'. return b"%s(%s)" % ( b"ST_GeogFromWKB" if self.geography else b"ST_GeomFromEWKB", - self._adapter.getquoted(), + self._quote(self.ewkb).encode(), ) else: # For rasters, add explicit type cast to WKB string. - return b"'%s'::raster" % self.ewkb.encode() + return b"'%s'::raster" % self.ewkb.hex().encode() diff --git a/django/contrib/gis/db/backends/postgis/pgraster.py b/django/contrib/gis/db/backends/postgis/pgraster.py index 22794342ca..c231b4863f 100644 --- a/django/contrib/gis/db/backends/postgis/pgraster.py +++ b/django/contrib/gis/db/backends/postgis/pgraster.py @@ -149,5 +149,4 @@ def to_pgraster(rast): # Add packed header and band data to result result += bandheader + band.data(as_memoryview=True) - # Convert raster to hex string before passing it to the DB. - return result.hex() + return result