Welcome to TinyDB, your tiny, document oriented database optimized for your happiness :)
>>> from tinydb import TinyDB, where
>>> db = TinyDB('path/to/db.json')
>>> db.insert({'int': 1, 'char': 'a'})
>>> db.search(where('int') == 1)
[{'int': 1, 'char': 'a'}]
Great that you’ve taken time to check out the TinyDB docs! Before we begin looking at TinyDB itself, let’s take some time to see whether you should use TinyDB.
In short: If you need a simple database with a clean API that just works without lots of configuration, TinyDB might be the right choice for you.
To put it plainly: If you need advanced features or high performance, TinyDB is the wrong database for you – consider using databases like Buzhug, CodernityDB or MongoDB.
To install TinyDB from PyPI, run:
$ pip install tinydb
You can also grab the latest development version from GitHub. After downloading and unpacking it, you can install it using:
$ python setup.py install
Let’s cover the basics before going more into detail. We’ll start by setting up a TinyDB database:
>>> from tinydb import TinyDB, where
>>> db = TinyDB('db.json')
You now have a TinyDB database that stores its data in db.json. What about inserting some data? TinyDB expects the data to be Python dicts:
>>> db.insert({'type': 'apple', 'count': 7})
1
>>> db.insert({'type': 'peach', 'count': 3})
2
Note
The insert method returns the inserted element’s ID. Read more about it here: Using Element IDs.
Now you can get all elements stored in the database by running:
>>> db.all()
[{'count': 7, 'type': 'apple'}, {'count': 3, 'type': 'peach'}]
Of course you’ll also want to search for specific elements. Let’s try:
>>> db.search(where('type') == 'peach')
[{'count': 3, 'type': 'peach'}]
>>> db.search(where('count') > 5)
[{'count': 7, 'type': 'apple'}]
Next we’ll update the count field of the apples:
>>> db.update({'count': 10}, where('type') == 'apple')
>>> db.all()
[{'count': 10, 'type': 'apple'}, {'count': 3, 'type': 'peach'}]
In the same manner you can also remove elements:
>>> db.remove(where('count') < 5)
>>> db.all()
[{'count': 10, 'type': 'apple'}]
And of course you can throw away all data to start with an empty database:
>>> db.purge()
>>> db.all()
[]
Before we dive deeper, let’s recapitulate the basics:
Inserting | |
db.insert(...) | Insert an element |
Getting data | |
db.all() | Get all elements |
db.search(query) | Get a list of elements matching the query |
Updating | |
db.update(fields, query) | Update all elements matching the query to contain fields |
Removing | |
db.remove(query) | Remove all elements matching the query |
db.purge() | Purge all elements |
Querying | |
where('field') == 2 | Match any element that has a key field with value == 2 (also possible: != > >= < <=) |
Before we dive deeper into the usage of TinyDB, we should stop for a moment and discuss the topic of serializtion.
TinyDB serializes all data using the Python JSON module by default. It’s great for serializing simple data types but cannot handle more complex data types like custom classes. On Python 2 it also converts strings to unicode strings upon reading (described here).
If you need a better serializer, you can write your own storage, that uses a more powerful (but also slower) library like pickle or PyYAML.
So let’s start with inserting and retrieving data from your database.
As already described you can insert an element using db.insert(...). In case you want to insert multiple elements, you can use db.insert_multiple(...):
>>> db.insert_multiple([{'int': 1, 'char': 'a'}, {'int': 1, 'char': 'b'}])
>>> db.insert_multiple({'int': 1, 'value': i} for i in range(2))
There are several ways to retrieve data from your database. For instance you can get the number of stored elements:
>>> len(db)
3
Then of course you can use db.search(...) as described in the Getting Started section. But sometimes you want to get only one matching element. Instead of using
>>> try:
... result = db.search(where('value') == 1)[0]
... except IndexError:
... pass
you can use db.get(...):
>>> db.get(where('value') == 1)
{'int': 1, 'value': 1}
>>> db.get(where('value') == 100)
None
Caution
If multiple elements match the query, propably a random one of them will be returned!
Often you don’t want to search for elements but only know whether they are stored in the database. In this case db.contains(...) is your friend:
>>> db.contains(where('char') == 'a')
In a similar manner you can look up the number of elements matching a query:
>>> db.count(where('int') == 1)
3
Let’s summarize the ways to handle data:
Inserting | |
db.insert_multiple(...) | Insert multiple elements |
Getting data | |
len(db) | Get the number of elements in the database |
db.get(query) | Get one element matching the query |
db.contains(query) | Check if the database contains a matching element |
db.count(query) | Get the number of matching elements |
Internally TinyDB associates an ID with every element you insert. It’s returned after inserting an element:
>>> db.insert({'value': 1})
3
>>> db.insert_multiple([{...}, {...}, {...}])
[4, 5, 6]
In addition you can get the ID of already inserted elements using element.eid:
>>> el = db.get(where('value') == 1)
>>> el.eid
3
Different TinyDB methods also work with IDs, namely: update, remove, contains and get.
>>> db.update({'value': 2}, eids=[1, 2])
>>> db.contains(eids=[1])
True
>>> db.remove(eids=[1, 2])
>>> db.get(eid=3)
{...}
Let’s sum up the way TinyDB supports working with IDs:
Getting an element’s ID | |
db.insert(...) | Returns the inserted element’s ID |
db.insert_multiple(...) | Returns the inserted elements’ ID |
element.eid | Get the ID of an element fetched from the db |
Working with IDs | |
db.get(eid=...) | Get the elemtent with the given ID |
db.contains(eids=[...]) | Check if the db contains elements with one of the given IDs |
db.update({...}, eids=[...]) | Update all elements with the given IDs |
db.remove(eids=[...]) | Remove all elements with the given IDs |
TinyDB lets you use a rich set of queries. In the Getting Started you’ve learned about the basic comparisons (==, <, >, ...). In addition to that TinyDB enables you run logical operations on queries.
>>> # Negate a query:
>>> db.search(~ where('int') == 1)
>>> # Logical AND:
>>> db.search((where('int') == 1) & (where('char') == 'b'))
[{'int': 1, 'char': 'b'}]
>>> # Logical OR:
>>> db.search((where('char') == 'a') | (where('char') == 'b'))
[{'int': 1, 'char': 'a'}, {'int': 1, 'char': 'b'}]
Note
When using & or |, make sure you wrap the conditions on both sides with parentheses or Python will mess up the comparison.
You also can search for elements where a specific key exists:
>>> db.search(where('char'))
[{'int': 1, 'char': 'a'}, {'int': 1, 'char': 'b'}]
In addition to these checks TinyDB supports checking against a regex or a custom test function:
>>> # Regex:
>>> db.search(where('char').matches('[aZ]*'))
[{'int': 1, 'char': 'a'}, {'int': 1, 'char': 'b'}]
>>> # Custom test:
>>> test_func = lambda c: c == 'a'
>>> db.search(where('char').test(test_func))
[{'char': 'a', 'int': 1}]
You can insert nested elements into your database:
>>> db.insert({'field': {'name': {'first_name': 'John', 'last_name': 'Doe'}}})
To search for a nested field, use where('field').has(...). You can apply any queries you already know to this selector:
>>> db.search(where('field').has('name'))
[{'field': ...}]
>>> db.search(where('field').has('name').has('last_name') == 'Doe')
[{'field': ...}]
You also can use lists inside of elements:
>>> db.insert({'field': [{'val': 1}, {'val': 2}, {'val': 3}])
Using where('field').any(...) and where('field').all(...) you can specify checks for the list’s items. They behave similarly to Python’s any and all:
>>> db.search(where('field').any(where('val') == 1))
True
>>> db.search(where('field').all(where('val') > 0))
True
Again, let’s recapitulate the query operations:
Queries | |
where('field').matches(regex) | Match any element matching the regular expression |
where('field').test(func) | Matches any element for which the function returns True |
Combining Queries | |
~ query | Match elements that don’t match the query |
(query1) & (query2) | Match elements that match both queries |
(query1) | (query2) | Match elements that match one of the queries |
Nested Queries | |
where('field').has('field') | Match any element that has the specified item. Perform more queries on this selector as needed |
where('field').any(query) | Match any element where ‘field’ is a list where one of the items matches the subquery |
where('field').all(query) | Match any element where ‘field’ is a list where all items match the subquery |
TinyDB supports working with multiple tables. They behave just the same as the TinyDB class. To create and use a table, use db.table(name).
>>> table = db.table('table_name')
>>> table.insert({'value': True})
>>> table.all()
[{'value': True}]
To remove all tables from a database, use:
>>> db.purge_tables()
Note
TinyDB uses a table named _default as default table. All operations on the database object (like db.insert(...)) operate on this table.
You can get a list with the names of all tables in your database:
>>> db.tables()
{'_default', 'table_name'}
TinyDB caches query result for performance. You can optimize the query cache size by passing the cache_size to the table(...) function:
>>> table = db.table('table_name', cache_size=30)
Hint
You can set cache_size to None to make the cache unlimited in size.
If you perform lots of queries while the data changes only little, you may enable a smarter query cache. It updates the query cache when inserting/removing/updating elements so the cache doesn’t get invalidated.
>>> table = db.table('table_name', smart_cache=True)
TinyDB comes with two storage types: JSON and in-memory. By default TinyDB stores its data in JSON files so you have to specify the path where to store it:
>>> from tinydb import TinyDB, where
>>> db = TinyDB('path/to/db.json')
To use the in-memory storage, use:
>>> from tinydb.storages import MemoryStorage
>>> db = TinyDB(storage=MemoryStorage)
Middlewares wrap around existing storages allowing you to customize their behaviour.
>>> from tinydb.storages import JSONStorage
>>> from tinydb.middlewares import CachingMiddleware
>>> db = TinyDB('/path/to/db.json', storage=CachingMiddleware(JSONStorage))
Hint
You can nest middlewares:
>>> db = TinyDB('/path/to/db.json', storage=FirstMiddleware(SecondMiddleware(JSONStorage)))
The CachingMiddleware improves speed by reducing disk I/O. It caches all read operations and writes data to disk after a configured number of write operations.
To make sure that all data is safely written when closing the table, use one of these ways:
# Using a context manager:
with database as db:
# Your operations
# Using the close function
db.close()
Whether reporting bugs, discussing improvements and new ideas or writing extensions: Contributions to TinyDB are welcome! Here’s how to get started:
TinyDB aims to be simple and fun to use. Therefore two key values in development are simplicity and elegance. Sometimes these values contradict each other. In this case, try using as little magic as possible. In any case don’t forget commenting code that isn’t clear at first glance.
In general the TinyDB source should always follow PEP 8. Exceptions are allowed in well justified and documented cases. However we make a small exception concerning docstrings:
When using multiline docstrings, keep the opening and closing triple quotes on their own lines and add an empty line after it.
def some_function():
"""
Documentation ...
"""
# implementation ...
TinyDB follows the SemVer versioning guidelines. This implies that backwards incompatible changes in the API will increment the major version. So think twice before making such changes.
You can write a custom storage by subclassing Storage:
class CustomStorage(Storage):
def __init__(self, arg1):
pass
def read(self):
# your implementation
def write(self, data):
# your implementation
def close(self):
# optional: close open file handles, etc.
To indicate that your storage is empty, raise an ValueError in read(self). TinyDB will create the data for a new database and ask your storage to write it.
When creating a new instance of TinyDB, the instance will pass all arguments and keyword arguments (except storage) to your storage class:
db = TinyDB(arg1, storage=CustomStorage)
You can modify the behaviour of existing storages by writing a custom middleware. To do so, subclass Middleware:
class CustomMiddleware(CustomMiddleware):
def __init__(self, storage_cls):
# Any middleware *has* to call the super constructor
# with storage_cls
super(CustomMiddleware, self).__init__(storage_cls)
def read(self):
# your implementation
self.storage.read() # access the storage's read function
def write(self, data):
# your implementation
self.storage.write(data) # access the storage's close function
def close(self):
# optional: close open file handles, etc.
self.storage.close() # access the storage's close function
Remember to call the super constructor in your __init__ as shown in the example.
To wrap a storage with your new middleware, use
db = TinyDB(storage=CustomMiddleware(SomeStorageClass))
The main class of TinyDB.
Gives access to the database, provides methods to insert/search/remove and getting tables.
See Table.__exit__()
Forward all unknown attribute calls to the underlying standard table.
Create a new instance of TinyDB.
All arguments and keyword arguments will be passed to the underlying storage class (default: JSONStorage).
Parameters: | storage – The class of the storage to use. Will be initialized with args and kwargs. |
---|
Get the total number of elements in the DB.
>>> len(db)
0
Purge all tables from the database. CANNOT BE REVERSED!
Get access to a specific table.
Creates a new table, if it hasn’t been created before, otherwise it returns the cached Table object.
Parameters: |
|
---|
Get the names of all tables in the database.
Returns: | a set of table names |
---|---|
Return type: | set[str] |
Represents a single TinyDB Table.
Allow the database to be used as a context manager.
Returns: | the table instance |
---|
Try to close the storage after being used as a context manager.
Get access to a table.
Parameters: |
|
---|
Get the total number of elements in the table.
Get all elements stored in the table.
Returns: | a list with all elements. |
---|---|
Return type: | list[Element] |
Try to close the storage after being used as a context manager.
Check wether the database contains an element matching a condition or an ID.
If eids is set, it checks if the db contains an element with one of the specified.
Parameters: |
|
---|
Count the elements matching a condition.
Parameters: | cond (Query) – the condition use |
---|
Get exactly one element specified by a query or and ID.
Returns None if the element doesn’t exist
Parameters: |
|
---|---|
Returns: | the element or None |
Return type: | Element | None |
Insert a new element into the table.
Parameters: | element – the element to insert |
---|---|
Returns: | the inserted element’s ID |
Insert multiple elements into the table.
Parameters: | elements – a list of elements to insert |
---|---|
Returns: | a list containing the inserted elements’ IDs |
Helper function for processing all elements specified by condition or IDs.
A repeating pattern in TinyDB is to run some code on all elements that match a condition or are specified by their ID. This is implemented in this function. The function passed as func has to be a callable. It’s first argument will be the data currently in the database. It’s second argument is the element ID of the currently processed element.
Parameters: |
|
---|
Purge the table by removing all elements.
Remove all matching elements.
Parameters: |
|
---|
Search for all elements matching a ‘where’ cond.
Parameters: | cond (Query) – the condition to check against |
---|---|
Returns: | list of matching elements |
Return type: | list[Element] |
Update all matching elements to have a given set of fields.
Parameters: |
|
---|
Provides methods to do tests on dict fields.
Any type of comparison will be called in this class. In addition, it is aliased to where to provide a more intuitive syntax.
When not using any comparison operation, this simply tests for existence of the given key.
Combines this query and another with logical and.
Example:
>>> (where('f1') == 5) & (where('f2') != 2)
('f1' == 5) and ('f2' != 2)
Return type: | QueryAnd |
---|
Run the test on the element.
Parameters: | element (dict) – The dict that we will run our tests against. |
---|
Test a dict value for equality.
>>> where('f1') == 42
'f1' == 42
Test a dict value for being greater than or equal to another value.
>>> where('f1') >= 42
'f1' >= 42
Test a dict value for being greater than another value.
>>> where('f1') > 42
'f1' > 42
Negates a query.
>>> ~(where('f1') >= 42)
not ('f1' >= 42)
Return type: | tinydb.queries.QueryNot |
---|
Test a dict value for being lower than or equal to another value.
>>> where('f1') <= 42
'f1' <= 42
Test a dict value for being lower than another value.
>>> where('f1') < 42
'f1' < 42
Test a dict value for inequality.
>>> where('f1') != 42
'f1' != 42
Combines this query and another with logical or.
Example:
>>> (where('f1') == 5) | (where('f2') != 2)
('f1' == 5) or ('f2' != 2)
Return type: | QueryOr |
---|
Checks if a condition is met by any element in a list.
>>> where('f1').all(where('f2') == 1)
'f1' all have 'f2' == 1
Matches:
{'f1': [{'f2': 1}, {'f2': 1}]}
Parameters: | cond – The condition to check |
---|---|
Return type: | tinydb.queries.Query |
Checks if a condition is met by any element in a list.
>>> where('f1').any(where('f2') == 1)
'f1' has any 'f2' == 1
Matches:
{'f1': [{'f2': 1}, {'f2': 0}]}
Parameters: | cond – The condition to check |
---|---|
Return type: | tinydb.queries.Query |
Run test on a nested dict.
>>> where('x').has('y') == 2
has 'x' => ('y' == 2)
Matches:
{'x': {'y': 2}}
Parameters: | key – the key to search for in the nested dict |
---|---|
Return type: | QueryHas |
Run a regex test against a dict value.
>>> where('f1').matches('^\w+$')
'f1' ~= ^\w+$
Parameters: | regex – The regular expression to pass to re.match |
---|---|
Return type: | QueryRegex |
Run a user-defined test function against a dict value.
>>> def test_func(val):
... return val == 42
...
>>> where('f1').test(test_func)
'f1'.test(<function test_func at 0xXXXXXXXX>)
Parameters: | func – The function to run. Has to accept one parameter and return a boolean. |
---|---|
Return type: | QueryCustom |
Contains the base class for storages and implementations.
The abstract base class for all Storages.
A Storage (de)serializes the current state of the database and stores it in some place (memory, file on disk, ...).
Read the last stored state.
Write the current state of the database to the storage.
Optional: Close open file handles, etc.
Contains the base class for middlewares and implementations.
The base class for all Middlewares.
Middlewares hook into the read/write process of TinyDB allowing you to extend the behaviour by adding caching, logging, ...
If read() or write() are not overloaded, they will be forwarded directly to the storage instance.
Read the last stored state.
Write the current state of the database to the storage.
Optional: Close open file handles, etc.
TinyDB follows the SemVer versioning guidelines. For more information, see semver.org
Warning
TinyDB changed the way data is stored. You may need to migrate your databases to the new scheme. Check out the Upgrade Notes for details.
Apart from that the API remains compatible to v1.4 and prior.
To improve the handling of IDs TinyDB changed the way it stores data (see Issue #13 for details). Opening an database from v1.4 or prior will most likely result in an exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tinydb\database.py", line 49, in __init__
self._table = self.table('_default')
File "tinydb\database.py", line 69, in table
table = table_class(name, self, **options)
File "tinydb\database.py", line 171, in __init__
self._last_id = int(sorted(self._read().keys())[-1])
File "tinydb\database.py", line 212, in _read
data[eid] = Element(data[eid], eid)
TypeError: list indices must be integers, not dict
In this case you need to migrate the database to the recent scheme. TinyDB provides a migration script for the default JSON storage:
$ python -m tinydb.migrate db1.json db2.json
Processing db1.json ... Done
Processing db2.json ... Done
If you have database files that have been written using a custom storage class, you can write your own migration script that calls tinydb.migrate.migrate:
Migrate a database to the scheme used in v2.0.
To migrate a db that uses a custom storage, use
>>> from tinydb.migrate import migrate
>>> args = [...] # args for your storage class
>>> kwargs = {...} # kwargs for your storage class
>>> migrate(*args, **kwargs, storage=YourStorageClass)
True
Parameters: | storage – The class of the storage to use. Will be initialized with args and kwargs. Default: JSONStorage |
---|---|
Returns: | True if the db has been migrated, False if the db didn’t need a migration. |