From 7e4b9997c2cec4c2af42bd3088847a81c970b6fc Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sun, 12 Apr 2020 20:46:51 -0700 Subject: [PATCH] Database(..., recreate=True) option, refs #97 --- docs/python-api.rst | 10 +++++++++- sqlite_utils/db.py | 12 +++++++----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/docs/python-api.rst b/docs/python-api.rst index 1b2a2c5..310fb01 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -15,7 +15,15 @@ Database objects are constructed by passing in either a path to a file on disk o db = Database("my_database.db") -This will create ``my_database.db`` if it does not already exist. You can also pass in an existing SQLite connection: +This will create ``my_database.db`` if it does not already exist. + +If you want to recreate a database from scratch (first removing the existing file from disk if it already exists) you can use the ``recreate=True`` argument: + +.. code-block:: python + + db = Database("my_database.db", recreate=True) + +Instead of a file path you can pass in an existing SQLite connection: .. code-block:: python diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index d51ede3..3f9bb6f 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -4,6 +4,7 @@ import datetime import hashlib import itertools import json +import os import pathlib SQLITE_MAX_VARS = 999 @@ -96,17 +97,18 @@ class PrimaryKeyRequired(Exception): class Database: - def __init__(self, filename_or_conn=None, memory=False): + def __init__(self, filename_or_conn=None, memory=False, recreate=False): assert (filename_or_conn is not None and not memory) or ( filename_or_conn is None and memory ), "Either specify a filename_or_conn or pass memory=True" - if memory: + if memory or filename_or_conn == ":memory:": self.conn = sqlite3.connect(":memory:") - elif isinstance(filename_or_conn, str): - self.conn = sqlite3.connect(filename_or_conn) - elif isinstance(filename_or_conn, pathlib.Path): + elif isinstance(filename_or_conn, (str, pathlib.Path)): + if recreate and os.path.exists(filename_or_conn): + os.remove(filename_or_conn) self.conn = sqlite3.connect(str(filename_or_conn)) else: + assert not recreate, "recreate cannot be used with connections, only paths" self.conn = filename_or_conn def __getitem__(self, table_name):