msiemens / tinydb

TinyDB is a lightweight document oriented database optimized for your happiness :)
https://tinydb.readthedocs.org
MIT License
6.81k stars 548 forks source link

Document ID and existing unique value in the document #545

Closed aptly-io closed 1 month ago

aptly-io commented 1 year ago

When inserting documents and knowing a certain document property value (e.g. house-id) is unique, is there a way to tell tinydb to use that house-id as document ID?

Just found https://github.com/msiemens/tinydb/issues/351

The document_id_class is a class variable, it's for all tinydb's Table (looks not ideal at first sight).

Would this approach make sense: When inserting a new Mapping, first make it a Document(mapping, mapping.house-id) (where the doc_id equal to the house-id). However Document needs an int type doc_it. Should one also subclass Document to customize the doc_id's type and change the Table's document_class? When creating a Table sub-class, one also has to create TinyDB sub-class to modify its class variable table_class?

Is there a more elegant approach that I'm overlooking?

aptly-io commented 1 year ago

This might be a recipe for others when a str as doc_id:


class _Document(dict):
    def __init__(self, value: Mapping, doc_id: str):
        super().__init__(value)
        self.doc_id = doc_id

class _Table(Table):
    document_class = _Document
    document_id_class = str
    def _get_next_id(self):
        raise NotImplementedError("doc_id should be self provided")

class _TinyDB(TinyDB):
    table_class = _Table

class Model:

    def __init__(self):
        self._db = _TinyDB("db.json")

There are some issue with table.py though when using _Document ...

msiemens commented 1 month ago

I think your solution with a subclass is the best solution for your use-case (modulo the bug you found with the incorrect isinstance check).