database.py 11.6 KB
Newer Older
1
2
3
4
5
6
7
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
#!/usr/bin/env python3

# Copyright (C) 2021:
#   Helmholtz-Zentrum Potsdam Deutsches GeoForschungsZentrum GFZ
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.

import logging
import sqlite3


logger = logging.getLogger(__name__)


class SpatialiteDatabase:
    """The SpatialiteDatabase class represents a Spatialite database. It manages the
    database connection and cursor. Upon connection, the Spatialite extension is loaded.

    Args:
        database_filepath (str):
            File path for the Spatialite database file.
        spatialite_filepath (str):
            File path of the Spatialite extension.

    Attributes:
        database_filepath (str):
            Spatialite database file path.
        spatialite_filepath (str):
            File path to the Spatialite extension.
        connection (sqlite3.Connection):
            Database connection
        cursor (sqlite3.Cursor):
            Database cursor
    """

    def __init__(self, database_filepath, spatialite_filepath="mod_spatialite"):
        self.database_filepath = database_filepath
        self.spatialite_filepath = spatialite_filepath

        self.connection = None
        self.cursor = None

    def connect(self, init_spatial_metadata=True):
        """Connects to a database, loads the Spatialite extension and
        initializes it if requested. If the database file does not exist,
        it will be automatically created.

        Args:
            init_spatial_metadata (Bool):
                Defines if the spatial metadata should be initialized. This is not
                necessary if an existing Spatialite database is opened.
        """

        # Connect (if exists) or create SQLite database
        logger.debug("Connecting to database at %s" % self.database_filepath)
Karsten Prehn's avatar
Karsten Prehn committed
67
68
69
70
71
        try:
            self.connection = sqlite3.connect(self.database_filepath)
        except Exception:
            logger.exception("Error connecting to the database file")
            raise
72
73
74
75
76
        logger.debug("Connection to database established")

        # Load and initialize the Spatialite extension
        self.connection.enable_load_extension(True)
        sql_statement = "SELECT load_extension('%s');" % self.spatialite_filepath
Karsten Prehn's avatar
Karsten Prehn committed
77
78
79
80
81
82
83
        try:
            self.connection.execute(sql_statement)
        except sqlite3.OperationalError:
            logger.exception("Error loading spatial extension")
            raise
        logger.debug("Spatialite extension loaded")

84
        if init_spatial_metadata:
Karsten Prehn's avatar
Karsten Prehn committed
85
86
87
88
89
90
            try:
                self.connection.execute("SELECT InitSpatialMetaData(1);")
            except Exception:
                logger.exception("Error initializing spatial metadata")
                raise
            logger.debug("Spatial metadata initialized")
91
92

        # Debug output
Karsten Prehn's avatar
Karsten Prehn committed
93
94
95
96
97
        try:
            versions = self.connection.execute("SELECT sqlite_version(), spatialite_version()")
        except Exception:
            logger.exception("Error querying database versions")
            raise
98
99
100
101
102
        for row in versions:
            logger.debug("SQLite version: %s" % row[0])
            logger.debug("Spatialite version: %s" % row[1])

        self.cursor = self.connection.cursor()
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


class ExposureDatabase(SpatialiteDatabase):
    """
    The ExposureDatabase class represents a Spatialite database for
    exposure models. It is derived from the generic Database class.

    Args:
        database_filepath (str):
            File path for the exposure database file.
        spatialite_filepath (str):
            File path of the Spatialite extension.
    """

    def __init__(self, database_filepath, spatialite_filepath="mod_spatialite"):
        SpatialiteDatabase.__init__(self, database_filepath, spatialite_filepath)

    def create_tables(self):
        """
        Creates all necessary tables in the database. These are:
            BuildingAsset: Stores building-type assets
            TileAsset    : Stores tile-type assets
            Building     : Stores building geometries
            Taxonomy     : Stores taxonomy strings
            District     : Stores administrative districts
        """

        # Create table BuildingAsset
        sql_statement = "CREATE TABLE BuildingAsset ("
        sql_statement += "id           TEXT, "
        sql_statement += "taxonomy_id  INTEGER, "
        sql_statement += "number       REAL, "
        sql_statement += "structural   REAL, "
        sql_statement += "night        REAL, "
        sql_statement += "occupancy    TEXT, "
        sql_statement += "district_id  TEXT, "
        sql_statement += "building_id  INTEGER)"
        self.connection.execute(sql_statement)
        logger.debug("Table BuildingAsset created")

        # Create table TileAsset
        sql_statement = "CREATE TABLE TileAsset ("
        sql_statement += "id           TEXT, "
        sql_statement += "taxonomy_id  INTEGER, "
        sql_statement += "number       REAL, "
        sql_statement += "structural   REAL, "
        sql_statement += "night        REAL, "
        sql_statement += "occupancy    TEXT, "
        sql_statement += "district_id  TEXT, "
152
        sql_statement += "quadkey      TEXT)"
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
        self.connection.execute(sql_statement)
        logger.debug("Table TileAsset created")

        # Create table Building
        sql_statement = "CREATE TABLE Building ("
        sql_statement += "id       INTEGER, "
        sql_statement += "quadkey  TEXT)"
        self.connection.execute(sql_statement)
        sql_statement = "SELECT AddGeometryColumn('Building', 'geom', 4326, "
        sql_statement += "'MULTIPOLYGON', 'XY')"
        self.connection.execute(sql_statement)
        logger.debug("Table Building created")

        # Create table Taxonomy
        sql_statement = "CREATE TABLE Taxonomy ("
        sql_statement += "id               INTEGER, "
        sql_statement += "taxonomy_string  TEXT)"
        self.connection.execute(sql_statement)
        logger.debug("Table Taxonomy created")

        # Create table District
        sql_statement = "CREATE TABLE District ("
        sql_statement += "id          INTEGER, "
        sql_statement += "admin_id    TEXT, "
        sql_statement += "admin_name  TEXT)"
        self.connection.execute(sql_statement)
        logger.debug("Table District created")

    def insert_building_asset(
        self,
        building_asset_id,
        taxonomy_id,
        number,
        structural,
        night,
        occupancy,
        district_id,
        building_id,
    ):
        """
        Inserts a building-type asset to the BuildingAsset table.

        Args:
            building_asset_id (str):
                ID of the building asset
            taxonomy_id (int):
                ID of the taxonomy of the building asset (corresponds to Taxonomy.id)
            number (float):
                Number of buildings of the building asset
            structural (float):
                Structural value of the building asset
            night (float):
                Number of people in the buildings of this asset (sum)
            occupancy (str):
                Occupancy type of the building asset
            district_id (int):
                ID of the district (corresponds to District.id)
            building_id (int):
                ID of the building(corresponds to Building.id)
        """

        sql_statement = "INSERT INTO BuildingAsset "
        sql_statement += "(id, taxonomy_id, number, structural, night, "
        sql_statement += "occupancy, district_id, building_id) "
        sql_statement += "VALUES ('%s', %d, %f, %f, %f, '%s', %d, %d)" % (
            building_asset_id,
            taxonomy_id,
            number,
            structural,
            night,
            occupancy,
            district_id,
            building_id,
        )
        self.cursor.execute(sql_statement)

    def insert_tile_asset(
        self,
        tile_asset_id,
        taxonomy_id,
        number,
        structural,
        night,
        occupancy,
        district_id,
        quadkey,
    ):
        """
        Inserts a tile-type asset to the TileAsset table.

        Args:
            tile_asset_id (str):
                ID of the tile asset
            taxonomy_id (int):
                ID of the taxonomy of the tile asset (corresponds to Taxonomy.id)
            number (float):
                Number of buildings of the tile asset
            structural (float):
                Structural value of the tile asset (sum over all buildings in this asset)
            night (float):
                Number of people in the buildings of the tile asset (sum)
            occupancy (str):
                Occupancy type of the tile asset
            district_id (int):
                ID of the district (corresponds to District.id)
            quadkey (str):
                ID (Quadkey) of the tile the tile asset is located in
        """

        sql_statement = "INSERT INTO TileAsset "
        sql_statement += "(id, taxonomy_id, number, structural, night, "
        sql_statement += "occupancy, district_id, quadkey) "
        sql_statement += "VALUES ('%s', %d, %f, %f, %f, '%s', %d, '%s')" % (
            tile_asset_id,
            taxonomy_id,
            number,
            structural,
            night,
            occupancy,
            district_id,
            quadkey,
        )
        self.cursor.execute(sql_statement)

    def insert_building(self, building_id, geom, quadkey):
        """
        Inserts a building and its geometry to the Building table.

        Args:
            building_id (int):
                ID of the building
            geom (geom):
                Geometry of the building (multi-polygon)
            quadkey (str):
                ID (Quadkey) of the tile the building centroid is located in
        """

        sql_statement = "INSERT INTO Building "
        sql_statement += "(id, geom, quadkey) "
        sql_statement += "VALUES (%d, %s, '%s')" % (building_id, geom, quadkey)
        self.cursor.execute(sql_statement)

    def insert_taxonomy(self, taxonomy_id, taxonomy_string):
        """
        Inserts a taxonomy ID and its respective description to the Taxonomy table.

        Args:
            taxonomy_id (int):
                ID of the taxonomy item
            taxonomy_string (str):
                Taxonomy string following the GEM Taxonomy
        """

        sql_statement = "INSERT INTO Taxonomy "
        sql_statement += "(id, taxonomy_string) "
        sql_statement += "VALUES (%d, '%s')" % (taxonomy_id, taxonomy_string)
        self.cursor.execute(sql_statement)

    def insert_district(self, district_id, admin_id, admin_name):
        """
        Inserts a district ID and name to the District table.

        Args:
            district_id (int):
                ID of the district dataset
            admin_id (str):
                Official ID of the district
            admin_name (str):
                Official Name of the district
        """

        sql_statement = "INSERT INTO District "
        sql_statement += "(id, admin_id, admin_name) "
        sql_statement += "VALUES (%d, '%s', '%s')" % (district_id, admin_id, admin_name)
        self.cursor.execute(sql_statement)