]> git.decadent.org.uk Git - dak.git/blob - daklib/dbconn.py
merge with master
[dak.git] / daklib / dbconn.py
1 #!/usr/bin/python
2
3 """ DB access class
4
5 @contact: Debian FTPMaster <ftpmaster@debian.org>
6 @copyright: 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
7 @copyright: 2008-2009  Mark Hymers <mhy@debian.org>
8 @copyright: 2009  Joerg Jaspert <joerg@debian.org>
9 @copyright: 2009  Mike O'Connor <stew@debian.org>
10 @license: GNU General Public License version 2 or later
11 """
12
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
17
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 # GNU General Public License for more details.
22
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
27 ################################################################################
28
29 # < mhy> I need a funny comment
30 # < sgran> two peanuts were walking down a dark street
31 # < sgran> one was a-salted
32 #  * mhy looks up the definition of "funny"
33
34 ################################################################################
35
36 import os
37 import psycopg2
38 import traceback
39
40 from singleton import Singleton
41 from config import Config
42
43 ################################################################################
44
45 class Cache(object):
46     def __init__(self, hashfunc=None):
47         if hashfunc:
48             self.hashfunc = hashfunc
49         else:
50             self.hashfunc = lambda x: x['value']
51
52         self.data = {}
53
54     def SetValue(self, keys, value):
55         self.data[self.hashfunc(keys)] = value
56
57     def GetValue(self, keys):
58         return self.data.get(self.hashfunc(keys))
59
60 ################################################################################
61
62 class DBConn(Singleton):
63     """
64     database module init.
65     """
66     def __init__(self, *args, **kwargs):
67         super(DBConn, self).__init__(*args, **kwargs)
68
69     def _startup(self, *args, **kwargs):
70         self.__createconn()
71         self.__init_caches()
72
73     ## Connection functions
74     def __createconn(self):
75         cnf = Config()
76         connstr = "dbname=%s" % cnf["DB::Name"]
77         if cnf["DB::Host"]:
78            connstr += " host=%s" % cnf["DB::Host"]
79         if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
80            connstr += " port=%s" % cnf["DB::Port"]
81
82         self.db_con = psycopg2.connect(connstr)
83
84     def reconnect(self):
85         try:
86             self.db_con.close()
87         except psycopg2.InterfaceError:
88             pass
89
90         self.db_con = None
91         self.__createconn()
92
93     ## Cache functions
94     def __init_caches(self):
95         self.caches = {'suite':         Cache(),
96                        'section':       Cache(),
97                        'priority':      Cache(),
98                        'override_type': Cache(),
99                        'architecture':  Cache(),
100                        'archive':       Cache(),
101                        'component':     Cache(),
102                        'content_path_names':     Cache(),
103                        'content_file_names':     Cache(),
104                        'location':      Cache(lambda x: '%s_%s_%s' % (x['location'], x['component'], x['location'])),
105                        'maintainer':    {}, # TODO
106                        'keyring':       {}, # TODO
107                        'source':        Cache(lambda x: '%s_%s_' % (x['source'], x['version'])),
108                        'files':         Cache(lambda x: '%s_%s_' % (x['filename'], x['location'])),
109                        'maintainer':    {}, # TODO
110                        'fingerprint':   {}, # TODO
111                        'queue':         {}, # TODO
112                        'uid':           {}, # TODO
113                        'suite_version': Cache(lambda x: '%s_%s' % (x['source'], x['suite'])),
114                       }
115
116         self.prepared_statements = {}
117
118     def prepare(self,name,statement):
119         if not self.prepared_statements.has_key(name):
120             c = self.cursor()
121             c.execute(statement)
122             self.prepared_statements[name] = statement
123
124     def clear_caches(self):
125         self.__init_caches()
126
127     ## Functions to pass through to the database connector
128     def cursor(self):
129         return self.db_con.cursor()
130
131     def commit(self):
132         return self.db_con.commit()
133
134     ## Get functions
135     def __get_single_id(self, query, values, cachename=None):
136         # This is a bit of a hack but it's an internal function only
137         if cachename is not None:
138             res = self.caches[cachename].GetValue(values)
139             if res:
140                 return res
141
142         c = self.db_con.cursor()
143         c.execute(query, values)
144
145         if c.rowcount != 1:
146             return None
147
148         res = c.fetchone()[0]
149
150         if cachename is not None:
151             self.caches[cachename].SetValue(values, res)
152
153         return res
154
155     def __get_id(self, retfield, table, qfield, value):
156         query = "SELECT %s FROM %s WHERE %s = %%(value)s" % (retfield, table, qfield)
157         return self.__get_single_id(query, {'value': value}, cachename=table)
158
159     def get_suite_id(self, suite):
160         """
161         Returns database id for given C{suite}.
162         Results are kept in a cache during runtime to minimize database queries.
163
164         @type suite: string
165         @param suite: The name of the suite
166
167         @rtype: int
168         @return: the database id for the given suite
169
170         """
171         return int(self.__get_id('id', 'suite', 'suite_name', suite))
172
173     def get_section_id(self, section):
174         """
175         Returns database id for given C{section}.
176         Results are kept in a cache during runtime to minimize database queries.
177
178         @type section: string
179         @param section: The name of the section
180
181         @rtype: int
182         @return: the database id for the given section
183
184         """
185         return self.__get_id('id', 'section', 'section', section)
186
187     def get_priority_id(self, priority):
188         """
189         Returns database id for given C{priority}.
190         Results are kept in a cache during runtime to minimize database queries.
191
192         @type priority: string
193         @param priority: The name of the priority
194
195         @rtype: int
196         @return: the database id for the given priority
197
198         """
199         return self.__get_id('id', 'priority', 'priority', priority)
200
201     def get_override_type_id(self, override_type):
202         """
203         Returns database id for given override C{type}.
204         Results are kept in a cache during runtime to minimize database queries.
205
206         @type override_type: string
207         @param override_type: The name of the override type
208
209         @rtype: int
210         @return: the database id for the given override type
211
212         """
213         return self.__get_id('id', 'override_type', 'type', override_type)
214
215     def get_architecture_id(self, architecture):
216         """
217         Returns database id for given C{architecture}.
218         Results are kept in a cache during runtime to minimize database queries.
219
220         @type architecture: string
221         @param architecture: The name of the override type
222
223         @rtype: int
224         @return: the database id for the given architecture
225
226         """
227         return self.__get_id('id', 'architecture', 'arch_string', architecture)
228
229     def get_archive_id(self, archive):
230         """
231         returns database id for given c{archive}.
232         results are kept in a cache during runtime to minimize database queries.
233
234         @type archive: string
235         @param archive: the name of the override type
236
237         @rtype: int
238         @return: the database id for the given archive
239
240         """
241         return self.__get_id('id', 'archive', 'lower(name)', archive)
242
243     def get_component_id(self, component):
244         """
245         Returns database id for given C{component}.
246         Results are kept in a cache during runtime to minimize database queries.
247
248         @type component: string
249         @param component: The name of the override type
250
251         @rtype: int
252         @return: the database id for the given component
253
254         """
255         return self.__get_id('id', 'component', 'lower(name)', component)
256
257     def get_location_id(self, location, component, archive):
258         """
259         Returns database id for the location behind the given combination of
260           - B{location} - the path of the location, eg. I{/srv/ftp.debian.org/ftp/pool/}
261           - B{component} - the id of the component as returned by L{get_component_id}
262           - B{archive} - the id of the archive as returned by L{get_archive_id}
263         Results are kept in a cache during runtime to minimize database queries.
264
265         @type location: string
266         @param location: the path of the location
267
268         @type component: int
269         @param component: the id of the component
270
271         @type archive: int
272         @param archive: the id of the archive
273
274         @rtype: int
275         @return: the database id for the location
276
277         """
278
279         archive_id = self.get_archive_id(archive)
280
281         if not archive_id:
282             return None
283
284         res = None
285
286         if component:
287             component_id = self.get_component_id(component)
288             if component_id:
289                 res = self.__get_single_id("SELECT id FROM location WHERE path=%(location)s AND component=%(component)s AND archive=%(archive)s",
290                         {'location': location,
291                          'archive': int(archive_id),
292                          'component': component_id}, cachename='location')
293         else:
294             res = self.__get_single_id("SELECT id FROM location WHERE path=%(location)s AND archive=%(archive)d",
295                     {'location': location, 'archive': archive_id, 'component': ''}, cachename='location')
296
297         return res
298
299     def get_source_id(self, source, version):
300         """
301         Returns database id for the combination of C{source} and C{version}
302           - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
303           - B{version}
304         Results are kept in a cache during runtime to minimize database queries.
305
306         @type source: string
307         @param source: source package name
308
309         @type version: string
310         @param version: the source version
311
312         @rtype: int
313         @return: the database id for the source
314
315         """
316         return self.__get_single_id("SELECT id FROM source s WHERE s.source=%(source)s AND s.version=%(version)s",
317                                  {'source': source, 'version': version}, cachename='source')
318
319     def get_suite_version(self, source, suite):
320         """
321         Returns database id for a combination of C{source} and C{suite}.
322
323           - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
324           - B{suite} - a suite name, eg. I{unstable}
325
326         Results are kept in a cache during runtime to minimize database queries.
327
328         @type source: string
329         @param source: source package name
330
331         @type suite: string
332         @param suite: the suite name
333
334         @rtype: string
335         @return: the version for I{source} in I{suite}
336
337         """
338         return self.__get_single_id("""
339         SELECT s.version FROM source s, suite su, src_associations sa
340         WHERE sa.source=s.id
341           AND sa.suite=su.id
342           AND su.suite_name=%(suite)s
343           AND s.source=%(source)""", {'suite': suite, 'source': source}, cachename='suite_version')
344
345
346     def get_files_id (self, filename, size, md5sum, location_id):
347         """
348         Returns -1, -2 or the file_id for filename, if its C{size} and C{md5sum} match an
349         existing copy.
350
351         The database is queried using the C{filename} and C{location_id}. If a file does exist
352         at that location, the existing size and md5sum are checked against the provided
353         parameters. A size or checksum mismatch returns -2. If more than one entry is
354         found within the database, a -1 is returned, no result returns None, otherwise
355         the file id.
356
357         Results are kept in a cache during runtime to minimize database queries.
358
359         @type filename: string
360         @param filename: the filename of the file to check against the DB
361
362         @type size: int
363         @param size: the size of the file to check against the DB
364
365         @type md5sum: string
366         @param md5sum: the md5sum of the file to check against the DB
367
368         @type location_id: int
369         @param location_id: the id of the location as returned by L{get_location_id}
370
371         @rtype: int / None
372         @return: Various return values are possible:
373                    - -2: size/checksum error
374                    - -1: more than one file found in database
375                    - None: no file found in database
376                    - int: file id
377
378         """
379         values = {'filename' : filename,
380                   'location' : location_id}
381
382         res = self.caches['files'].GetValue( values )
383
384         if not res:
385             query = """SELECT id, size, md5sum
386                        FROM files
387                        WHERE filename = %(filename)s AND location = %(location)s"""
388
389             cursor = self.db_con.cursor()
390             cursor.execute( query, values )
391
392             if cursor.rowcount == 0:
393                 res = None
394
395             elif cursor.rowcount != 1:
396                 res = -1
397
398             else:
399                 row = cursor.fetchone()
400
401                 if row[1] != int(size) or row[2] != md5sum:
402                     res =  -2
403
404                 else:
405                     self.caches['files'].SetValue(values, row[0])
406                     res = row[0]
407
408         return res
409
410
411     def get_or_set_contents_file_id(self, filename):
412         """
413         Returns database id for given filename.
414
415         Results are kept in a cache during runtime to minimize database queries.
416         If no matching file is found, a row is inserted.
417
418         @type filename: string
419         @param filename: The filename
420
421         @rtype: int
422         @return: the database id for the given component
423         """
424         try:
425             values={'value': filename}
426             query = "SELECT id FROM content_file_names WHERE file = %(value)s"
427             id = self.__get_single_id(query, values, cachename='content_file_names')
428             if not id:
429                 c = self.db_con.cursor()
430                 c.execute( "INSERT INTO content_file_names VALUES (DEFAULT, %(value)s) RETURNING id",
431                            values )
432
433                 id = c.fetchone()[0]
434                 self.caches['content_file_names'].SetValue(values, id)
435
436             return id
437         except:
438             traceback.print_exc()
439             raise
440
441     def get_or_set_contents_path_id(self, path):
442         """
443         Returns database id for given path.
444
445         Results are kept in a cache during runtime to minimize database queries.
446         If no matching file is found, a row is inserted.
447
448         @type path: string
449         @param path: The filename
450
451         @rtype: int
452         @return: the database id for the given component
453         """
454         try:
455             values={'value': path}
456             query = "SELECT id FROM content_file_paths WHERE path = %(value)s"
457             id = self.__get_single_id(query, values, cachename='content_path_names')
458             if not id:
459                 c = self.db_con.cursor()
460                 c.execute( "INSERT INTO content_file_paths VALUES (DEFAULT, %(value)s) RETURNING id",
461                            values )
462
463                 id = c.fetchone()[0]
464                 self.caches['content_path_names'].SetValue(values, id)
465
466             return id
467         except:
468             traceback.print_exc()
469             raise
470
471     def get_suite_architectures(self, suite):
472         """
473         Returns list of architectures for C{suite}.
474
475         @type suite: string, int
476         @param suite: the suite name or the suite_id
477
478         @rtype: list
479         @return: the list of architectures for I{suite}
480         """
481
482         suite_id = None
483         if type(suite) == str:
484             suite_id = self.get_suite_id(suite)
485         elif type(suite) == int:
486             suite_id = suite
487         else:
488             return None
489
490         c = self.db_con.cursor()
491         c.execute( """SELECT a.arch_string FROM suite_architectures sa
492                       JOIN architecture a ON (a.id = sa.architecture)
493                       WHERE suite='%s'""" % suite_id )
494
495         return map(lambda x: x[0], c.fetchall())
496
497     def insert_content_paths(self, bin_id, fullpaths):
498         """
499         Make sure given path is associated with given binary id
500
501         @type bin_id: int
502         @param bin_id: the id of the binary
503         @type fullpaths: list
504         @param fullpaths: the list of paths of the file being associated with the binary
505
506         @return: True upon success
507         """
508
509         c = self.db_con.cursor()
510
511         c.execute("BEGIN WORK")
512         try:
513
514             for fullpath in fullpaths:
515                 (path, file) = os.path.split(fullpath)
516
517                 if path.startswith( "./" ):
518                     path = path[2:]
519                 # Get the necessary IDs ...
520                 file_id = self.get_or_set_contents_file_id(file)
521                 path_id = self.get_or_set_contents_path_id(path)
522
523                 c.execute("""INSERT INTO content_associations
524                                (binary_pkg, filepath, filename)
525                            VALUES ( '%d', '%d', '%d')""" % (bin_id, path_id, file_id) )
526
527             c.execute("COMMIT")
528             return True
529         except:
530             traceback.print_exc()
531             c.execute("ROLLBACK")
532             return False
533
534     def insert_pending_content_paths(self, package, fullpaths):
535         """
536         Make sure given paths are temporarily associated with given
537         package
538
539         @type package: dict
540         @param package: the package to associate with should have been read in from the binary control file
541         @type fullpaths: list
542         @param fullpaths: the list of paths of the file being associated with the binary
543
544         @return: True upon success
545         """
546
547         c = self.db_con.cursor()
548
549         c.execute("BEGIN WORK")
550         try:
551             arch_id = self.get_architecture_id(package['Architecture'])
552
553             # Remove any already existing recorded files for this package
554             c.execute("""DELETE FROM pending_content_associations
555                          WHERE package=%(Package)s
556                          AND version=%(Version)s
557                          AND architecture=%(ArchID)s""", {'Package': package['Package'],
558                                                           'Version': package['Version'],
559                                                           'ArchID':  arch_id})
560
561             for fullpath in fullpaths:
562                 (path, file) = os.path.split(fullpath)
563
564                 if path.startswith( "./" ):
565                     path = path[2:]
566                 # Get the necessary IDs ...
567                 file_id = self.get_or_set_contents_file_id(file)
568                 path_id = self.get_or_set_contents_path_id(path)
569
570                 c.execute("""INSERT INTO pending_content_associations
571                                (package, version, architecture, filepath, filename)
572                             VALUES (%%(Package)s, %%(Version)s, '%d', '%d', '%d')"""
573                     % (arch_id, path_id, file_id), package )
574
575             c.execute("COMMIT")
576             return True
577         except:
578             traceback.print_exc()
579             c.execute("ROLLBACK")
580             return False