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

feat: persist empty tables #518

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
8 changes: 8 additions & 0 deletions tests/test_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,11 @@ def test_table_repr(db):
def test_truncate_table(db):
db.truncate()
assert db._get_next_id() == 1


def test_persist_table(db):
db.table("persisted", persist_empty=True)
assert "persisted" in db.tables()

db.table("nonpersisted", persist_empty=False)
assert "nonpersisted" not in db.tables()
10 changes: 7 additions & 3 deletions tinydb/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class Table:
:param storage: The storage instance to use for this table
:param name: The table name
:param cache_size: Maximum capacity of query cache
:param persist_empty: Store new table even with no operations on it
"""

#: The class used to represent documents
Expand All @@ -98,7 +99,8 @@ def __init__(
self,
storage: Storage,
name: str,
cache_size: int = default_query_cache_capacity
cache_size: int = default_query_cache_capacity,
persist_empty: bool = False
):
"""
Create a table instance.
Expand All @@ -110,6 +112,8 @@ def __init__(
= self.query_cache_class(capacity=cache_size)

self._next_id = None
if persist_empty:
self._update_table(lambda table: table.clear())

def __repr__(self):
args = [
Expand Down Expand Up @@ -163,7 +167,7 @@ def updater(table: dict):
if doc_id in table:
raise ValueError(f'Document with ID {str(doc_id)} '
f'already exists')

# By calling ``dict(document)`` we convert the data we got to a
# ``dict`` instance even if it was a different class that
# implemented the ``Mapping`` interface
Expand Down Expand Up @@ -676,7 +680,7 @@ def _read_table(self) -> Dict[str, Mapping]:
"""
Read the table data from the underlying storage.

Documents and doc_ids are NOT yet transformed, as
Documents and doc_ids are NOT yet transformed, as
we may not want to convert *all* documents when returning
only one document for example.
"""
Expand Down