Commit 96f5dcf8 authored by Danijel Schorlemmer's avatar Danijel Schorlemmer Committed by Danijel Schorlemmer
Browse files

Implemented a Database class and the call to create a Spatialite database

parent 308f9c43
Pipeline #19907 passed with stage
in 49 seconds
#!/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
# Initialize log
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:
File path for the Spatialite database file.
spatialite_filepath:
File path of the Spatialite extension.
Attributes:
self.database_filepath (str): Spatialite database file path.
self.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()
#!/usr/bin/env python3 #!/usr/bin/env python3
# Copyright (c) 2020-2021: # Copyright (C) 2021:
# Helmholtz-Zentrum Potsdam Deutsches GeoForschungsZentrum GFZ # Helmholtz-Zentrum Potsdam Deutsches GeoForschungsZentrum GFZ
# #
# This program is free software: you can redistribute it and/or modify it # This program is free software: you can redistribute it and/or modify it
...@@ -16,8 +16,14 @@ ...@@ -16,8 +16,14 @@
# You should have received a copy of the GNU Affero General Public License # 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/. # along with this program. If not, see http://www.gnu.org/licenses/.
import logging import logging
import sys import sys
import argparse
import os
import sqlite3
from database import Database # pylint: disable=E0611,E0401
# Add a logger printing error, warning, info and debug messages to the screen # Add a logger printing error, warning, info and debug messages to the screen
logger = logging.getLogger() logger = logging.getLogger()
...@@ -26,13 +32,48 @@ logger.addHandler(logging.StreamHandler(sys.stdout)) ...@@ -26,13 +32,48 @@ logger.addHandler(logging.StreamHandler(sys.stdout))
def main(): def main():
description = "Creates the exposure model for the area of Coquimbo "
description += "and stores it in a Spatialite database. "
description += "Further options allow for output for the loss-calculator."
parser = argparse.ArgumentParser(description=description)
parser.add_argument("command", type=str, help="'create' to create the exposure database")
parser.add_argument(
"-d",
"--database",
required=True,
type=str,
help="File path of the database",
)
parser.add_argument(
"-s",
"--spatialite_extension",
required=False,
type=str,
default="mod_spatialite",
help="File path of the spatialite extension (default: mod_spatialite)",
)
args = parser.parse_args()
# Read arguments from command line
command = args.command
database_filepath = args.database
spatialite_filepath = args.spatialite_extension
# Example logging output db = Database(database_filepath, spatialite_filepath)
# This can be either logger.error(), logger.warning(), logger.info() or logger.debug()
logger.info("Creating exposure model of Coquimbo")
# Leave the program if command == "create":
sys.exit() if os.path.exists(database_filepath):
logger.warning("Database exists. Exiting ...")
exit()
try:
db.create_connection_and_cursor()
except sqlite3.OperationalError:
logger.warning("Spatialite extension cannot be loaded. Exiting ...")
exit()
else:
logger.warning("Command not recognized. Exiting ...")
if __name__ == "__main__": if __name__ == "__main__":
......
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