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

Empty table does not persist #513

Open
dmarsic opened this issue Feb 18, 2023 · 1 comment
Open

Empty table does not persist #513

dmarsic opened this issue Feb 18, 2023 · 1 comment

Comments

@dmarsic
Copy link

dmarsic commented Feb 18, 2023

Hi,

I attempted to create empty tables, similar to CREATE TABLE in SQL. TinyDB currently does not persist empty tables:

  1. My initial approach didn't create a table because Table does not call _update_table() when creating an instance.
In [1]: from tinydb import TinyDB

In [2]: db = TinyDB("example.json")

In [3]: t = db.table("emptytbl")

In [4]: db.close()

In [5]: from pathlib import Path

In [6]: Path("example.json").read_text()
Out[6]: ''
  1. Workaround with adding truncate() call to ensure that the table gets written.
In [1]: from tinydb import TinyDB

In [2]: db = TinyDB("example.json")

In [3]: t = db.table("emptytbl")

In [4]: t.truncate()

In [5]: db.close()

In [6]: from pathlib import Path

In [7]: Path("example.json").read_text()
Out[7]: '{"emptytbl": {}}'

I'm new to the project so I'm not sure if this is intentional. I propose adding a flag to Table, persist_empty: bool = False, and if the flag is true then call _update_table to ensure an empty table gets immediately written.

I'm happy to submit a PR if that makes sense.

@msiemens
Copy link
Owner

That's an interesting point. You're right, right now calling table(...) is a lazy operation that does not touch the file system until data is written to the table for the first time. I'd be happy to accept a PR for this 🙂

dmarsic added a commit to dmarsic/tinydb that referenced this issue Feb 27, 2023
Allows persisting empty tables when parameter `persist_empty` is set.

Related issue: msiemens#513
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants