]> git.decadent.org.uk Git - dak.git/blob - daklib/DBConn.py
Merge commit 'ftpmaster/master' into psycopg2
[dak.git] / daklib / DBConn.py
1 #!/usr/bin/env python
2
3 # DB access class
4 # Copyright (C) 2008  Mark Hymers <mhy@debian.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # < mhy> I need a funny comment
23 # < sgran> two peanuts were walking down a dark street
24 # < sgran> one was a-salted
25 #  * mhy looks up the definition of "funny"
26
27 ################################################################################
28
29 import psycopg2
30 from psycopg2.extras import DictCursor
31
32 from Singleton import Singleton
33 from Config import Config
34
35 ################################################################################
36
37 class Cache(object):
38     def __init__(self, hashfunc=None):
39         if hashfunc:
40             self.hashfunc = hashfunc
41         else:
42             self.hashfunc = lambda x: x['value']
43
44         self.data = {}
45
46     def SetValue(self, keys, value):
47         self.data[self.hashfunc(keys)] = value
48
49     def GetValue(self, keys):
50         return self.data.get(self.hashfunc(keys))
51
52 ################################################################################
53
54 class DBConn(Singleton):
55     """
56     A DBConn object is a singleton containing
57     information about the connection to the SQL Database
58     """
59     def __init__(self, *args, **kwargs):
60         super(DBConn, self).__init__(*args, **kwargs)
61
62     def _startup(self, *args, **kwargs):
63         self.__createconn()
64         self.__init_caches()
65
66     ## Connection functions
67     def __createconn(self):
68         connstr = Config().GetDBConnString()
69         self.db_con = psycopg2.connect(connstr)
70
71     def reconnect(self):
72         try:
73             self.db_con.close()
74         except psycopg2.InterfaceError:
75             pass
76
77         self.db_con = None
78         self.__createconn()
79
80     ## Cache functions
81     def __init_caches(self):
82         self.caches = {'suite':         Cache(), 
83                        'section':       Cache(),
84                        'priority':      Cache(),
85                        'override_type': Cache(),
86                        'architecture':  Cache(),
87                        'archive':       Cache(),
88                        'component':     Cache(),
89                        'location':      Cache(lambda x: '%s_%s_%s' % (x['location'], x['component'], x['location'])),
90                        'maintainer':    {}, # TODO
91                        'keyring':       {}, # TODO
92                        'source':        Cache(lambda x: '%s_%s_' % (x['source'], x['version'])),
93                        'files':         {}, # TODO
94                        'maintainer':    {}, # TODO
95                        'fingerprint':   {}, # TODO
96                        'queue':         {}, # TODO
97                        'uid':           {}, # TODO
98                        'suite_version': Cache(lambda x: '%s_%s' % (x['source'], x['suite'])),
99                       }
100
101     def clear_caches(self):
102         self.__init_caches()
103
104     ## Functions to pass through to the database connector
105     def cursor(self):
106         return self.db_con.cursor()
107
108     def commit(self):
109         return self.db_con.commit()
110
111     ## Get functions
112     def __get_single_id(self, query, values, cachename=None):
113         # This is a bit of a hack but it's an internal function only
114         if cachename is not None:
115             res = self.caches[cachename].GetValue(values)
116             if res:
117                 return res
118
119         c = self.db_con.cursor()
120         c.execute(query, values)
121
122         if c.rowcount != 1:
123             return None
124
125         res = c.fetchone()[0]
126
127         if cachename is not None:
128             self.caches[cachename].SetValue(values, res)
129             
130         return res
131    
132     def __get_id(self, retfield, table, qfield, value):
133         query = "SELECT %s FROM %s WHERE %s = %%(value)s" % (retfield, table, qfield)
134         return self.__get_single_id(query, {'value': value}, cachename=table)
135
136     def get_suite_id(self, suite):
137         return self.__get_id('id', 'suite', 'suite_name', suite)
138
139     def get_section_id(self, section):
140         return self.__get_id('id', 'section', 'section', section)
141
142     def get_priority_id(self, priority):
143         return self.__get_id('id', 'priority', 'priority', priority)
144
145     def get_override_type_id(self, override_type):
146         return self.__get_id('id', 'override_type', 'override_type', override_type)
147
148     def get_architecture_id(self, architecture):
149         return self.__get_id('id', 'architecture', 'arch_string', architecture)
150
151     def get_archive_id(self, archive):
152         return self.__get_id('id', 'archive', 'lower(name)', archive)
153
154     def get_component_id(self, component):
155         return self.__get_id('id', 'component', 'lower(name)', component)
156
157     def get_location_id(self, location, component, archive):
158         archive_id = self.get_archive_id(archive)
159
160         if not archive_id:
161             return None
162
163         res = None
164
165         if component:
166             component_id = self.get_component_id(component)
167             if component_id:
168                 res = self.__get_single_id("SELECT id FROM location WHERE path=%(location)s AND component=%(component)d AND archive=%(archive)d",
169                         {'location': location, 'archive': archive_id, 'component': component_id}, cachename='location')
170         else:
171             res = self.__get_single_id("SELECT id FROM location WHERE path=%(location)s AND archive=%(archive)d",
172                     {'location': location, 'archive': archive_id, 'component': ''}, cachename='location')
173
174         return res
175
176     def get_source_id(self, source, version):
177         return self.__get_single_id("SELECT id FROM source s WHERE s.source=%(source)s AND s.version=%(version)s",
178                                  {'source': source, 'version': version}, cachename='source')
179
180     def get_suite_version(self, source, suite):
181         return self.__get_single_id("""
182         SELECT s.version FROM source s, suite su, src_associations sa
183         WHERE sa.source=s.id
184           AND sa.suite=su.id
185           AND su.suite_name=%(suite)s
186           AND s.source=%(source)""", {'suite': suite, 'source': source}, cachename='suite_version')
187