1 # -*- coding: UTF-8 -*- |
|
2 # Copyright (c) 2008 - 2010, Pascal Volk |
|
3 # See COPYING for distribution information. |
|
4 |
|
5 """Virtual Mail Manager's Transport class to manage the transport for |
|
6 domains and accounts.""" |
|
7 |
|
8 from __main__ import ERR |
|
9 from Exceptions import VMMTransportException |
|
10 |
|
11 class Transport(object): |
|
12 """A wrapper class that provides access to the transport table""" |
|
13 __slots__ = ('__id', '__transport', '_dbh') |
|
14 def __init__(self, dbh, tid=None, transport=None): |
|
15 """Creates a new Transport instance. |
|
16 |
|
17 Either tid or transport must be specified. |
|
18 |
|
19 Keyword arguments: |
|
20 dbh -- a pyPgSQL.PgSQL.connection |
|
21 tid -- the id of a transport (long) |
|
22 transport -- the value of the transport (str) |
|
23 """ |
|
24 self._dbh = dbh |
|
25 if tid is None and transport is None: |
|
26 raise VMMTransportException( |
|
27 _('Either tid or transport must be specified.'), |
|
28 ERR.TRANSPORT_INIT) |
|
29 elif tid is not None: |
|
30 try: |
|
31 self.__id = long(tid) |
|
32 except ValueError: |
|
33 raise VMMTransportException(_('tid must be an int/long.'), |
|
34 ERR.TRANSPORT_INIT) |
|
35 self._loadByID() |
|
36 else: |
|
37 self.__transport = transport |
|
38 self._loadByName() |
|
39 |
|
40 def __eq__(self, other): |
|
41 if isinstance(other, self.__class__): |
|
42 return self.__id == other.getID() |
|
43 return NotImplemented |
|
44 |
|
45 def __ne__(self, other): |
|
46 if isinstance(other, self.__class__): |
|
47 return self.__id != other.getID() |
|
48 return NotImplemented |
|
49 |
|
50 def __str__(self): |
|
51 return self.__transport |
|
52 |
|
53 def _loadByID(self): |
|
54 dbc = self._dbh.cursor() |
|
55 dbc.execute('SELECT transport FROM transport WHERE tid = %s', self.__id) |
|
56 result = dbc.fetchone() |
|
57 dbc.close() |
|
58 if result is not None: |
|
59 self.__transport = result[0] |
|
60 else: |
|
61 raise VMMTransportException(_('Unknown tid specified.'), |
|
62 ERR.UNKNOWN_TRANSPORT_ID) |
|
63 |
|
64 def _loadByName(self): |
|
65 dbc = self._dbh.cursor() |
|
66 dbc.execute('SELECT tid FROM transport WHERE transport = %s', |
|
67 self.__transport) |
|
68 result = dbc.fetchone() |
|
69 dbc.close() |
|
70 if result is not None: |
|
71 self.__id = result[0] |
|
72 else: |
|
73 self._save() |
|
74 |
|
75 def _save(self): |
|
76 dbc = self._dbh.cursor() |
|
77 dbc.execute("SELECT nextval('transport_id')") |
|
78 self.__id = dbc.fetchone()[0] |
|
79 dbc.execute('INSERT INTO transport (tid, transport) VALUES (%s, %s)', |
|
80 self.__id, self.__transport) |
|
81 self._dbh.commit() |
|
82 dbc.close() |
|
83 |
|
84 def getID(self): |
|
85 """Returns the unique ID of the transport.""" |
|
86 return self.__id |
|
87 |
|
88 def getTransport(self): |
|
89 """Returns the value of transport, ex: 'dovecot:'""" |
|
90 return self.__transport |
|