Exemplo n.º 1
0
class Table:
    
    def __init__(self, name, shelved=False, queue=False):
        global _config;
        self.name = name
        self.shelved = shelved 
        self.queue = queue
        self.condition = Condition()
        self.keys = {}  # key
        self.indexs = {}  # 对tuple【2】的索引
        self.count = 0       
        self.scheme=None
        if shelved:
            # open db   
            path = '%s/%s_%s.bsd' % (_config['root_dir'], _config['server_key'], name)
            if self.queue:
                bsd = bsddb.rnopen(path, 'c')
            else:                
                bsd = bsddb.btopen(path, 'c')
                
            self.db = shelve.BsdDbShelf(bsd)
            # self.db['中文']='test'
            # print self.db.keys()
            # del self.db['中文']
           
        else:
            if self.queue:
                self.db = OrderedDict()  # memery db
            else:
                self.db = {}  # memery db
            
    def add_tuple(self, tuple):
        key = tuple[0]        
        if self.db.has_key(key):
            return False 
        if self.queue:
            if key == None:
                key = self.count       
        self.db[key] = tuple
        self.count += 1
        return True
    
    def add_indexs(self, value, i=2):
        return            
        if len(value) > i:
            index_field = value[i]
            if index_field == None:
                return  # 空值不建立索引,节约内存空间    
            if(type(index_field) == type([])):  # 是list,则转为tuple
               index_field = tuple(index_field)
               return
            if type(index_field) != type({}) :  # 需要索引value[0]
                if self.indexs.has_key(index_field):
                    self.indexs[index_field].append(value[0])
                else:
                    self.indexs[index_field] = [value[0]]
            else:
                # TODO@byron 对map建立索引
                pass
        pass
    
    def get_tuple(self, k):
        return self.db.get(k, None)
  
    
    def tuples(self, k=None):       
        if self.shelved:
            r = []            
            if type(k) == type([]):           
                for i in k:
                   tup = self.db.get(i, None)
                   if(tup): r.append(tup)
                return r            
        
            try:
                self.condition.acquire()
                tup = self.db.first();
                while(tup):
                    r.append(tup[1])
                    tup = self.db.next()
                self.condition.release()
            except Exception, e:
                self.condition.release()
                pass
            return r
        else: