tinydb icon indicating copy to clipboard operation
tinydb copied to clipboard

db.clear_cache() does not re-read new db.json file

Open ktdreyer opened this issue 2 months ago • 0 comments

I'm writing a transaction context manager (similar to https://github.com/eugene-eeo/tinyrecord) that can potentially replace the underlying db.json file with a newer one (from a Git repo).

The docs state:

To clear the cache and read data from the storage again you can use db.clear_cache().

In my tests, when I call db.clear_cache(), read queries will still return old data. For example:

import os
from tinydb import TinyDB, Query

# Write some data to the file:
db = TinyDB('db.json')
db.insert({'type': 'apple', 'count': 7})

# Delete the file and clear the cache:
os.unlink('db.json')
db.clear_cache()

# Queries still show results, for example:
results = db.all()
print(results)   # prints the "apple" record

To fix it, I have to reach deep into the table's storage and re-open the file handle:

# Re-initialize storage file handle to the new inode
db.storage.close()
db.storage._handle = open('db.json', mode=db.storage._mode)

ktdreyer avatar Jun 26 '24 20:06 ktdreyer