Skip to content

Commit

Permalink
fix: Optionally append to an existing mbtiles database
Browse files Browse the repository at this point in the history
  • Loading branch information
robsavoye committed May 21, 2024
1 parent 9c37efb commit d18d33c
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions osm_fieldwork/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,20 +106,22 @@ def __init__(
self,
dbname: str = None,
suffix: str = "jpg",
append: bool = False,
):
"""Handle the sqlite3 database file.
Args:
dbname (str): The name of the output sqlite file
suffix (str): The image suffix, jpg or png usually
append (bool): Whether to append to or create the database
Returns:
(DataFile): An instance of this class
"""
self.db = None
self.cursor = None
if dbname:
self.createDB(dbname)
self.createDB(dbname, append)
self.dbname = dbname
self.metadata = None
self.toplevel = None
Expand All @@ -136,13 +138,14 @@ def addBounds(
"""
entry = str(bounds)
entry = entry[1 : len(entry) - 1].replace(" ", "")
self.cursor.execute(f"INSERT INTO metadata (name, value) VALUES('bounds', '{entry}')")
self.cursor.execute(f"INSERT OR IGNORE INTO metadata (name, value) VALUES('bounds', '{entry}') ")
# self.cursor.execute(f"INSERT INTO metadata (name, value) VALUES('minzoom', '9')")
# self.cursor.execute(f"INSERT INTO metadata (name, value) VALUES('maxzoom', '15')")

def createDB(
self,
dbname: str,
append: bool = False,
):
"""Create and sqlitedb in either mbtiles or Osman sqlitedb format.
Expand All @@ -151,11 +154,17 @@ def createDB(
"""
suffix = os.path.splitext(dbname)[1]

if os.path.exists(dbname):
if os.path.exists(dbname) and append == False:
os.remove(dbname)

self.db = sqlite3.connect(dbname)
self.cursor = self.db.cursor()
self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='tiles'")
exists = self.cursor.fetchone()
if exists and append:
logging.info("Appending to database file %s" % dbname)
return

if suffix == ".mbtiles":
self.cursor.execute("CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob)")
self.cursor.execute("CREATE INDEX tiles_idx on tiles (zoom_level, tile_column, tile_row)")
Expand Down

0 comments on commit d18d33c

Please sign in to comment.