Left: | ||
Right: |
LEFT | RIGHT |
---|---|
(no file at all) | |
1 # This file is part of trytond_backend_gis. The COPYRIGHT file at the top | |
ced
2017/09/20 17:28:20
Wrong name
ced
2017/09/20 17:28:20
I find that the file should be trytond_gis/backend
| |
2 # level of this repository contains the full copyright notices and license | |
3 # terms. | |
4 import binascii | |
5 | |
6 from geomet import wkb | |
7 from psycopg2.extensions import register_adapter, new_type, register_type, AsIs | |
8 | |
9 from trytond.backend.postgresql.database import Database as PGDatabase | |
10 from trytond.backend.postgresql.database import ( | |
11 DatabaseIntegrityError, DatabaseOperationalError) | |
12 | |
13 from trytond_gis import _GeoJSON | |
14 | |
15 __all__ = ['Database', 'DatabaseIntegrityError', 'DatabaseOperationalError'] | |
16 | |
17 | |
18 def ewkb2geojson(value, cursor): | |
19 if value is None: | |
20 return None | |
21 return wkb.loads(binascii.a2b_hex(value)) | |
22 | |
23 | |
24 class Database(PGDatabase): | |
25 | |
26 _GIS_OIDS = None | |
27 | |
28 @classmethod | |
29 def create(cls, connection, database_name): | |
30 super(Database, cls).create(connection, database_name) | |
31 | |
32 database = cls(database_name) | |
33 with database.get_connection() as db_connection: | |
34 cursor = db_connection.cursor() | |
35 cursor.execute("CREATE EXTENSION postgis") | |
36 | |
37 def get_connection(self, autocommit=False, readonly=False): | |
38 conn = super(Database, self).get_connection(autocommit, readonly) | |
39 | |
40 if self._GIS_OIDS is None: | |
41 cursor = conn.cursor() | |
42 cursor.execute( | |
43 "SELECT 1 FROM pg_extension WHERE extname='postgis'") | |
44 if cursor.fetchone(): | |
45 cursor.execute('SELECT NULL::geometry, NULL::geography') | |
46 geometry_oid = cursor.description[0][1] | |
47 geography_oid = cursor.description[1][1] | |
48 self._GIS_OIDS = { | |
49 'geometry': geometry_oid, | |
50 'geography': geography_oid, | |
51 } | |
52 | |
53 GEOMETRY = new_type((geometry_oid,), 'GEOMETRY', ewkb2geojson) | |
54 register_type(GEOMETRY) | |
55 GEOGRAPHY = new_type( | |
56 (geography_oid,), 'GEOGRAPHY', ewkb2geojson) | |
57 register_type(GEOGRAPHY) | |
58 | |
59 return conn | |
60 | |
61 register_adapter(_GeoJSON, | |
62 lambda value: AsIs("'%s'" % binascii.b2a_hex(wkb.dumps(value)).upper())) | |
LEFT | RIGHT |