edelooff / sqlalchemy-json

Full-featured JSON type with mutation tracking for SQLAlchemy
http://variable-scope.com/posts/mutation-tracking-in-nested-json-structures-using-sqlalchemy
BSD 2-Clause "Simplified" License
189 stars 34 forks source link

How to get a read-only copy? #46

Closed torotil closed 1 year ago

torotil commented 1 year ago

In some most cases I use a JSON to store some configs to the database. When editing the config it’s very comfortable to be able to rely on the mutation tracking, when reading the config I want to make sure that the config is not modified. This is especially important when the config needs some normalization before being used.

According to my tests neither copy() nor deepcopy() do the job.

What’s the best way to achieve this? Is it worth implementing the __copy__() and __deepcopy__() magic methods?

torotil commented 1 year ago

Ok, I finally came around to write a test case which fails for version 0.5.0 but not for the main branch. It seems [#37] fixed this as well.

def test_deepcopy(session, article):
    article_copy = Article(
        author=article.author,
        content=article.content,
        references=copy.deepcopy(article.references),
    )
    article_copy.references["github.com"]["someone/somerepo"] = 10
    article_copy.references["modified"] = True
    assert "someone/somerepo" not in article.references["github.com"]
    assert not session.dirty  # Fails for 0.5.0

So this will be fixed for me as soon as 0.6.0 is released.