# Mark Huang <mlhuang@cs.princeton.edu>
# Copyright (C) 2006 The Trustees of Princeton University
#
-# $Id: Roles.py,v 1.2 2006/10/06 18:19:41 mlhuang Exp $
+# $Id: Roles.py,v 1.7 2006/11/08 23:02:01 mlhuang Exp $
#
from types import StringTypes
from PLC.Faults import *
from PLC.Parameter import Parameter
+from PLC.Filter import Filter
from PLC.Table import Row, Table
class Role(Row):
table_name = 'roles'
primary_key = 'role_id'
+ join_tables = ['person_role', ('slice_attribute_types', 'min_role_id')]
fields = {
'role_id': Parameter(int, "Role identifier"),
'name': Parameter(str, "Role", max = 100),
}
- def __init__(self, api, fields = {}):
- Row.__init__(self, fields)
- self.api = api
-
def validate_role_id(self, role_id):
# Make sure role does not already exist
conflicts = Roles(self.api, [role_id])
return role_id
def validate_name(self, name):
- # Remove leading and trailing spaces
- name = name.strip()
-
- # Make sure name is not blank after we removed the spaces
- if not name:
+ # Make sure name is not blank
+ if not len(name):
raise PLCInvalidArgument, "Role must be specified"
# Make sure role does not already exist
return name
- def delete(self, commit = True):
- assert 'role_id' in self
-
- # Clean up miscellaneous join tables
- for table in ['person_role', 'roles']:
- self.api.db.do("DELETE FROM %s" \
- " WHERE role_id = %d" % \
- (table, self['role_id']), self)
-
- self.api.db.do("DELETE FROM attributes WHERE min_role_id = %d" % \
- self['role_id'])
-
- if commit:
- self.api.db.commit()
-
class Roles(Table):
"""
Representation of the roles table in the database.
"""
- def __init__(self, api, role_id_or_name_list = None):
- sql = "SELECT %s FROM roles" % \
+ def __init__(self, api, role_filter = None):
+ Table.__init__(self, api, Role)
+
+ sql = "SELECT %s FROM roles WHERE True" % \
", ".join(Role.fields)
- if role_id_or_name_list:
- # Separate the list into integers and strings
- role_ids = filter(lambda role_id: isinstance(role_id, (int, long)),
- role_id_or_name_list)
- names = filter(lambda name: isinstance(name, StringTypes),
- role_id_or_name_list)
- sql += " WHERE (False"
- if role_ids:
- sql += " OR role_id IN (%s)" % ", ".join(map(str, role_ids))
- if names:
- sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
- sql += ")"
-
- rows = api.db.selectall(sql)
-
- for row in rows:
- self[row['role_id']] = Role(api, row)
+ if role_filter is not None:
+ if isinstance(role_filter, (list, tuple, set)):
+ # Separate the list into integers and strings
+ ints = filter(lambda x: isinstance(x, (int, long)), role_filter)
+ strs = filter(lambda x: isinstance(x, StringTypes), role_filter)
+ role_filter = Filter(Role.fields, {'role_id': ints, 'name': strs})
+ sql += " AND (%s)" % role_filter.sql(api, "OR")
+ elif isinstance(role_filter, dict):
+ role_filter = Filter(Role.fields, role_filter)
+ sql += " AND (%s)" % role_filter.sql(api, "AND")
+
+ self.selectall(sql)