mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-07-23 01:14:31 +02:00
Database(..., recreate=True) option, refs #97
This commit is contained in:
parent
635c91475a
commit
7e4b9997c2
2 changed files with 16 additions and 6 deletions
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue