'Restore the job\'s reference structure after loading items
from the item table'

def restore_references(self):

    db = current.db
    UID = current.xml.UID
    for item in self.items.values():
        for citem_id in item.load_components:
            if (citem_id in self.items):
                item.components.append(self.items[citem_id])
        item.load_components = []
        for ritem in item.load_references:
            field = ritem['field']
            if ('item_id' in ritem):
                item_id = ritem['item_id']
                if (item_id in self.items):
                    _item = self.items[item_id]
                    entry = Storage(tablename=_item.tablename, element=_item.element, uid=_item.uid, id=_item.id, item_id=item_id)
                    item.references.append(Storage(field=field, entry=entry))
            else:
                _id = None
                uid = ritem.get('uid', None)
                tablename = ritem.get('tablename', None)
                if (tablename and uid):
                    try:
                        table = current.s3db[tablename]
                    except:
                        continue
                    if (UID not in table.fields):
                        continue
                    query = (table[UID] == uid)
                    row = db(query).select(table._id, limitby=(0, 1)).first()
                    if row:
                        _id = row[table._id.name]
                    else:
                        continue
                    entry = Storage(tablename=ritem['tablename'], element=None, uid=ritem['uid'], id=_id, item_id=None)
                    item.references.append(Storage(field=field, entry=entry))
        item.load_references = []
        if (item.load_parent is not None):
            parent = self.items[item.load_parent]
            if (parent is None):
                item.skip = True
            else:
                item.parent = parent
            item.load_parent = None
