Create schema submodule holding versioned schemas

This is meant to hold schemas and migrations. It contains an
`__init__.py` due to a limitation of `importlib.resources` outlined in
detail here: https://github.com/python/importlib_resources/issues/58

Eventually the schema submodule will handle automatic migration of older
databases when importing into new stores.
This commit is contained in:
Jacob Hinkle 2022-09-21 13:50:46 -04:00
parent e75af52765
commit d0f113645b
5 changed files with 15 additions and 23 deletions

View File

@ -8,16 +8,13 @@ import sqlite3
schema_version = 0
def init(path):
"""
Initialize a data store directory.
"""
if os.path.exists(path):
raise FileExistsError(f"Refusing to overwrite existing database {path}")
schema = importlib.resources.open_text("nancy", "schema.sql").read()
conn = sqlite3.connect(path)
conn.cursor().executescript(schema)
return conn
def init_schema(cur):
"""Initialize a database following the current schema."""
schema = importlib.resources.read_text(
"nancy.schema",
f"version{schema_version}.sql",
)
cur.executescript(schema)
def connect(path):

View File

View File

@ -59,9 +59,8 @@ class Store:
f"File {db_path} exists. Refusing to re-initialize",
)
# initialize a database in the target directory
schema = importlib.resources.open_text("nancy", "schema.sql").read()
conn = sqlite3.connect(db_path)
conn.cursor().executescript(schema)
db.init_schema(conn.cursor())
new_store = cls(directory, conn)
new_store.record_machine_description()

View File

@ -10,17 +10,13 @@ import sqlite3
@pytest.fixture
def temp_db():
"""Create an in-memory database that follow's the nancy schema"""
conn = sqlite3.connect(':memory:')
with sqlite3.connect(':memory:') as conn:
cur = conn.cursor()
#import importlib
#schema = importlib.resources.open_text("nancy", "schema.sql").read()
schema = open(os.path.join(
os.path.dirname(__file__),
'../src/nancy/schema.sql',
), 'r').read()
cur.executescript(schema)
from nancy import db
db.init_schema(cur)
yield cur
conn.close()
@pytest.fixture