msiemens/tinydb

Checking that user inserts a set

vient opened this issue · 4 comments

vient commented

When you try to insert a string, operation completes successfully. After that, ValueError: dictionary update sequence element #0 has length 1; 2 is required is thrown at any operation.
It's not a real bug since it is explicitly said in the docs that TinyDB expects inserted element to be a set, but anyway it's not good that such destructive operation is allowed. Maybe an exception on inserting anything except set will be more appropriate?

Hey @vient, somehow I cannot reproduce this behaviour (neither on Python 2 nor on Python 3). Could you post the full example code and stack trace?

vient commented

Here it is. I'm using Python 3.5.1.

>>> from tinydb import TinyDB
>>> table = TinyDB(r'D:\db')
>>> table.insert('qwerty')
1
>>> table.insert({'type': 'sample'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python 3.5\lib\site-packages\tinydb\database.py", line 287, in insert
    data = self._read()
  File "C:\Program Files\Python 3.5\lib\site-packages\tinydb\database.py", line 248, in _read
    return self._storage.read()
  File "C:\Program Files\Python 3.5\lib\site-packages\tinydb\database.py", line 38, in read
    data[eid] = Element(val, eid)
  File "C:\Program Files\Python 3.5\lib\site-packages\tinydb\database.py", line 20, in __init__
    self.update(value)
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>>

Okay, now I've got it. I used an empty string which seems to insert an empty dictionary without failing. Now regarding the solution I think the best way to go is to check for every element we insert if it's a dictionary and raise an exception otherwise. In theory this would be a breaking change, as an exception is introduced, but it would have created broken databases anyways. Also this will likely introduce a small performance penalty if the checking occurs every insert. I'm still thinking if we can do something about the performance.

I've now added 9eaf562 which solves this issue by raising a ValueError. It will be included in the next release of TinyDB :)