Added printing of hex code next to literal to unicode entry output.
[jblite.git] / jblite / db.py
blob4bd5c2319e5a1c13d3f77b7a35784827bab8ac99
1 """Base database object support."""
3 from table import Record
6 class Database(object):
8 entry_class = None
9 table_map = None
11 def __init__(self):
12 self.tables = {}
14 def lookup(self, key, entry_id):
15 """Creates an entry object.
17 Finds a record table based upon the entry table. (This
18 contains all data for an entry.) This is then wrapped in an
19 Entry object which provides logic for displaying or otherwise
20 using the data.
22 """
23 # Lookup data in entry table.
24 data = self.tables[key].lookup_by_id(entry_id) # 1 row only
25 # Lookup child data using the entry_id as a foreign key.
26 children = self._lookup_children(self.table_map[key], data['id'])
27 record = Record(data, children)
28 return self.entry_class(record)
30 def _lookup_children(self, children_map, fk):
31 children = {}
32 for child_table in children_map:
33 grandchild_map = children_map[child_table]
34 rows = self._lookup_by_fk(child_table,
35 children_map[child_table], fk)
36 if len(rows) > 0:
37 children[child_table] = rows
38 return children
40 def _lookup_by_fk(self, table_name, children_map, fk):
41 """Looks up data from a table and related 'child' tables.
43 table_name: name of the table to query.
44 children_map: a dictionary of child table mappings, or None if
45 no children are present.
46 fk: foreign key used in table query.
48 """
49 rows = self.tables[table_name].lookup_by_fk(fk)
50 results = []
51 for row in rows:
52 children = self._lookup_children(children_map, row['id'])
53 record = Record(row, children)
54 results.append(record)
55 return results