adewes / blitzdb

Blitz is a document-oriented database for Python that is backend-agnostic. It comes with a flat-file database for JSON documents and provides MongoDB-like querying capabilities.
http://blitzdb.readthedocs.org
MIT License
331 stars 37 forks source link

OrderedDict turns to normal dict when document is loaded from database #76

Open M4rtinK opened 7 years ago

M4rtinK commented 7 years ago

Looks like Document instance attributes that hold ordered dicts turn to normal dicts when the document is reatrieved from the database, short reproducer:

#!/usr/bin/python3

from collections import OrderedDict
import tempfile
import blitzdb

with tempfile.TemporaryDirectory() as temp_dir_name:
    db = blitzdb.FileBackend(temp_dir_name)
    original_document = blitzdb.Document()
    original_document.od = OrderedDict()
    original_document.od["foo"] = 1
    original_document.od["bar"] = 2
    original_document.od["baz"] = 3

    print("original document")
    print(original_document.od)
    print(isinstance(original_document.od, OrderedDict))

    original_document.save(db)
    db.commit()

    loaded_document = db.get(blitzdb.Document, {})

    print("loaded document")
    print(loaded_document.od)
    print(isinstance(loaded_document.od, OrderedDict))
adewes commented 7 years ago

Unfortunately this is not supported by BlitzDB, so if you want to retain the order of your keys you should store the items in the document instead and convert it back to an ordered dict after retrieving the object from the database (you could write a custom Document type that could do that for you automatically).