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