Hexatonic
Hexatonic

Reputation: 2407

Is it possible to ask for keys from TinyDB

How can find out what a tinydb database contains, sort of like asking for the colums of a table in SQL with DESCRIBE name_of_table; or calling keys() on a dictionary.

In general, I'm looking for tips on how to examine a Tiny Db database when you're not quite sure what it contains.

Upvotes: 0

Views: 3109

Answers (1)

Anton Zuenko
Anton Zuenko

Reputation: 761

Tinydb fits entirely in memory so it's ok to call .all(), get data and make some stats. Here is the code that dumps db structure per table per document type, defined by the set of keys:

from tinydb import TinyDB
from collections import Counter

db = TinyDB('db.json')

for table in db.tables():
    contents = db.table(table).all()

    schema = Counter(frozenset(doc.keys()) for doc in contents)

    print('table %s (documents %d):' % (table, sum(schema.values())))
    for fields, count in schema.iteritems():
        print('  document (count %d):' % count)
        print('\n'.join('    %s' % field for field in fields))

Sample output:

table _default (documents 36):
  document (count 15):
    foo
    bar
  document (count 21):
    int
    char

Upvotes: 3

Related Questions