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 schema_version = 0
def init(path): def init_schema(cur):
""" """Initialize a database following the current schema."""
Initialize a data store directory. schema = importlib.resources.read_text(
""" "nancy.schema",
if os.path.exists(path): f"version{schema_version}.sql",
raise FileExistsError(f"Refusing to overwrite existing database {path}") )
schema = importlib.resources.open_text("nancy", "schema.sql").read() cur.executescript(schema)
conn = sqlite3.connect(path)
conn.cursor().executescript(schema)
return conn
def connect(path): def connect(path):

View File

View File

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

View File

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