Exemplo n.º 1
0
    def add(self, obj):
        logger.debug("adding object {0}".format(obj.__dict__))
        classpath = utils.get_classpath(obj)
        outcasts = self._check_if_obj_has_not_primitive_fields(obj)
        for outcast in outcasts:
            # we need to add an id for this field, and put it on the corresponding object.
            r = random.randint(0, sys.maxint)
            obj.__dict__[outcast].__dict__['jsondb_id'] = r
            self.add(obj.__dict__[outcast])
            obj.__dict__[outcast] = "<jsondb_id:({0};{1})>".format(utils.get_classpath(obj.__dict__[outcast]).replace(os.path.sep, '.'), r)

        if(classpath.replace(os.path.sep, '.') not in self.tables):
            self.tables.update({classpath.replace(os.path.sep, '.'): []})
        self.tables[classpath.replace(os.path.sep, '.')].append(obj.__dict__)
        logger.debug(self.tables)
        self.save_table(utils.get_table_name(self.dbpath, obj))
Exemplo n.º 2
0
    def get(self, clazz, **kwargs):
        # We need to test if we have the same id in the same table. highly unlikely, but still.
        # Here, we should use the visitor pattern, maybe?
        # Or a filter system ~=chain of responsability?
        # Yeah, filter system, let's go.
        classpath = utils.get_classpath(clazz).replace(os.path.sep, '.')
        if(classpath not in self.tables):
            return []
        data = self.tables[classpath]
        objects = []
        filters = []
        for field, expected in kwargs.items():
            filters.append(JSONdb.Filter(field, expected))

        def is_valid(obj):
            for filter in filters:
                if(not filter.validate(obj)):
                    return False
            return True
        logger.debug("found objects {0}, who must match {1}".format(data, filters))
        for d in data:
            logger.debug("treating object {0}".format(d))
            obj = clazz()
            obj.__dict__.update(d)
            if(is_valid(obj)):
                logger.debug("object {0} is valid!".format(obj.__dict__))
                for field in self._get_relational_fields(obj):
                    # load the object's class, and get it
                    classname = obj.__dict__[field][obj.__dict__[field].find('(')+1:obj.__dict__[field].find(';')]
                    jsondb_id = int(obj.__dict__[field][obj.__dict__[field].find(';')+1:obj.__dict__[field].find(')')])
                    logger.debug("obj to load: {0}:{1}".format(classname, jsondb_id))
                    obj_loaded = self.get(utils.class_import(classname), jsondb_id=jsondb_id)
                    if(obj_loaded == []):
                        logger.error("We could not load field {0} of object {1}! get returned []".format(field, obj.__dict__))
                    obj.__dict__[field] = obj_loaded[0]

                if('jsondb_id' in obj.__dict__):
                    del obj.__dict__['jsondb_id']
                objects.append(obj)
        return objects