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
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.
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.
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
27 ################################################################################
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"
34 ################################################################################
40 from singleton import Singleton
41 from config import Config
43 ################################################################################
46 def __init__(self, hashfunc=None):
48 self.hashfunc = hashfunc
50 self.hashfunc = lambda x: x['value']
54 def SetValue(self, keys, value):
55 self.data[self.hashfunc(keys)] = value
57 def GetValue(self, keys):
58 return self.data.get(self.hashfunc(keys))
60 ################################################################################
62 class DBConn(Singleton):
66 def __init__(self, *args, **kwargs):
67 super(DBConn, self).__init__(*args, **kwargs)
69 def _startup(self, *args, **kwargs):
73 ## Connection functions
74 def __createconn(self):
76 connstr = "dbname=%s" % cnf["DB::Name"]
78 connstr += " host=%s" % cnf["DB::Host"]
79 if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
80 connstr += " port=%s" % cnf["DB::Port"]
82 self.db_con = psycopg2.connect(connstr)
87 except psycopg2.InterfaceError:
94 def __init_caches(self):
95 self.caches = {'suite': Cache(),
98 'override_type': Cache(),
99 'architecture': 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
113 'suite_version': Cache(lambda x: '%s_%s' % (x['source'], x['suite'])),
116 self.prepared_statements = {}
118 def prepare(self,name,statement):
119 if not self.prepared_statements.has_key(name):
122 self.prepared_statements[name] = statement
124 def clear_caches(self):
127 ## Functions to pass through to the database connector
129 return self.db_con.cursor()
132 return self.db_con.commit()
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)
142 c = self.db_con.cursor()
143 c.execute(query, values)
148 res = c.fetchone()[0]
150 if cachename is not None:
151 self.caches[cachename].SetValue(values, res)
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)
159 def get_suite_id(self, suite):
161 Returns database id for given C{suite}.
162 Results are kept in a cache during runtime to minimize database queries.
165 @param suite: The name of the suite
168 @return: the database id for the given suite
171 suiteid = self.__get_id('id', 'suite', 'suite_name', suite)
177 def get_section_id(self, section):
179 Returns database id for given C{section}.
180 Results are kept in a cache during runtime to minimize database queries.
182 @type section: string
183 @param section: The name of the section
186 @return: the database id for the given section
189 return self.__get_id('id', 'section', 'section', section)
191 def get_priority_id(self, priority):
193 Returns database id for given C{priority}.
194 Results are kept in a cache during runtime to minimize database queries.
196 @type priority: string
197 @param priority: The name of the priority
200 @return: the database id for the given priority
203 return self.__get_id('id', 'priority', 'priority', priority)
205 def get_override_type_id(self, override_type):
207 Returns database id for given override C{type}.
208 Results are kept in a cache during runtime to minimize database queries.
210 @type override_type: string
211 @param override_type: The name of the override type
214 @return: the database id for the given override type
217 return self.__get_id('id', 'override_type', 'type', override_type)
219 def get_architecture_id(self, architecture):
221 Returns database id for given C{architecture}.
222 Results are kept in a cache during runtime to minimize database queries.
224 @type architecture: string
225 @param architecture: The name of the override type
228 @return: the database id for the given architecture
231 return self.__get_id('id', 'architecture', 'arch_string', architecture)
233 def get_archive_id(self, archive):
235 returns database id for given c{archive}.
236 results are kept in a cache during runtime to minimize database queries.
238 @type archive: string
239 @param archive: the name of the override type
242 @return: the database id for the given archive
245 return self.__get_id('id', 'archive', 'lower(name)', archive)
247 def get_component_id(self, component):
249 Returns database id for given C{component}.
250 Results are kept in a cache during runtime to minimize database queries.
252 @type component: string
253 @param component: The name of the override type
256 @return: the database id for the given component
259 return self.__get_id('id', 'component', 'lower(name)', component)
261 def get_location_id(self, location, component, archive):
263 Returns database id for the location behind the given combination of
264 - B{location} - the path of the location, eg. I{/srv/ftp.debian.org/ftp/pool/}
265 - B{component} - the id of the component as returned by L{get_component_id}
266 - B{archive} - the id of the archive as returned by L{get_archive_id}
267 Results are kept in a cache during runtime to minimize database queries.
269 @type location: string
270 @param location: the path of the location
273 @param component: the id of the component
276 @param archive: the id of the archive
279 @return: the database id for the location
283 archive_id = self.get_archive_id(archive)
291 component_id = self.get_component_id(component)
293 res = self.__get_single_id("SELECT id FROM location WHERE path=%(location)s AND component=%(component)s AND archive=%(archive)s",
294 {'location': location,
295 'archive': int(archive_id),
296 'component': component_id}, cachename='location')
298 res = self.__get_single_id("SELECT id FROM location WHERE path=%(location)s AND archive=%(archive)d",
299 {'location': location, 'archive': archive_id, 'component': ''}, cachename='location')
303 def get_source_id(self, source, version):
305 Returns database id for the combination of C{source} and C{version}
306 - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
308 Results are kept in a cache during runtime to minimize database queries.
311 @param source: source package name
313 @type version: string
314 @param version: the source version
317 @return: the database id for the source
320 return self.__get_single_id("SELECT id FROM source s WHERE s.source=%(source)s AND s.version=%(version)s",
321 {'source': source, 'version': version}, cachename='source')
323 def get_suite_version(self, source, suite):
325 Returns database id for a combination of C{source} and C{suite}.
327 - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
328 - B{suite} - a suite name, eg. I{unstable}
330 Results are kept in a cache during runtime to minimize database queries.
333 @param source: source package name
336 @param suite: the suite name
339 @return: the version for I{source} in I{suite}
342 return self.__get_single_id("""
343 SELECT s.version FROM source s, suite su, src_associations sa
346 AND su.suite_name=%(suite)s
347 AND s.source=%(source)""", {'suite': suite, 'source': source}, cachename='suite_version')
350 def get_files_id (self, filename, size, md5sum, location_id):
352 Returns -1, -2 or the file_id for filename, if its C{size} and C{md5sum} match an
355 The database is queried using the C{filename} and C{location_id}. If a file does exist
356 at that location, the existing size and md5sum are checked against the provided
357 parameters. A size or checksum mismatch returns -2. If more than one entry is
358 found within the database, a -1 is returned, no result returns None, otherwise
361 Results are kept in a cache during runtime to minimize database queries.
363 @type filename: string
364 @param filename: the filename of the file to check against the DB
367 @param size: the size of the file to check against the DB
370 @param md5sum: the md5sum of the file to check against the DB
372 @type location_id: int
373 @param location_id: the id of the location as returned by L{get_location_id}
376 @return: Various return values are possible:
377 - -2: size/checksum error
378 - -1: more than one file found in database
379 - None: no file found in database
383 values = {'filename' : filename,
384 'location' : location_id}
386 res = self.caches['files'].GetValue( values )
389 query = """SELECT id, size, md5sum
391 WHERE filename = %(filename)s AND location = %(location)s"""
393 cursor = self.db_con.cursor()
394 cursor.execute( query, values )
396 if cursor.rowcount == 0:
399 elif cursor.rowcount != 1:
403 row = cursor.fetchone()
405 if row[1] != int(size) or row[2] != md5sum:
409 self.caches['files'].SetValue(values, row[0])
415 def get_or_set_contents_file_id(self, filename):
417 Returns database id for given filename.
419 Results are kept in a cache during runtime to minimize database queries.
420 If no matching file is found, a row is inserted.
422 @type filename: string
423 @param filename: The filename
426 @return: the database id for the given component
429 values={'value': filename}
430 query = "SELECT id FROM content_file_names WHERE file = %(value)s"
431 id = self.__get_single_id(query, values, cachename='content_file_names')
433 c = self.db_con.cursor()
434 c.execute( "INSERT INTO content_file_names VALUES (DEFAULT, %(value)s) RETURNING id",
438 self.caches['content_file_names'].SetValue(values, id)
442 traceback.print_exc()
445 def get_or_set_contents_path_id(self, path):
447 Returns database id for given path.
449 Results are kept in a cache during runtime to minimize database queries.
450 If no matching file is found, a row is inserted.
453 @param path: The filename
456 @return: the database id for the given component
459 values={'value': path}
460 query = "SELECT id FROM content_file_paths WHERE path = %(value)s"
461 id = self.__get_single_id(query, values, cachename='content_path_names')
463 c = self.db_con.cursor()
464 c.execute( "INSERT INTO content_file_paths VALUES (DEFAULT, %(value)s) RETURNING id",
468 self.caches['content_path_names'].SetValue(values, id)
472 traceback.print_exc()
475 def get_suite_architectures(self, suite):
477 Returns list of architectures for C{suite}.
479 @type suite: string, int
480 @param suite: the suite name or the suite_id
483 @return: the list of architectures for I{suite}
487 if type(suite) == str:
488 suite_id = self.get_suite_id(suite)
489 elif type(suite) == int:
494 c = self.db_con.cursor()
495 c.execute( """SELECT a.arch_string FROM suite_architectures sa
496 JOIN architecture a ON (a.id = sa.architecture)
497 WHERE suite='%s'""" % suite_id )
499 return map(lambda x: x[0], c.fetchall())
501 def insert_content_paths(self, bin_id, fullpaths):
503 Make sure given path is associated with given binary id
506 @param bin_id: the id of the binary
507 @type fullpaths: list
508 @param fullpaths: the list of paths of the file being associated with the binary
510 @return: True upon success
513 c = self.db_con.cursor()
515 c.execute("BEGIN WORK")
518 for fullpath in fullpaths:
519 (path, file) = os.path.split(fullpath)
521 if path.startswith( "./" ):
523 # Get the necessary IDs ...
524 file_id = self.get_or_set_contents_file_id(file)
525 path_id = self.get_or_set_contents_path_id(path)
527 c.execute("""INSERT INTO content_associations
528 (binary_pkg, filepath, filename)
529 VALUES ( '%d', '%d', '%d')""" % (bin_id, path_id, file_id) )
534 traceback.print_exc()
535 c.execute("ROLLBACK")
538 def insert_pending_content_paths(self, package, fullpaths):
540 Make sure given paths are temporarily associated with given
544 @param package: the package to associate with should have been read in from the binary control file
545 @type fullpaths: list
546 @param fullpaths: the list of paths of the file being associated with the binary
548 @return: True upon success
551 c = self.db_con.cursor()
553 c.execute("BEGIN WORK")
555 arch_id = self.get_architecture_id(package['Architecture'])
557 # Remove any already existing recorded files for this package
558 c.execute("""DELETE FROM pending_content_associations
559 WHERE package=%(Package)s
560 AND version=%(Version)s
561 AND architecture=%(ArchID)s""", {'Package': package['Package'],
562 'Version': package['Version'],
565 for fullpath in fullpaths:
566 (path, file) = os.path.split(fullpath)
568 if path.startswith( "./" ):
570 # Get the necessary IDs ...
571 file_id = self.get_or_set_contents_file_id(file)
572 path_id = self.get_or_set_contents_path_id(path)
574 c.execute("""INSERT INTO pending_content_associations
575 (package, version, architecture, filepath, filename)
576 VALUES (%%(Package)s, %%(Version)s, '%d', '%d', '%d')"""
577 % (arch_id, path_id, file_id), package )
582 traceback.print_exc()
583 c.execute("ROLLBACK")