Merge remote-tracking branch 'origin/pycurl' into planetlab-4_0-branch
[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 5574 2007-10-25 20:33:17Z thierry $
8 #
9
10 from types import StringTypes
11 from PLC.Faults import *
12 from PLC.Parameter import Parameter
13 from PLC.Filter import Filter
14 from PLC.Table import Row, Table
15
16 class AddressType(Row):
17     """
18     Representation of a row in the address_types table. To use,
19     instantiate with a dict of values.
20     """
21
22     table_name = 'address_types'
23     primary_key = 'address_type_id'
24     join_tables = ['address_address_type']
25     fields = {
26         'address_type_id': Parameter(int, "Address type identifier"),
27         'name': Parameter(str, "Address type", max = 20),
28         'description': Parameter(str, "Address type description", max = 254),
29         }
30
31     def validate_name(self, name):
32         # Make sure name is not blank
33         if not len(name):
34             raise PLCInvalidArgument, "Address type must be specified"
35         
36         # Make sure address type does not already exist
37         conflicts = AddressTypes(self.api, [name])
38         for address_type_id in conflicts:
39             if 'address_type_id' not in self or self['address_type_id'] != address_type_id:
40                raise PLCInvalidArgument, "Address type name already in use"
41
42         return name
43
44 class AddressTypes(Table):
45     """
46     Representation of the address_types table in the database.
47     """
48
49     def __init__(self, api, address_type_filter = None, columns = None):
50         Table.__init__(self, api, AddressType, columns)
51
52         sql = "SELECT %s FROM address_types WHERE True" % \
53               ", ".join(self.columns)
54
55         if address_type_filter is not None:
56             if isinstance(address_type_filter, (list, tuple, set)):
57                 # Separate the list into integers and strings
58                 ints = filter(lambda x: isinstance(x, (int, long)), address_type_filter)
59                 strs = filter(lambda x: isinstance(x, StringTypes), address_type_filter)
60                 address_type_filter = Filter(AddressType.fields, {'address_type_id': ints, 'name': strs})
61                 sql += " AND (%s) %s" % address_type_filter.sql(api, "OR")
62             elif isinstance(address_type_filter, dict):
63                 address_type_filter = Filter(AddressType.fields, address_type_filter)
64                 sql += " AND (%s) %s" % address_type_filter.sql(api, "AND")
65
66         self.selectall(sql)