Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix table updates #49

Merged
merged 2 commits into from
Mar 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 33 additions & 9 deletions src/audio_feeder/sql_database_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,21 +300,45 @@ def _save_table(
) -> None:
table_type = oh.TYPE_MAPPING[oh.TABLE_MAPPING[table_name]]

# Delete anything not in `table_contents`
stmt = sa.delete(table_type).where(
sa.column("id").not_in(table_contents.keys())
)
session.execute(stmt)

try:
session.add_all(list(table_contents.values()))
except orm.exc.UnmappedInstanceError:
# If the instances were created before the ORM mapping was set up,
# instrumentation won't be set up on the instances, so we need to
# create new copies of the instances (at least until we find a
# better way to do this.
session.add_all(
[table_entry.copy() for table_entry in table_contents.values()]
# Find all the objects that have been modified, either by mutating them
# in-place, replacing them with a new schema object or because they
# are new to the table.
to_update: typing.MutableMapping[ID, ot.SchemaObject] = {}
to_replace: typing.MutableMapping[ID, ot.SchemaObject] = {}

for key, obj in table_contents.items():
insp = sa.inspect(obj)
if insp.modified:
if insp.has_identity:
# These objects already exist in the table
to_update[key] = obj
else:
# These are either new or are using a new instance
to_replace[key] = obj

if to_replace:
# Delete all rows where the object in the table dictionary is using
# a new instance.
replace_stmt = sa.delete(table_type).where(
sa.column("id").in_(to_replace.keys())
)
session.execute(replace_stmt)

for to_add in (to_replace, to_update):
try:
session.add_all(to_add.values())
except orm.exc.UnmappedInstanceError:
# If the instances were created before the ORM mapping was set
# up, instrumentation won't be set up on the instances, so we
# need to create new copies of the instances (at least until we
# find a better way to do this.
session.add_all([table_entry.copy() for table_entry in to_add.values()])

def save_table(self, table_name: TableName, table_contents: Table) -> None:
with self.session() as session:
Expand Down
35 changes: 35 additions & 0 deletions tests/test_database_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import sqlite3
import typing

import attrs
import pytest

from audio_feeder import _db_types
Expand Down Expand Up @@ -148,6 +149,7 @@ def test_save_table(db_handler: _db_types.DatabaseHandler) -> None:


def test_save_database_remove(db_handler: _db_types.DatabaseHandler) -> None:
"""Test removing a key from the database."""
db_tables = db_handler.load_database()

book_ids = [book_id for book_id in db_tables["books"].keys()]
Expand All @@ -167,6 +169,39 @@ def test_save_database_remove(db_handler: _db_types.DatabaseHandler) -> None:
assert book_id in books_table


def test_update_database_mutate(db_handler: _db_types.DatabaseHandler) -> None:
db_tables = db_handler.load_database()

author_id, author = next(iter(db_tables["authors"].items()))
assert author.description is None
author.description = "The first author in the table"

db_handler.save_table("authors", db_tables["authors"])

author_table = db_handler.load_table("authors")
assert author_table[author_id].description == "The first author in the table"


def test_update_database_replace(db_handler: _db_types.DatabaseHandler) -> None:
db_tables = db_handler.load_database()

((book_id, book),) = filter(
lambda x: x[1].title == "Dracula", db_tables["books"].items()
)

book_kwargs = attrs.asdict(book)
book_kwargs["series_name"] = "Dracula"
book_kwargs["series_number"] = 1
replacement_book = oh.Book(**book_kwargs)
db_tables["books"][book_id] = replacement_book

db_handler.save_table("books", db_tables["books"])

books_table = db_handler.load_table("books")
assert books_table[book_id].series_name == "Dracula"
assert books_table[book_id].series_number == 1


@pytest.mark.parametrize(
"db_relpath, expected_version",
(
Expand Down