Example #1
0
 def get_tasks(self, user_id=None):
     """
     Get a list of waiting tasks.
     """
     if(user_id):
         return self.connection.runQuery(sql.build_select('task', user_id=user_id))
     else:
         return self.connection.runQuery(sql.build_select('task'))
Example #2
0
 def get_tasks(self, user_id=None):
     """
     Get a list of waiting tasks.
     """
     if (user_id):
         return self.connection.runQuery(
             sql.build_select('task', user_id=user_id))
     else:
         return self.connection.runQuery(sql.build_select('task'))
Example #3
0
 def load_permissions(self):
     """
     Pre-load the list of existing permissions.
     """
     if not(ObjectExchange.permission_list):
         results = self.connection.runQuery(sql.build_select('permission'))
         ObjectExchange.permission_list = dict([(x['name'], x['id']) for x in results])
Example #4
0
 def is_allowed(self, accessor, permission, subject):
     """
     Is `accessor` allowed to do `permission` on `subject`?.
     """
     if(permission not in self.permission_list):
         import warnings
         warnings.warn("Unknown permission encountered: %s" % permission)
         return False
     
     permission_id = self.permission_list[permission]
     anything_id = self.permission_list['anything']
     
     access_query = sql.build_select('access', dict(
         object_id        = subject.get_id() if isinstance(subject, interface.Object) else None,
         verb_id            = subject.get_id() if isinstance(subject, interface.Verb) else None,
         property_id        = subject.get_id() if isinstance(subject, interface.Property) else None,
         permission_id    = (permission_id, anything_id),
         __order_by        = 'weight DESC',
     ))
     
     access = self.connection.runQuery(access_query)
     
     result = False
     for rule in access:
         rule_type = (rule['rule'] == 'allow')
         if(rule['type'] == 'group'):
             if(rule['group'] not in group_definitions):
                 raise ValueError("Unknown group: %s" % rule['accessor'])
             if(group_definitions[rule['group']](self, accessor, subject)):
                 result = rule_type
         elif(rule['type'] == 'accessor'):
             if(rule['accessor_id'] == accessor.get_id()):
                 result = rule_type
     return result
Example #5
0
 def get_last_client_ip(self, avatar_id):
     """
     Get the last IP used to login as this player.
     """
     result = self.connection.runQuery(
         sql.build_select('session', user_id=avatar_id))
     return result[0]['last_client_ip'] if result else None
Example #6
0
 def load_permissions(self):
     """
     Pre-load the list of existing permissions.
     """
     if not (ObjectExchange.permission_list):
         results = self.connection.runQuery(sql.build_select('permission'))
         ObjectExchange.permission_list = dict([(x['name'], x['id'])
                                                for x in results])
Example #7
0
 def test_build_select_dot_syntax(self):
     query = sql.build_select('db.table', {
         't.col2': 'col2_data',
         's.col1': 'col1_data'
     })
     expecting = "SELECT * FROM db.table WHERE s.col1 = 'col1_data' AND t.col2 = 'col2_data'"
     self.assertEqual(query, expecting,
                      'Got "%s" when expecting "%s"' % (query, expecting))
Example #8
0
 def test_build_select(self):
     query = sql.build_select('table', {
         'col2': 'col2_data',
         'col1': 'col1_data'
     })
     expecting = "SELECT * FROM table WHERE col1 = 'col1_data' AND col2 = 'col2_data'"
     self.assertEqual(query, expecting,
                      'Got "%s" when expecting "%s"' % (query, expecting))
Example #9
0
 def test_build_select_in_limit(self):
     query = sql.build_select('table', {
         'col1': ['col1_data', 'col2_data'],
         '__limit': 5
     })
     expecting = "SELECT * FROM table WHERE col1 IN ('col1_data', 'col2_data') LIMIT 5"
     self.assertEqual(query, expecting,
                      'Got "%s" when expecting "%s"' % (query, expecting))
Example #10
0
 def test_build_select_raw(self):
     query = sql.build_select('table', {
         'col1':
         sql.RAW("%s = ENCRYPT('something', SUBSTRING(col1,1,2))")
     })
     expecting = "SELECT * FROM table WHERE col1 = ENCRYPT('something', SUBSTRING(col1,1,2))"
     self.assertEqual(query, expecting,
                      'Got "%s" when expecting "%s"' % (query, expecting))
Example #11
0
 def test_build_select_order(self):
     query = sql.build_select('table', {
         'col1': 'col1_data',
         'col2': 'col2_data',
         '__order_by': 'id DESC'
     })
     expecting = "SELECT * FROM table WHERE col1 = 'col1_data' AND col2 = 'col2_data' ORDER BY id DESC"
     self.assertEqual(query, expecting,
                      'Got "%s" when expecting "%s"' % (query, expecting))
Example #12
0
 def is_unique_name(self, key):
     """
     Has the given key been designated as a unique name?
     """
     result = self.connection.runQuery(sql.build_select('object', dict(
         name        = sql.RAW(sql.interp('LOWER(%%s) = LOWER(%s)', key)),
         unique_name = True
     )))
     return bool(result)
Example #13
0
 def is_unique_name(self, key):
     """
     Has the given key been designated as a unique name?
     """
     result = self.connection.runQuery(
         sql.build_select(
             'object',
             dict(name=sql.RAW(sql.interp('LOWER(%%s) = LOWER(%s)', key)),
                  unique_name=True)))
     return bool(result)
Example #14
0
    def get_object(self, key, return_list=False):
        """
        Return the object specified by the provided key.
        
        If return_list is True, ambiguous object keys will return a list
        of matching objects.
        """
        if (isinstance(key, str)):
            key = key.strip()
        try:
            key = int(key)
        except:
            pass

        if (key in ('', 'none', 'None', 'null', 'NULL', None)):
            return None

        items = None
        if (isinstance(key, str)):
            if (key.startswith('#')):
                end = key.find("(")
                if (end == -1):
                    end = key.find(" ")
                if (end == -1):
                    end = len(key)
                key = int(key[1:end])
            else:
                items = self.connection.runQuery(
                    sql.build_select('object',
                                     name=sql.RAW(
                                         sql.interp('LOWER(%%s) = LOWER(%s)',
                                                    key))))
                if (len(items) == 0):
                    if (return_list):
                        return []
                    else:
                        raise errors.NoSuchObjectError(key)
                elif (len(items) > 1):
                    if (return_list):
                        return self.instantiate('object', *items)
                    else:
                        raise errors.AmbiguousObjectError(key, items)
                else:
                    return self.instantiate('object', items[0])

        if (isinstance(key, int)):
            if (key == -1):
                return None

            return self.load('object', key)
        else:
            raise ValueError("Invalid key type: %r" % repr(key))
Example #15
0
 def get_object(self, key, return_list=False):
     """
     Return the object specified by the provided key.
     
     If return_list is True, ambiguous object keys will return a list
     of matching objects.
     """
     if(isinstance(key, str)):
         key = key.strip()
     try:
         key = int(key)
     except:
         pass
     
     if(key in ('', 'none', 'None', 'null', 'NULL', None)):
         return None
     
     items = None
     if(isinstance(key, str)):
         if(key.startswith('#')):
             end = key.find("(")
             if(end == -1):
                 end = key.find( " ")
             if(end == -1):
                 end = len(key)
             key = int(key[1:end])
         else:
             items = self.connection.runQuery(sql.build_select('object', name=sql.RAW(sql.interp('LOWER(%%s) = LOWER(%s)', key))))
             if(len(items) == 0):
                 if(return_list):
                     return []
                 else:
                     raise errors.NoSuchObjectError(key)
             elif(len(items) > 1):
                 if(return_list):
                     return self.instantiate('object', *items)
                 else:
                     raise errors.AmbiguousObjectError(key, items)
             else:
                 return self.instantiate('object', items[0])
     
     if(isinstance(key, int)):
         if(key == -1):
             return None
         
         return self.load('object', key)
     else:
         raise ValueError("Invalid key type: %r" % repr(key))
Example #16
0
 def load(self, obj_type, obj_id):
     """
     Load a specific object from the database.
     """
     obj_key = '%s-%s' % (obj_type, obj_id)
     if(obj_key in self.cache):
         return self.cache[obj_key]
     
     items = self.connection.runQuery(sql.build_select(obj_type, id=obj_id))
     if not(items):
         raise errors.NoSuchObjectError("%s #%s" % (obj_type, obj_id))
     
     def fail(record):
         raise RuntimeError("Don't know how to make an object of type '%s'" % obj_type)
     
     maker = getattr(self, '_mk%s' % obj_type, fail)
     obj = maker(items[0])
     if not(obj.get_id()):
         obj.set_id(obj_id)
     self.cache[obj_key] = obj
     
     return obj
Example #17
0
    def is_allowed(self, accessor, permission, subject):
        """
        Is `accessor` allowed to do `permission` on `subject`?.
        """
        if (permission not in self.permission_list):
            import warnings
            warnings.warn("Unknown permission encountered: %s" % permission)
            return False

        permission_id = self.permission_list[permission]
        anything_id = self.permission_list['anything']

        access_query = sql.build_select(
            'access',
            dict(
                object_id=subject.get_id() if isinstance(
                    subject, interface.Object) else None,
                verb_id=subject.get_id()
                if isinstance(subject, interface.Verb) else None,
                property_id=subject.get_id() if isinstance(
                    subject, interface.Property) else None,
                permission_id=(permission_id, anything_id),
                __order_by='weight DESC',
            ))

        access = self.connection.runQuery(access_query)

        result = False
        for rule in access:
            rule_type = (rule['rule'] == 'allow')
            if (rule['type'] == 'group'):
                if (rule['group'] not in group_definitions):
                    raise ValueError("Unknown group: %s" % rule['accessor'])
                if (group_definitions[rule['group']](self, accessor, subject)):
                    result = rule_type
            elif (rule['type'] == 'accessor'):
                if (rule['accessor_id'] == accessor.get_id()):
                    result = rule_type
        return result
Example #18
0
    def load(self, obj_type, obj_id):
        """
        Load a specific object from the database.
        """
        obj_key = '%s-%s' % (obj_type, obj_id)
        if (obj_key in self.cache):
            return self.cache[obj_key]

        items = self.connection.runQuery(sql.build_select(obj_type, id=obj_id))
        if not (items):
            raise errors.NoSuchObjectError("%s #%s" % (obj_type, obj_id))

        def fail(record):
            raise RuntimeError(
                "Don't know how to make an object of type '%s'" % obj_type)

        maker = getattr(self, '_mk%s' % obj_type, fail)
        obj = maker(items[0])
        if not (obj.get_id()):
            obj.set_id(obj_id)
        self.cache[obj_key] = obj

        return obj
Example #19
0
 def test_build_select_none(self):
     query = sql.build_select('table', {'col1': None})
     expecting = "SELECT * FROM table WHERE col1 IS NULL"
     self.assertEqual(query, expecting,
                      'Got "%s" when expecting "%s"' % (query, expecting))
Example #20
0
 def test_build_select2(self):
     query = sql.build_select('table', col2='col2_data', col1='col1_data');
     expecting = "SELECT * FROM table WHERE col1 = 'col1_data' AND col2 = 'col2_data'"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #21
0
 def test_build_select_not_in(self):
     query = sql.build_select('table',
                              {'col1': sql.NOT(['col1_data', 'col2_data'])})
     expecting = "SELECT * FROM table WHERE col1 NOT IN ('col1_data', 'col2_data')"
     self.assertEqual(query, expecting,
                      'Got "%s" when expecting "%s"' % (query, expecting))
Example #22
0
 def test_build_select_none(self):
     query = sql.build_select('table', {'col1':None});
     expecting = "SELECT * FROM table WHERE col1 IS NULL"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #23
0
 def test_build_select_lt(self):
     query = sql.build_select('table', {'col1':sql.LT("somestring")});
     expecting = "SELECT * FROM table WHERE col1 < 'somestring'"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #24
0
 def test_build_select_raw(self):
     query = sql.build_select('table', {'col1':sql.RAW("%s = ENCRYPT('something', SUBSTRING(col1,1,2))")});
     expecting = "SELECT * FROM table WHERE col1 = ENCRYPT('something', SUBSTRING(col1,1,2))"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #25
0
 def get_avatar_id(self, player_id):
     result = self.connection.runQuery(sql.build_select('player', dict(id=player_id)))
     return result[0]['avatar_id']
Example #26
0
 def get_last_client_ip(self, avatar_id):
     """
     Get the last IP used to login as this player.
     """
     result = self.connection.runQuery(sql.build_select('session', user_id=avatar_id))
     return result[0]['last_client_ip'] if result else None
Example #27
0
 def test_build_select_order(self):
     query = sql.build_select('table', {'col1':'col1_data', 'col2':'col2_data', '__order_by':'id DESC'});
     expecting = "SELECT * FROM table WHERE col1 = 'col1_data' AND col2 = 'col2_data' ORDER BY id DESC"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #28
0
 def test_build_select_dot_syntax(self):
     query = sql.build_select('db.table', {'t.col2':'col2_data', 's.col1':'col1_data'});
     expecting = "SELECT * FROM db.table WHERE s.col1 = 'col1_data' AND t.col2 = 'col2_data'"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #29
0
 def test_build_select_distinct(self):
     query = sql.build_select('table', {'col1':'col1_data', 'col2':'col2_data', '__select_keyword':'DISTINCT'});
     expecting = "SELECT DISTINCT * FROM table WHERE col1 = 'col1_data' AND col2 = 'col2_data'"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #30
0
 def get_avatar_id(self, player_id):
     result = self.connection.runQuery(
         sql.build_select('player', dict(id=player_id)))
     return result[0]['avatar_id']
Example #31
0
 def test_build_select_lt(self):
     query = sql.build_select('table', {'col1': sql.LT("somestring")})
     expecting = "SELECT * FROM table WHERE col1 < 'somestring'"
     self.assertEqual(query, expecting,
                      'Got "%s" when expecting "%s"' % (query, expecting))
Example #32
0
 def get_task(self, task_id):
     """
     Fetch the record for the provided task id.
     """
     result = self.connection.runQuery(sql.build_select('task', id=task_id))
     return result[0] if result else None
Example #33
0
 def test_build_select_not_in(self):
     query = sql.build_select('table', {'col1':sql.NOT(['col1_data', 'col2_data'])});
     expecting = "SELECT * FROM table WHERE col1 NOT IN ('col1_data', 'col2_data')"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #34
0
 def test_build_select_in_limit(self):
     query = sql.build_select('table', {'col1':['col1_data', 'col2_data'], '__limit':5});
     expecting = "SELECT * FROM table WHERE col1 IN ('col1_data', 'col2_data') LIMIT 5"
     self.failUnlessEqual(query, expecting, 'Got "%s" when expecting "%s"' % (sql, expecting))
Example #35
0
 def get_task(self, task_id):
     """
     Fetch the record for the provided task id.
     """
     result = self.connection.runQuery(sql.build_select('task', id=task_id))
     return result[0] if result else None