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 return int(self.__get_id('id', 'suite', 'suite_name', suite))
173 def get_section_id(self, section):
175 Returns database id for given C{section}.
176 Results are kept in a cache during runtime to minimize database queries.
178 @type section: string
179 @param section: The name of the section
182 @return: the database id for the given section
185 return self.__get_id('id', 'section', 'section', section)
187 def get_priority_id(self, priority):
189 Returns database id for given C{priority}.
190 Results are kept in a cache during runtime to minimize database queries.
192 @type priority: string
193 @param priority: The name of the priority
196 @return: the database id for the given priority
199 return self.__get_id('id', 'priority', 'priority', priority)
201 def get_override_type_id(self, override_type):
203 Returns database id for given override C{type}.
204 Results are kept in a cache during runtime to minimize database queries.
207 @param type: The name of the override type
210 @return: the database id for the given override type
213 return self.__get_id('id', 'override_type', 'type', override_type)
215 def get_architecture_id(self, architecture):
217 Returns database id for given C{architecture}.
218 Results are kept in a cache during runtime to minimize database queries.
220 @type architecture: string
221 @param architecture: The name of the override type
224 @return: the database id for the given architecture
227 return self.__get_id('id', 'architecture', 'arch_string', architecture)
229 def get_archive_id(self, archive):
231 returns database id for given c{archive}.
232 results are kept in a cache during runtime to minimize database queries.
234 @type archive: string
235 @param archive: the name of the override type
238 @return: the database id for the given archive
241 return self.__get_id('id', 'archive', 'lower(name)', archive)
243 def get_component_id(self, component):
245 Returns database id for given C{component}.
246 Results are kept in a cache during runtime to minimize database queries.
248 @type component: string
249 @param component: The name of the override type
252 @return: the database id for the given component
255 return self.__get_id('id', 'component', 'lower(name)', component)
257 def get_location_id(self, location, component, archive):
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.
265 @type location: string
266 @param location: the path of the location
269 @param component: the id of the component
272 @param archive: the id of the archive
275 @return: the database id for the location
279 archive_id = self.get_archive_id(archive)
287 component_id = self.get_component_id(component)
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')
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')
299 def get_source_id(self, source, version):
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}
304 Results are kept in a cache during runtime to minimize database queries.
307 @param source: source package name
309 @type version: string
310 @param version: the source version
313 @return: the database id for the source
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')
319 def get_suite_version(self, source, suite):
321 Returns database id for a combination of C{source} and C{suite}.
323 - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
324 - B{suite} - a suite name, eg. I{unstable}
326 Results are kept in a cache during runtime to minimize database queries.
329 @param source: source package name
332 @param suite: the suite name
335 @return: the version for I{source} in I{suite}
338 return self.__get_single_id("""
339 SELECT s.version FROM source s, suite su, src_associations sa
342 AND su.suite_name=%(suite)s
343 AND s.source=%(source)""", {'suite': suite, 'source': source}, cachename='suite_version')
346 def get_files_id (self, filename, size, md5sum, location_id):
348 Returns -1, -2 or the file_id for filename, if its C{size} and C{md5sum} match an
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
357 Results are kept in a cache during runtime to minimize database queries.
359 @type filename: string
360 @param filename: the filename of the file to check against the DB
363 @param size: the size of the file to check against the DB
366 @param md5sum: the md5sum of the file to check against the DB
368 @type location_id: int
369 @param location_id: the id of the location as returned by L{get_location_id}
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
379 values = {'filename' : filename,
380 'location' : location_id}
382 res = self.caches['files'].GetValue( values )
385 query = """SELECT id, size, md5sum
387 WHERE filename = %(filename)s AND location = %(location)s"""
389 cursor = self.db_con.cursor()
390 cursor.execute( query, values )
392 if cursor.rowcount == 0:
395 elif cursor.rowcount != 1:
399 row = cursor.fetchone()
401 if row[1] != size or row[2] != md5sum:
405 self.caches[cachename].SetValue(values, row[0])
411 def get_or_set_contents_file_id(self, filename):
413 Returns database id for given filename.
415 Results are kept in a cache during runtime to minimize database queries.
416 If no matching file is found, a row is inserted.
418 @type filename: string
419 @param filename: The filename
422 @return: the database id for the given component
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')
429 c = self.db_con.cursor()
430 c.execute( "INSERT INTO content_file_names VALUES (DEFAULT, %(value)s) RETURNING id",
434 self.caches['content_file_names'].SetValue(values, id)
438 traceback.print_exc()
441 def get_or_set_contents_path_id(self, path):
443 Returns database id for given path.
445 Results are kept in a cache during runtime to minimize database queries.
446 If no matching file is found, a row is inserted.
449 @param path: The filename
452 @return: the database id for the given component
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')
459 c = self.db_con.cursor()
460 c.execute( "INSERT INTO content_file_paths VALUES (DEFAULT, %(value)s) RETURNING id",
464 self.caches['content_path_names'].SetValue(values, id)
468 traceback.print_exc()
471 def get_suite_architectures(self, suite):
473 Returns list of architectures for C{suite}.
475 @type suite: string, int
476 @param suite: the suite name or the suite_id
479 @return: the list of architectures for I{suite}
483 if type(suite) == str:
484 suite_id = self.get_suite_id(suite)
485 elif type(suite) == int:
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 )
495 return map(lambda x: x[0], c.fetchall())
497 def insert_content_paths(self, bin_id, fullpaths):
499 Make sure given path is associated with given binary id
502 @param bin_id: the id of the binary
503 @type fullpath: string
504 @param fullpath: the path of the file being associated with the binary
506 @return True upon success
509 c = self.db_con.cursor()
511 c.execute("BEGIN WORK")
514 for fullpath in fullpaths:
515 (path, file) = os.path.split(fullpath)
517 # Get the necessary IDs ...
518 file_id = self.get_or_set_contents_file_id(file)
519 path_id = self.get_or_set_contents_path_id(path)
521 c.execute("""INSERT INTO content_associations
522 (binary_pkg, filepath, filename)
523 VALUES ( '%d', '%d', '%d')""" % (bin_id, path_id, file_id) )
528 traceback.print_exc()
529 c.execute("ROLLBACK")
532 def insert_pending_content_paths(self, package, fullpaths):
534 Make sure given paths are temporarily associated with given
538 @param package: the package to associate with should have been read in from the binary control file
539 @type fullpaths: list
540 @param fullpaths: the list of paths of the file being associated with the binary
542 @return True upon success
545 c = self.db_con.cursor()
547 c.execute("BEGIN WORK")
549 arch_id = self.get_architecture_id(package['Architecture'])
551 # Remove any already existing recorded files for this package
552 c.execute("""DELETE FROM pending_content_associations
553 WHERE package=%(Package)s
554 AND version=%(Version)s
555 AND architecture=%(ArchID)s""", {'Package': package['Package'],
556 'Version': package['Version'],
559 for fullpath in fullpaths:
560 (path, file) = os.path.split(fullpath)
562 if path.startswith( "./" ):
564 # Get the necessary IDs ...
565 file_id = self.get_or_set_contents_file_id(file)
566 path_id = self.get_or_set_contents_path_id(path)
568 c.execute("""INSERT INTO pending_content_associations
569 (package, version, architecture, filepath, filename)
570 VALUES (%%(Package)s, %%(Version)s, '%d', '%d', '%d')"""
571 % (arch_id, path_id, file_id), package )
576 traceback.print_exc()
577 c.execute("ROLLBACK")