Commit f3b3e02b authored by Danijel Schorlemmer's avatar Danijel Schorlemmer
Browse files

Introducing the exposurelib for the elementary Spatialite database class

parent ea175fb2
Pipeline #21634 passed with stage
in 1 minute and 54 seconds
......@@ -18,9 +18,9 @@
import logging
import sqlite3
import csv
import numpy
from exposurelib.database import SpatialiteDatabase
from collections import namedtuple
from shapely import wkt
from shapely.affinity import translate
......@@ -30,59 +30,7 @@ from pygeotile.tile import Tile
logger = logging.getLogger(__name__)
class Database:
"""The Database 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.
"""
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 create_connection_and_cursor(self, init_spatial_metadata=True):
"""Create a database connection, loads the Spatialite extension and initializes it.
Attributes:
None
Returns:
None
"""
# Create SQLite database for the exposure data
logger.debug("Connecting to database at %s" % self.database_filepath)
self.connection = sqlite3.connect(self.database_filepath)
logger.debug("Connection to database established")
self.connection.enable_load_extension(True)
sql_statement = "SELECT load_extension('%s');" % self.spatialite_filepath
self.connection.execute(sql_statement)
if init_spatial_metadata:
self.connection.execute("SELECT InitSpatialMetaData(1);")
logger.debug("Spatialite extension loaded and initialized")
versions = self.connection.execute("SELECT sqlite_version(), spatialite_version()")
for row in versions:
logger.debug("SQLite version: %s" % row[0])
logger.debug("Spatialite version: %s" % row[1])
self.cursor = self.connection.cursor()
class CoquimboDatabase(Database):
class CoquimboDatabase(SpatialiteDatabase):
"""The CoquimboDatabase class represents a Spatialite database for the Coquimbo
exposure model. It is derived from the generic Database class.
......@@ -98,7 +46,7 @@ class CoquimboDatabase(Database):
"""
def __init__(self, database_filepath, spatialite_filepath="mod_spatialite"):
Database.__init__(self, database_filepath, spatialite_filepath)
SpatialiteDatabase.__init__(self, database_filepath, spatialite_filepath)
# Coquimbo bounding box
BoundingBox = namedtuple("BoundingBox", ["lon_min", "lon_max", "lat_min", "lat_max"])
......@@ -421,8 +369,8 @@ class CoquimboDatabase(Database):
File path to a geopackage with OpenStreetMap buildings.
"""
building_db = Database(buildings_filepath, self.spatialite_filepath)
building_db.create_connection_and_cursor()
building_db = SpatialiteDatabase(buildings_filepath, self.spatialite_filepath)
building_db.connect()
sql_statement = "SELECT AsWKT(CastAutomagic(geom)), osm_id, osm_way_id FROM obm"
building_db.cursor.execute(sql_statement)
......
......@@ -22,7 +22,7 @@ import sys
import argparse
import os
import sqlite3
from database import CoquimboDatabase # pylint: disable=E0611,E0401
from .database import CoquimboDatabase # pylint: disable=E0611,E0401
# Add a logger printing error, warning, info and debug messages to the screen
......@@ -94,7 +94,7 @@ def main():
exit()
db = CoquimboDatabase(database_filepath, spatialite_filepath)
try:
db.create_connection_and_cursor()
db.connect()
except sqlite3.OperationalError:
logger.warning("Spatialite extension cannot be loaded. Exiting ...")
exit()
......
......@@ -10,7 +10,12 @@ setup(
version="0.1",
description="Create exposure model for Coquimbo",
license="AGPLv3+",
install_requires=["shapely", "geopandas", "pygeotile"],
install_requires=[
"shapely",
"geopandas",
"pygeotile",
"exposurelib@https://git.gfz-potsdam.de/dynamicexposure/globaldynamicexposure/exposure-lib/-/archive/master/exposure-lib-master.zip", # noqa: E501
],
extras_require={
"tests": tests_require,
"linters": linters_require,
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment