- use base class __init__() and delete() implementations
[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.3 2006/10/10 21:52:08 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         # Remove leading and trailing spaces
32         name = name.strip()
33
34         # Make sure name is not blank after we removed the spaces
35         if not name:
36             raise PLCInvalidArgument, "Address type must be specified"
37         
38         # Make sure address type does not already exist
39         conflicts = AddressTypes(self.api, [name])
40         for address_type_id in conflicts:
41             if 'address_type_id' not in self or self['address_type_id'] != address_type_id:
42                raise PLCInvalidArgument, "Address type name already in use"
43
44         return name
45
46 class AddressTypes(Table):
47     """
48     Representation of the address_types table in the database.
49     """
50
51     def __init__(self, api, address_type_id_or_name_list = None):
52         sql = "SELECT %s FROM address_types" % \
53               ", ".join(AddressType.fields)
54         
55         if address_type_id_or_name_list:
56             # Separate the list into integers and strings
57             address_type_ids = filter(lambda address_type_id: isinstance(address_type_id, (int, long)),
58                                    address_type_id_or_name_list)
59             names = filter(lambda name: isinstance(name, StringTypes),
60                            address_type_id_or_name_list)
61             sql += " WHERE (False"
62             if address_type_ids:
63                 sql += " OR address_type_id IN (%s)" % ", ".join(map(str, address_type_ids))
64             if names:
65                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
66             sql += ")"
67
68         rows = api.db.selectall(sql)
69
70         for row in rows:
71             self[row['address_type_id']] = AddressType(api, row)