- use base class __init__() and delete() implementations
[plcapi.git] / PLC / Roles.py
1 #
2 # Functions for interacting with the roles table in the database
3 #
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
6 #
7 # $Id: Roles.py,v 1.4 2006/10/16 21:57:05 mlhuang Exp $
8 #
9
10 from types import StringTypes
11 from PLC.Faults import *
12 from PLC.Parameter import Parameter
13 from PLC.Table import Row, Table
14
15 class Role(Row):
16     """
17     Representation of a row in the roles table. To use,
18     instantiate with a dict of values.
19     """
20
21     table_name = 'roles'
22     primary_key = 'role_id'
23     join_tables = ['person_role', ('slice_attribute_types', 'min_role_id')]
24     fields = {
25         'role_id': Parameter(int, "Role identifier"),
26         'name': Parameter(str, "Role", max = 100),
27         }
28
29     def validate_role_id(self, role_id):
30         # Make sure role does not already exist
31         conflicts = Roles(self.api, [role_id])
32         if conflicts:
33             raise PLCInvalidArgument, "Role ID already in use"
34
35         return role_id
36
37     def validate_name(self, name):
38         # Remove leading and trailing spaces
39         name = name.strip()
40
41         # Make sure name is not blank after we removed the spaces
42         if not name:
43             raise PLCInvalidArgument, "Role must be specified"
44         
45         # Make sure role does not already exist
46         conflicts = Roles(self.api, [name])
47         if conflicts:
48             raise PLCInvalidArgument, "Role name already in use"
49
50         return name
51
52 class Roles(Table):
53     """
54     Representation of the roles table in the database.
55     """
56
57     def __init__(self, api, role_id_or_name_list = None):
58         sql = "SELECT %s FROM roles" % \
59               ", ".join(Role.fields)
60         
61         if role_id_or_name_list:
62             # Separate the list into integers and strings
63             role_ids = filter(lambda role_id: isinstance(role_id, (int, long)),
64                                    role_id_or_name_list)
65             names = filter(lambda name: isinstance(name, StringTypes),
66                            role_id_or_name_list)
67             sql += " WHERE (False"
68             if role_ids:
69                 sql += " OR role_id IN (%s)" % ", ".join(map(str, role_ids))
70             if names:
71                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
72             sql += ")"
73
74         rows = api.db.selectall(sql)
75
76         for row in rows:
77             self[row['role_id']] = Role(api, row)