- remove optional sub-parameter; we use these fields in both Add() and
[plcapi.git] / PLC / AddressTypes.py
1 #
2 # Functions for interacting with the address_types table in the database
3 #
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
6 #
7 # $Id: AddressTypes.py,v 1.5 2006/10/24 20:02:22 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 AddressType(Row):
16     """
17     Representation of a row in the address_types table. To use,
18     instantiate with a dict of values.
19     """
20
21     table_name = 'address_types'
22     primary_key = 'address_type_id'
23     join_tables = ['address_address_type']
24     fields = {
25         'address_type_id': Parameter(int, "Address type identifier"),
26         'name': Parameter(str, "Address type", max = 20),
27         'description': Parameter(str, "Address type description", max = 254),
28         }
29
30     def validate_name(self, name):
31         # Make sure name is not blank
32         if not len(name):
33             raise PLCInvalidArgument, "Address type must be specified"
34         
35         # Make sure address type does not already exist
36         conflicts = AddressTypes(self.api, [name])
37         for address_type_id in conflicts:
38             if 'address_type_id' not in self or self['address_type_id'] != address_type_id:
39                raise PLCInvalidArgument, "Address type name already in use"
40
41         return name
42
43 class AddressTypes(Table):
44     """
45     Representation of the address_types table in the database.
46     """
47
48     def __init__(self, api, address_type_id_or_name_list = None):
49         sql = "SELECT %s FROM address_types" % \
50               ", ".join(AddressType.fields)
51         
52         if address_type_id_or_name_list:
53             # Separate the list into integers and strings
54             address_type_ids = filter(lambda address_type_id: isinstance(address_type_id, (int, long)),
55                                    address_type_id_or_name_list)
56             names = filter(lambda name: isinstance(name, StringTypes),
57                            address_type_id_or_name_list)
58             sql += " WHERE (False"
59             if address_type_ids:
60                 sql += " OR address_type_id IN (%s)" % ", ".join(map(str, address_type_ids))
61             if names:
62                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
63             sql += ")"
64
65         rows = api.db.selectall(sql)
66
67         for row in rows:
68             self[row['address_type_id']] = AddressType(api, row)