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 inspect import getargspec
42 from sqlalchemy import create_engine, Table, MetaData, select
43 from sqlalchemy.orm import sessionmaker, mapper, relation
45 # Don't remove this, we re-export the exceptions to scripts which import us
46 from sqlalchemy.exc import *
47 from sqlalchemy.orm.exc import NoResultFound
49 # Only import Config until Queue stuff is changed to store its config
51 from config import Config
52 from singleton import Singleton
53 from textutils import fix_maintainer
55 ################################################################################
57 __all__ = ['IntegrityError', 'SQLAlchemyError']
59 ################################################################################
61 def session_wrapper(fn):
62 def wrapped(*args, **kwargs):
63 private_transaction = False
64 session = kwargs.get('session')
66 # No session specified as last argument or in kwargs, create one.
67 if session is None or len(args) == len(getargspec(fn)[0]) - 1:
68 private_transaction = True
69 kwargs['session'] = DBConn().session()
72 return fn(*args, **kwargs)
74 if private_transaction:
75 # We created a session; close it.
76 kwargs['session'].close()
78 wrapped.__doc__ = fn.__doc__
79 wrapped.func_name = fn.func_name
83 ################################################################################
85 class Architecture(object):
86 def __init__(self, *args, **kwargs):
89 def __eq__(self, val):
90 if isinstance(val, str):
91 return (self.arch_string== val)
92 # This signals to use the normal comparison operator
95 def __ne__(self, val):
96 if isinstance(val, str):
97 return (self.arch_string != val)
98 # This signals to use the normal comparison operator
102 return '<Architecture %s>' % self.arch_string
104 __all__.append('Architecture')
107 def get_architecture(architecture, session=None):
109 Returns database id for given C{architecture}.
111 @type architecture: string
112 @param architecture: The name of the architecture
114 @type session: Session
115 @param session: Optional SQLA session object (a temporary one will be
116 generated if not supplied)
119 @return: Architecture object for the given arch (None if not present)
122 q = session.query(Architecture).filter_by(arch_string=architecture)
126 except NoResultFound:
129 __all__.append('get_architecture')
132 def get_architecture_suites(architecture, session=None):
134 Returns list of Suite objects for given C{architecture} name
137 @param source: Architecture name to search for
139 @type session: Session
140 @param session: Optional SQL session object (a temporary one will be
141 generated if not supplied)
144 @return: list of Suite objects for the given name (may be empty)
147 q = session.query(Suite)
148 q = q.join(SuiteArchitecture)
149 q = q.join(Architecture).filter_by(arch_string=architecture).order_by('suite_name')
155 __all__.append('get_architecture_suites')
157 ################################################################################
159 class Archive(object):
160 def __init__(self, *args, **kwargs):
164 return '<Archive %s>' % self.archive_name
166 __all__.append('Archive')
169 def get_archive(archive, session=None):
171 returns database id for given c{archive}.
173 @type archive: string
174 @param archive: the name of the arhive
176 @type session: Session
177 @param session: Optional SQLA session object (a temporary one will be
178 generated if not supplied)
181 @return: Archive object for the given name (None if not present)
184 archive = archive.lower()
186 q = session.query(Archive).filter_by(archive_name=archive)
190 except NoResultFound:
193 __all__.append('get_archive')
195 ################################################################################
197 class BinAssociation(object):
198 def __init__(self, *args, **kwargs):
202 return '<BinAssociation %s (%s, %s)>' % (self.ba_id, self.binary, self.suite)
204 __all__.append('BinAssociation')
206 ################################################################################
208 class DBBinary(object):
209 def __init__(self, *args, **kwargs):
213 return '<DBBinary %s (%s, %s)>' % (self.package, self.version, self.architecture)
215 __all__.append('DBBinary')
218 def get_suites_binary_in(package, session=None):
220 Returns list of Suite objects which given C{package} name is in
223 @param source: DBBinary package name to search for
226 @return: list of Suite objects for the given package
229 return session.query(Suite).join(BinAssociation).join(DBBinary).filter_by(package=package).all()
231 __all__.append('get_suites_binary_in')
234 def get_binary_from_id(id, session=None):
236 Returns DBBinary object for given C{id}
239 @param id: Id of the required binary
241 @type session: Session
242 @param session: Optional SQLA session object (a temporary one will be
243 generated if not supplied)
246 @return: DBBinary object for the given binary (None if not present)
249 q = session.query(DBBinary).filter_by(binary_id=id)
253 except NoResultFound:
256 __all__.append('get_binary_from_id')
259 def get_binaries_from_name(package, version=None, architecture=None, session=None):
261 Returns list of DBBinary objects for given C{package} name
264 @param package: DBBinary package name to search for
266 @type version: str or None
267 @param version: Version to search for (or None)
269 @type package: str, list or None
270 @param package: Architectures to limit to (or None if no limit)
272 @type session: Session
273 @param session: Optional SQL session object (a temporary one will be
274 generated if not supplied)
277 @return: list of DBBinary objects for the given name (may be empty)
280 q = session.query(DBBinary).filter_by(package=package)
282 if version is not None:
283 q = q.filter_by(version=version)
285 if architecture is not None:
286 if not isinstance(architecture, list):
287 architecture = [architecture]
288 q = q.join(Architecture).filter(Architecture.arch_string.in_(architecture))
294 __all__.append('get_binaries_from_name')
297 def get_binaries_from_source_id(source_id, session=None):
299 Returns list of DBBinary objects for given C{source_id}
302 @param source_id: source_id to search for
304 @type session: Session
305 @param session: Optional SQL session object (a temporary one will be
306 generated if not supplied)
309 @return: list of DBBinary objects for the given name (may be empty)
312 return session.query(DBBinary).filter_by(source_id=source_id).all()
314 __all__.append('get_binaries_from_source_id')
317 def get_binary_from_name_suite(package, suitename, session=None):
318 ### For dak examine-package
319 ### XXX: Doesn't use object API yet
321 sql = """SELECT DISTINCT(b.package), b.version, c.name, su.suite_name
322 FROM binaries b, files fi, location l, component c, bin_associations ba, suite su
323 WHERE b.package=:package
325 AND fi.location = l.id
326 AND l.component = c.id
329 AND su.suite_name=:suitename
330 ORDER BY b.version DESC"""
332 return session.execute(sql, {'package': package, 'suitename': suitename})
334 __all__.append('get_binary_from_name_suite')
337 def get_binary_components(package, suitename, arch, session=None):
338 # Check for packages that have moved from one component to another
339 query = """SELECT c.name FROM binaries b, bin_associations ba, suite s, location l, component c, architecture a, files f
340 WHERE b.package=:package AND s.suite_name=:suitename
341 AND (a.arch_string = :arch OR a.arch_string = 'all')
342 AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
343 AND f.location = l.id
344 AND l.component = c.id
347 vals = {'package': package, 'suitename': suitename, 'arch': arch}
349 return session.execute(query, vals)
351 __all__.append('get_binary_components')
353 ################################################################################
355 class Component(object):
356 def __init__(self, *args, **kwargs):
359 def __eq__(self, val):
360 if isinstance(val, str):
361 return (self.component_name == val)
362 # This signals to use the normal comparison operator
363 return NotImplemented
365 def __ne__(self, val):
366 if isinstance(val, str):
367 return (self.component_name != val)
368 # This signals to use the normal comparison operator
369 return NotImplemented
372 return '<Component %s>' % self.component_name
375 __all__.append('Component')
378 def get_component(component, session=None):
380 Returns database id for given C{component}.
382 @type component: string
383 @param component: The name of the override type
386 @return: the database id for the given component
389 component = component.lower()
391 q = session.query(Component).filter_by(component_name=component)
395 except NoResultFound:
398 __all__.append('get_component')
400 ################################################################################
402 class DBConfig(object):
403 def __init__(self, *args, **kwargs):
407 return '<DBConfig %s>' % self.name
409 __all__.append('DBConfig')
411 ################################################################################
413 class ContentFilename(object):
414 def __init__(self, *args, **kwargs):
418 return '<ContentFilename %s>' % self.filename
420 __all__.append('ContentFilename')
422 def get_or_set_contents_file_id(filename, session=None):
424 Returns database id for given filename.
426 If no matching file is found, a row is inserted.
428 @type filename: string
429 @param filename: The filename
430 @type session: SQLAlchemy
431 @param session: Optional SQL session object (a temporary one will be
432 generated if not supplied). If not passed, a commit will be performed at
433 the end of the function, otherwise the caller is responsible for commiting.
436 @return: the database id for the given component
440 session = DBConn().session()
443 q = session.query(ContentFilename).filter_by(filename=filename)
446 ret = q.one().cafilename_id
447 except NoResultFound:
448 cf = ContentFilename()
449 cf.filename = filename
455 ret = cf.cafilename_id
462 __all__.append('get_or_set_contents_file_id')
465 def get_contents(suite, overridetype, section=None, session=None):
467 Returns contents for a suite / overridetype combination, limiting
468 to a section if not None.
471 @param suite: Suite object
473 @type overridetype: OverrideType
474 @param overridetype: OverrideType object
476 @type section: Section
477 @param section: Optional section object to limit results to
479 @type session: SQLAlchemy
480 @param session: Optional SQL session object (a temporary one will be
481 generated if not supplied)
484 @return: ResultsProxy object set up to return tuples of (filename, section,
488 # find me all of the contents for a given suite
489 contents_q = """SELECT (p.path||'/'||n.file) AS fn,
493 FROM content_associations c join content_file_paths p ON (c.filepath=p.id)
494 JOIN content_file_names n ON (c.filename=n.id)
495 JOIN binaries b ON (b.id=c.binary_pkg)
496 JOIN override o ON (o.package=b.package)
497 JOIN section s ON (s.id=o.section)
498 WHERE o.suite = :suiteid AND o.type = :overridetypeid
499 AND b.type=:overridetypename"""
501 vals = {'suiteid': suite.suite_id,
502 'overridetypeid': overridetype.overridetype_id,
503 'overridetypename': overridetype.overridetype}
505 if section is not None:
506 contents_q += " AND s.id = :sectionid"
507 vals['sectionid'] = section.section_id
509 contents_q += " ORDER BY fn"
511 return session.execute(contents_q, vals)
513 __all__.append('get_contents')
515 ################################################################################
517 class ContentFilepath(object):
518 def __init__(self, *args, **kwargs):
522 return '<ContentFilepath %s>' % self.filepath
524 __all__.append('ContentFilepath')
526 def get_or_set_contents_path_id(filepath, session=None):
528 Returns database id for given path.
530 If no matching file is found, a row is inserted.
532 @type filename: string
533 @param filename: The filepath
534 @type session: SQLAlchemy
535 @param session: Optional SQL session object (a temporary one will be
536 generated if not supplied). If not passed, a commit will be performed at
537 the end of the function, otherwise the caller is responsible for commiting.
540 @return: the database id for the given path
544 session = DBConn().session()
547 q = session.query(ContentFilepath).filter_by(filepath=filepath)
550 ret = q.one().cafilepath_id
551 except NoResultFound:
552 cf = ContentFilepath()
553 cf.filepath = filepath
559 ret = cf.cafilepath_id
566 __all__.append('get_or_set_contents_path_id')
568 ################################################################################
570 class ContentAssociation(object):
571 def __init__(self, *args, **kwargs):
575 return '<ContentAssociation %s>' % self.ca_id
577 __all__.append('ContentAssociation')
579 def insert_content_paths(binary_id, fullpaths, session=None):
581 Make sure given path is associated with given binary id
584 @param binary_id: the id of the binary
585 @type fullpaths: list
586 @param fullpaths: the list of paths of the file being associated with the binary
587 @type session: SQLAlchemy session
588 @param session: Optional SQLAlchemy session. If this is passed, the caller
589 is responsible for ensuring a transaction has begun and committing the
590 results or rolling back based on the result code. If not passed, a commit
591 will be performed at the end of the function, otherwise the caller is
592 responsible for commiting.
594 @return: True upon success
599 session = DBConn().session()
605 for fullpath in fullpaths:
606 # Get the necessary IDs ...
607 (path, file) = os.path.split(fullpath)
609 filepath_id = get_or_set_contents_path_id(path, session)
610 filename_id = get_or_set_contents_file_id(file, session)
612 pathcache[fullpath] = (filepath_id, filename_id)
614 for fullpath, dat in pathcache.items():
615 ca = ContentAssociation()
616 ca.binary_id = binary_id
617 ca.filepath_id = dat[0]
618 ca.filename_id = dat[1]
621 # Only commit if we set up the session ourself
631 traceback.print_exc()
633 # Only rollback if we set up the session ourself
640 __all__.append('insert_content_paths')
642 ################################################################################
644 class DSCFile(object):
645 def __init__(self, *args, **kwargs):
649 return '<DSCFile %s>' % self.dscfile_id
651 __all__.append('DSCFile')
654 def get_dscfiles(dscfile_id=None, source_id=None, poolfile_id=None, session=None):
656 Returns a list of DSCFiles which may be empty
658 @type dscfile_id: int (optional)
659 @param dscfile_id: the dscfile_id of the DSCFiles to find
661 @type source_id: int (optional)
662 @param source_id: the source id related to the DSCFiles to find
664 @type poolfile_id: int (optional)
665 @param poolfile_id: the poolfile id related to the DSCFiles to find
668 @return: Possibly empty list of DSCFiles
671 q = session.query(DSCFile)
673 if dscfile_id is not None:
674 q = q.filter_by(dscfile_id=dscfile_id)
676 if source_id is not None:
677 q = q.filter_by(source_id=source_id)
679 if poolfile_id is not None:
680 q = q.filter_by(poolfile_id=poolfile_id)
684 __all__.append('get_dscfiles')
686 ################################################################################
688 class PoolFile(object):
689 def __init__(self, *args, **kwargs):
693 return '<PoolFile %s>' % self.filename
695 __all__.append('PoolFile')
698 def check_poolfile(filename, filesize, md5sum, location_id, session=None):
701 (ValidFileFound [boolean or None], PoolFile object or None)
703 @type filename: string
704 @param filename: the filename of the file to check against the DB
707 @param filesize: the size of the file to check against the DB
710 @param md5sum: the md5sum of the file to check against the DB
712 @type location_id: int
713 @param location_id: the id of the location to look in
716 @return: Tuple of length 2.
717 If more than one file found with that name:
719 If valid pool file found: (True, PoolFile object)
720 If valid pool file not found:
721 (False, None) if no file found
722 (False, PoolFile object) if file found with size/md5sum mismatch
725 q = session.query(PoolFile).filter_by(filename=filename)
726 q = q.join(Location).filter_by(location_id=location_id)
736 if obj.md5sum != md5sum or obj.filesize != filesize:
744 __all__.append('check_poolfile')
747 def get_poolfile_by_id(file_id, session=None):
749 Returns a PoolFile objects or None for the given id
752 @param file_id: the id of the file to look for
754 @rtype: PoolFile or None
755 @return: either the PoolFile object or None
758 q = session.query(PoolFile).filter_by(file_id=file_id)
762 except NoResultFound:
765 __all__.append('get_poolfile_by_id')
769 def get_poolfile_by_name(filename, location_id=None, session=None):
771 Returns an array of PoolFile objects for the given filename and
772 (optionally) location_id
774 @type filename: string
775 @param filename: the filename of the file to check against the DB
777 @type location_id: int
778 @param location_id: the id of the location to look in (optional)
781 @return: array of PoolFile objects
784 q = session.query(PoolFile).filter_by(filename=filename)
786 if location_id is not None:
787 q = q.join(Location).filter_by(location_id=location_id)
791 __all__.append('get_poolfile_by_name')
794 def get_poolfile_like_name(filename, session=None):
796 Returns an array of PoolFile objects which are like the given name
798 @type filename: string
799 @param filename: the filename of the file to check against the DB
802 @return: array of PoolFile objects
805 # TODO: There must be a way of properly using bind parameters with %FOO%
806 q = session.query(PoolFile).filter(PoolFile.filename.like('%%%s%%' % filename))
810 __all__.append('get_poolfile_like_name')
812 ################################################################################
814 class Fingerprint(object):
815 def __init__(self, *args, **kwargs):
819 return '<Fingerprint %s>' % self.fingerprint
821 __all__.append('Fingerprint')
823 def get_or_set_fingerprint(fpr, session=None):
825 Returns Fingerprint object for given fpr.
827 If no matching fpr is found, a row is inserted.
830 @param fpr: The fpr to find / add
832 @type session: SQLAlchemy
833 @param session: Optional SQL session object (a temporary one will be
834 generated if not supplied). If not passed, a commit will be performed at
835 the end of the function, otherwise the caller is responsible for commiting.
836 A flush will be performed either way.
839 @return: the Fingerprint object for the given fpr
843 session = DBConn().session()
846 q = session.query(Fingerprint).filter_by(fingerprint=fpr)
850 except NoResultFound:
851 fingerprint = Fingerprint()
852 fingerprint.fingerprint = fpr
853 session.add(fingerprint)
865 __all__.append('get_or_set_fingerprint')
867 ################################################################################
869 class Keyring(object):
870 def __init__(self, *args, **kwargs):
874 return '<Keyring %s>' % self.keyring_name
876 __all__.append('Keyring')
878 def get_or_set_keyring(keyring, session=None):
880 If C{keyring} does not have an entry in the C{keyrings} table yet, create one
881 and return the new Keyring
882 If C{keyring} already has an entry, simply return the existing Keyring
884 @type keyring: string
885 @param keyring: the keyring name
888 @return: the Keyring object for this keyring
893 session = DBConn().session()
897 obj = session.query(Keyring).filter_by(keyring_name=keyring).first()
900 obj = Keyring(keyring_name=keyring)
912 __all__.append('get_or_set_keyring')
914 ################################################################################
916 class Location(object):
917 def __init__(self, *args, **kwargs):
921 return '<Location %s (%s)>' % (self.path, self.location_id)
923 __all__.append('Location')
926 def get_location(location, component=None, archive=None, session=None):
928 Returns Location object for the given combination of location, component
931 @type location: string
932 @param location: the path of the location, e.g. I{/srv/ftp.debian.org/ftp/pool/}
934 @type component: string
935 @param component: the component name (if None, no restriction applied)
937 @type archive: string
938 @param archive_id: the archive name (if None, no restriction applied)
940 @rtype: Location / None
941 @return: Either a Location object or None if one can't be found
944 q = session.query(Location).filter_by(path=location)
946 if archive is not None:
947 q = q.join(Archive).filter_by(archive_name=archive)
949 if component is not None:
950 q = q.join(Component).filter_by(component_name=component)
954 except NoResultFound:
957 __all__.append('get_location')
959 ################################################################################
961 class Maintainer(object):
962 def __init__(self, *args, **kwargs):
966 return '''<Maintainer '%s' (%s)>''' % (self.name, self.maintainer_id)
968 def get_split_maintainer(self):
969 if not hasattr(self, 'name') or self.name is None:
970 return ('', '', '', '')
972 return fix_maintainer(self.name.strip())
974 __all__.append('Maintainer')
976 def get_or_set_maintainer(name, session=None):
978 Returns Maintainer object for given maintainer name.
980 If no matching maintainer name is found, a row is inserted.
983 @param name: The maintainer name to add
985 @type session: SQLAlchemy
986 @param session: Optional SQL session object (a temporary one will be
987 generated if not supplied). If not passed, a commit will be performed at
988 the end of the function, otherwise the caller is responsible for commiting.
989 A flush will be performed either way.
992 @return: the Maintainer object for the given maintainer
996 session = DBConn().session()
999 q = session.query(Maintainer).filter_by(name=name)
1002 except NoResultFound:
1003 maintainer = Maintainer()
1004 maintainer.name = name
1005 session.add(maintainer)
1017 __all__.append('get_or_set_maintainer')
1019 def get_maintainer(maintainer_id, session=None):
1021 Return the name of the maintainer behind C{maintainer_id} or None if that
1022 maintainer_id is invalid.
1024 @type maintainer_id: int
1025 @param maintainer_id: the id of the maintainer
1028 @return: the Maintainer with this C{maintainer_id}
1031 privatetrans = False
1033 session = DBConn().session()
1037 return session.query(Maintainer).get(maintainer_id)
1042 __all__.append('get_maintainer')
1044 ################################################################################
1046 class NewComment(object):
1047 def __init__(self, *args, **kwargs):
1051 return '''<NewComment for '%s %s' (%s)>''' % (self.package, self.version, self.comment_id)
1053 __all__.append('NewComment')
1056 def has_new_comment(package, version, session=None):
1058 Returns true if the given combination of C{package}, C{version} has a comment.
1060 @type package: string
1061 @param package: name of the package
1063 @type version: string
1064 @param version: package version
1066 @type session: Session
1067 @param session: Optional SQLA session object (a temporary one will be
1068 generated if not supplied)
1074 q = session.query(NewComment)
1075 q = q.filter_by(package=package)
1076 q = q.filter_by(version=version)
1078 return bool(q.count() > 0)
1080 __all__.append('has_new_comment')
1083 def get_new_comments(package=None, version=None, comment_id=None, session=None):
1085 Returns (possibly empty) list of NewComment objects for the given
1088 @type package: string (optional)
1089 @param package: name of the package
1091 @type version: string (optional)
1092 @param version: package version
1094 @type comment_id: int (optional)
1095 @param comment_id: An id of a comment
1097 @type session: Session
1098 @param session: Optional SQLA session object (a temporary one will be
1099 generated if not supplied)
1102 @return: A (possibly empty) list of NewComment objects will be returned
1105 q = session.query(NewComment)
1106 if package is not None: q = q.filter_by(package=package)
1107 if version is not None: q = q.filter_by(version=version)
1108 if comment_id is not None: q = q.filter_by(comment_id=comment_id)
1112 __all__.append('get_new_comments')
1114 ################################################################################
1116 class Override(object):
1117 def __init__(self, *args, **kwargs):
1121 return '<Override %s (%s)>' % (self.package, self.suite_id)
1123 __all__.append('Override')
1126 def get_override(package, suite=None, component=None, overridetype=None, session=None):
1128 Returns Override object for the given parameters
1130 @type package: string
1131 @param package: The name of the package
1133 @type suite: string, list or None
1134 @param suite: The name of the suite (or suites if a list) to limit to. If
1135 None, don't limit. Defaults to None.
1137 @type component: string, list or None
1138 @param component: The name of the component (or components if a list) to
1139 limit to. If None, don't limit. Defaults to None.
1141 @type overridetype: string, list or None
1142 @param overridetype: The name of the overridetype (or overridetypes if a list) to
1143 limit to. If None, don't limit. Defaults to None.
1145 @type session: Session
1146 @param session: Optional SQLA session object (a temporary one will be
1147 generated if not supplied)
1150 @return: A (possibly empty) list of Override objects will be returned
1153 q = session.query(Override)
1154 q = q.filter_by(package=package)
1156 if suite is not None:
1157 if not isinstance(suite, list): suite = [suite]
1158 q = q.join(Suite).filter(Suite.suite_name.in_(suite))
1160 if component is not None:
1161 if not isinstance(component, list): component = [component]
1162 q = q.join(Component).filter(Component.component_name.in_(component))
1164 if overridetype is not None:
1165 if not isinstance(overridetype, list): overridetype = [overridetype]
1166 q = q.join(OverrideType).filter(OverrideType.overridetype.in_(overridetype))
1170 __all__.append('get_override')
1173 ################################################################################
1175 class OverrideType(object):
1176 def __init__(self, *args, **kwargs):
1180 return '<OverrideType %s>' % self.overridetype
1182 __all__.append('OverrideType')
1185 def get_override_type(override_type, session=None):
1187 Returns OverrideType object for given C{override type}.
1189 @type override_type: string
1190 @param override_type: The name of the override type
1192 @type session: Session
1193 @param session: Optional SQLA session object (a temporary one will be
1194 generated if not supplied)
1197 @return: the database id for the given override type
1200 q = session.query(OverrideType).filter_by(overridetype=override_type)
1204 except NoResultFound:
1207 __all__.append('get_override_type')
1209 ################################################################################
1211 class PendingContentAssociation(object):
1212 def __init__(self, *args, **kwargs):
1216 return '<PendingContentAssociation %s>' % self.pca_id
1218 __all__.append('PendingContentAssociation')
1220 def insert_pending_content_paths(package, fullpaths, session=None):
1222 Make sure given paths are temporarily associated with given
1226 @param package: the package to associate with should have been read in from the binary control file
1227 @type fullpaths: list
1228 @param fullpaths: the list of paths of the file being associated with the binary
1229 @type session: SQLAlchemy session
1230 @param session: Optional SQLAlchemy session. If this is passed, the caller
1231 is responsible for ensuring a transaction has begun and committing the
1232 results or rolling back based on the result code. If not passed, a commit
1233 will be performed at the end of the function
1235 @return: True upon success, False if there is a problem
1238 privatetrans = False
1241 session = DBConn().session()
1245 arch = get_architecture(package['Architecture'], session)
1246 arch_id = arch.arch_id
1248 # Remove any already existing recorded files for this package
1249 q = session.query(PendingContentAssociation)
1250 q = q.filter_by(package=package['Package'])
1251 q = q.filter_by(version=package['Version'])
1252 q = q.filter_by(architecture=arch_id)
1257 for fullpath in fullpaths:
1258 (path, file) = os.path.split(fullpath)
1260 if path.startswith( "./" ):
1263 filepath_id = get_or_set_contents_path_id(path, session)
1264 filename_id = get_or_set_contents_file_id(file, session)
1266 pathcache[fullpath] = (filepath_id, filename_id)
1268 for fullpath, dat in pathcache.items():
1269 pca = PendingContentAssociation()
1270 pca.package = package['Package']
1271 pca.version = package['Version']
1272 pca.filepath_id = dat[0]
1273 pca.filename_id = dat[1]
1274 pca.architecture = arch_id
1277 # Only commit if we set up the session ourself
1285 except Exception, e:
1286 traceback.print_exc()
1288 # Only rollback if we set up the session ourself
1295 __all__.append('insert_pending_content_paths')
1297 ################################################################################
1299 class Priority(object):
1300 def __init__(self, *args, **kwargs):
1303 def __eq__(self, val):
1304 if isinstance(val, str):
1305 return (self.priority == val)
1306 # This signals to use the normal comparison operator
1307 return NotImplemented
1309 def __ne__(self, val):
1310 if isinstance(val, str):
1311 return (self.priority != val)
1312 # This signals to use the normal comparison operator
1313 return NotImplemented
1316 return '<Priority %s (%s)>' % (self.priority, self.priority_id)
1318 __all__.append('Priority')
1321 def get_priority(priority, session=None):
1323 Returns Priority object for given C{priority name}.
1325 @type priority: string
1326 @param priority: The name of the priority
1328 @type session: Session
1329 @param session: Optional SQLA session object (a temporary one will be
1330 generated if not supplied)
1333 @return: Priority object for the given priority
1336 q = session.query(Priority).filter_by(priority=priority)
1340 except NoResultFound:
1343 __all__.append('get_priority')
1346 def get_priorities(session=None):
1348 Returns dictionary of priority names -> id mappings
1350 @type session: Session
1351 @param session: Optional SQL session object (a temporary one will be
1352 generated if not supplied)
1355 @return: dictionary of priority names -> id mappings
1359 q = session.query(Priority)
1361 ret[x.priority] = x.priority_id
1365 __all__.append('get_priorities')
1367 ################################################################################
1369 class Queue(object):
1370 def __init__(self, *args, **kwargs):
1374 return '<Queue %s>' % self.queue_name
1376 def autobuild_upload(self, changes, srcpath, session=None):
1378 Update queue_build database table used for incoming autobuild support.
1380 @type changes: Changes
1381 @param changes: changes object for the upload to process
1383 @type srcpath: string
1384 @param srcpath: path for the queue file entries/link destinations
1386 @type session: SQLAlchemy session
1387 @param session: Optional SQLAlchemy session. If this is passed, the
1388 caller is responsible for ensuring a transaction has begun and
1389 committing the results or rolling back based on the result code. If
1390 not passed, a commit will be performed at the end of the function,
1391 otherwise the caller is responsible for commiting.
1393 @rtype: NoneType or string
1394 @return: None if the operation failed, a string describing the error if not
1397 privatetrans = False
1399 session = DBConn().session()
1402 # TODO: Remove by moving queue config into the database
1405 for suitename in changes.changes["distribution"].keys():
1406 # TODO: Move into database as:
1407 # buildqueuedir TEXT DEFAULT NULL (i.e. NULL is no build)
1408 # buildqueuecopy BOOLEAN NOT NULL DEFAULT FALSE (i.e. default is symlink)
1409 # This also gets rid of the SecurityQueueBuild hack below
1410 if suitename not in conf.ValueList("Dinstall::QueueBuildSuites"):
1414 s = get_suite(suitename, session)
1416 return "INTERNAL ERROR: Could not find suite %s" % suitename
1418 # TODO: Get from database as above
1419 dest_dir = conf["Dir::QueueBuild"]
1421 # TODO: Move into database as above
1422 if conf.FindB("Dinstall::SecurityQueueBuild"):
1423 dest_dir = os.path.join(dest_dir, suitename)
1425 for file_entry in changes.files.keys():
1426 src = os.path.join(srcpath, file_entry)
1427 dest = os.path.join(dest_dir, file_entry)
1429 # TODO: Move into database as above
1430 if conf.FindB("Dinstall::SecurityQueueBuild"):
1431 # Copy it since the original won't be readable by www-data
1433 utils.copy(src, dest)
1435 # Create a symlink to it
1436 os.symlink(src, dest)
1439 qb.suite_id = s.suite_id
1440 qb.queue_id = self.queue_id
1446 # If the .orig.tar.gz is in the pool, create a symlink to
1447 # it (if one doesn't already exist)
1448 if changes.orig_tar_id:
1449 # Determine the .orig.tar.gz file name
1450 for dsc_file in changes.dsc_files.keys():
1451 if dsc_file.endswith(".orig.tar.gz"):
1454 dest = os.path.join(dest_dir, filename)
1456 # If it doesn't exist, create a symlink
1457 if not os.path.exists(dest):
1458 q = session.execute("SELECT l.path, f.filename FROM location l, files f WHERE f.id = :id and f.location = l.id",
1459 {'id': changes.orig_tar_id})
1462 return "[INTERNAL ERROR] Couldn't find id %s in files table." % (changes.orig_tar_id)
1464 src = os.path.join(res[0], res[1])
1465 os.symlink(src, dest)
1467 # Add it to the list of packages for later processing by apt-ftparchive
1469 qb.suite_id = s.suite_id
1470 qb.queue_id = self.queue_id
1475 # If it does, update things to ensure it's not removed prematurely
1477 qb = get_queue_build(dest, s.suite_id, session)
1489 __all__.append('Queue')
1492 def get_queue(queuename, session=None):
1494 Returns Queue object for given C{queue name}.
1496 @type queuename: string
1497 @param queuename: The name of the queue
1499 @type session: Session
1500 @param session: Optional SQLA session object (a temporary one will be
1501 generated if not supplied)
1504 @return: Queue object for the given queue
1507 q = session.query(Queue).filter_by(queue_name=queuename)
1511 except NoResultFound:
1514 __all__.append('get_queue')
1516 ################################################################################
1518 class QueueBuild(object):
1519 def __init__(self, *args, **kwargs):
1523 return '<QueueBuild %s (%s)>' % (self.filename, self.queue_id)
1525 __all__.append('QueueBuild')
1528 def get_queue_build(filename, suite, session=None):
1530 Returns QueueBuild object for given C{filename} and C{suite}.
1532 @type filename: string
1533 @param filename: The name of the file
1535 @type suiteid: int or str
1536 @param suiteid: Suite name or ID
1538 @type session: Session
1539 @param session: Optional SQLA session object (a temporary one will be
1540 generated if not supplied)
1543 @return: Queue object for the given queue
1546 if isinstance(suite, int):
1547 q = session.query(QueueBuild).filter_by(filename=filename).filter_by(suite_id=suite)
1549 q = session.query(QueueBuild).filter_by(filename=filename)
1550 q = q.join(Suite).filter_by(suite_name=suite)
1554 except NoResultFound:
1557 __all__.append('get_queue_build')
1559 ################################################################################
1561 class Section(object):
1562 def __init__(self, *args, **kwargs):
1565 def __eq__(self, val):
1566 if isinstance(val, str):
1567 return (self.section == val)
1568 # This signals to use the normal comparison operator
1569 return NotImplemented
1571 def __ne__(self, val):
1572 if isinstance(val, str):
1573 return (self.section != val)
1574 # This signals to use the normal comparison operator
1575 return NotImplemented
1578 return '<Section %s>' % self.section
1580 __all__.append('Section')
1583 def get_section(section, session=None):
1585 Returns Section object for given C{section name}.
1587 @type section: string
1588 @param section: The name of the section
1590 @type session: Session
1591 @param session: Optional SQLA session object (a temporary one will be
1592 generated if not supplied)
1595 @return: Section object for the given section name
1598 q = session.query(Section).filter_by(section=section)
1602 except NoResultFound:
1605 __all__.append('get_section')
1608 def get_sections(session=None):
1610 Returns dictionary of section names -> id mappings
1612 @type session: Session
1613 @param session: Optional SQL session object (a temporary one will be
1614 generated if not supplied)
1617 @return: dictionary of section names -> id mappings
1621 q = session.query(Section)
1623 ret[x.section] = x.section_id
1627 __all__.append('get_sections')
1629 ################################################################################
1631 class DBSource(object):
1632 def __init__(self, *args, **kwargs):
1636 return '<DBSource %s (%s)>' % (self.source, self.version)
1638 __all__.append('DBSource')
1641 def source_exists(source, source_version, suites = ["any"], session=None):
1643 Ensure that source exists somewhere in the archive for the binary
1644 upload being processed.
1645 1. exact match => 1.0-3
1646 2. bin-only NMU => 1.0-3+b1 , 1.0-3.1+b1
1648 @type package: string
1649 @param package: package source name
1651 @type source_version: string
1652 @param source_version: expected source version
1655 @param suites: list of suites to check in, default I{any}
1657 @type session: Session
1658 @param session: Optional SQLA session object (a temporary one will be
1659 generated if not supplied)
1662 @return: returns 1 if a source with expected version is found, otherwise 0
1669 for suite in suites:
1670 q = session.query(DBSource).filter_by(source=source)
1672 # source must exist in suite X, or in some other suite that's
1673 # mapped to X, recursively... silent-maps are counted too,
1674 # unreleased-maps aren't.
1675 maps = cnf.ValueList("SuiteMappings")[:]
1677 maps = [ m.split() for m in maps ]
1678 maps = [ (x[1], x[2]) for x in maps
1679 if x[0] == "map" or x[0] == "silent-map" ]
1682 if x[1] in s and x[0] not in s:
1685 q = q.join(SrcAssociation).join(Suite)
1686 q = q.filter(Suite.suite_name.in_(s))
1688 # Reduce the query results to a list of version numbers
1689 ql = [ j.version for j in q.all() ]
1692 if source_version in ql:
1696 from daklib.regexes import re_bin_only_nmu
1697 orig_source_version = re_bin_only_nmu.sub('', source_version)
1698 if orig_source_version in ql:
1701 # No source found so return not ok
1706 __all__.append('source_exists')
1709 def get_suites_source_in(source, session=None):
1711 Returns list of Suite objects which given C{source} name is in
1714 @param source: DBSource package name to search for
1717 @return: list of Suite objects for the given source
1720 return session.query(Suite).join(SrcAssociation).join(DBSource).filter_by(source=source).all()
1722 __all__.append('get_suites_source_in')
1725 def get_sources_from_name(source, version=None, dm_upload_allowed=None, session=None):
1727 Returns list of DBSource objects for given C{source} name and other parameters
1730 @param source: DBSource package name to search for
1732 @type source: str or None
1733 @param source: DBSource version name to search for or None if not applicable
1735 @type dm_upload_allowed: bool
1736 @param dm_upload_allowed: If None, no effect. If True or False, only
1737 return packages with that dm_upload_allowed setting
1739 @type session: Session
1740 @param session: Optional SQL session object (a temporary one will be
1741 generated if not supplied)
1744 @return: list of DBSource objects for the given name (may be empty)
1747 q = session.query(DBSource).filter_by(source=source)
1749 if version is not None:
1750 q = q.filter_by(version=version)
1752 if dm_upload_allowed is not None:
1753 q = q.filter_by(dm_upload_allowed=dm_upload_allowed)
1757 __all__.append('get_sources_from_name')
1760 def get_source_in_suite(source, suite, session=None):
1762 Returns list of DBSource objects for a combination of C{source} and C{suite}.
1764 - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
1765 - B{suite} - a suite name, eg. I{unstable}
1767 @type source: string
1768 @param source: source package name
1771 @param suite: the suite name
1774 @return: the version for I{source} in I{suite}
1778 q = session.query(SrcAssociation)
1779 q = q.join('source').filter_by(source=source)
1780 q = q.join('suite').filter_by(suite_name=suite)
1783 return q.one().source
1784 except NoResultFound:
1787 __all__.append('get_source_in_suite')
1789 ################################################################################
1791 class SrcAssociation(object):
1792 def __init__(self, *args, **kwargs):
1796 return '<SrcAssociation %s (%s, %s)>' % (self.sa_id, self.source, self.suite)
1798 __all__.append('SrcAssociation')
1800 ################################################################################
1802 class SrcUploader(object):
1803 def __init__(self, *args, **kwargs):
1807 return '<SrcUploader %s>' % self.uploader_id
1809 __all__.append('SrcUploader')
1811 ################################################################################
1813 SUITE_FIELDS = [ ('SuiteName', 'suite_name'),
1814 ('SuiteID', 'suite_id'),
1815 ('Version', 'version'),
1816 ('Origin', 'origin'),
1818 ('Description', 'description'),
1819 ('Untouchable', 'untouchable'),
1820 ('Announce', 'announce'),
1821 ('Codename', 'codename'),
1822 ('OverrideCodename', 'overridecodename'),
1823 ('ValidTime', 'validtime'),
1824 ('Priority', 'priority'),
1825 ('NotAutomatic', 'notautomatic'),
1826 ('CopyChanges', 'copychanges'),
1827 ('CopyDotDak', 'copydotdak'),
1828 ('CommentsDir', 'commentsdir'),
1829 ('OverrideSuite', 'overridesuite'),
1830 ('ChangelogBase', 'changelogbase')]
1833 class Suite(object):
1834 def __init__(self, *args, **kwargs):
1838 return '<Suite %s>' % self.suite_name
1840 def __eq__(self, val):
1841 if isinstance(val, str):
1842 return (self.suite_name == val)
1843 # This signals to use the normal comparison operator
1844 return NotImplemented
1846 def __ne__(self, val):
1847 if isinstance(val, str):
1848 return (self.suite_name != val)
1849 # This signals to use the normal comparison operator
1850 return NotImplemented
1854 for disp, field in SUITE_FIELDS:
1855 val = getattr(self, field, None)
1857 ret.append("%s: %s" % (disp, val))
1859 return "\n".join(ret)
1861 __all__.append('Suite')
1864 def get_suite_architecture(suite, architecture, session=None):
1866 Returns a SuiteArchitecture object given C{suite} and ${arch} or None if it
1870 @param suite: Suite name to search for
1872 @type architecture: str
1873 @param architecture: Architecture name to search for
1875 @type session: Session
1876 @param session: Optional SQL session object (a temporary one will be
1877 generated if not supplied)
1879 @rtype: SuiteArchitecture
1880 @return: the SuiteArchitecture object or None
1883 q = session.query(SuiteArchitecture)
1884 q = q.join(Architecture).filter_by(arch_string=architecture)
1885 q = q.join(Suite).filter_by(suite_name=suite)
1889 except NoResultFound:
1892 __all__.append('get_suite_architecture')
1895 def get_suite(suite, session=None):
1897 Returns Suite object for given C{suite name}.
1900 @param suite: The name of the suite
1902 @type session: Session
1903 @param session: Optional SQLA session object (a temporary one will be
1904 generated if not supplied)
1907 @return: Suite object for the requested suite name (None if not presenT)
1910 q = session.query(Suite).filter_by(suite_name=suite)
1914 except NoResultFound:
1917 __all__.append('get_suite')
1919 ################################################################################
1921 class SuiteArchitecture(object):
1922 def __init__(self, *args, **kwargs):
1926 return '<SuiteArchitecture (%s, %s)>' % (self.suite_id, self.arch_id)
1928 __all__.append('SuiteArchitecture')
1931 def get_suite_architectures(suite, skipsrc=False, skipall=False, session=None):
1933 Returns list of Architecture objects for given C{suite} name
1936 @param source: Suite name to search for
1938 @type skipsrc: boolean
1939 @param skipsrc: Whether to skip returning the 'source' architecture entry
1942 @type skipall: boolean
1943 @param skipall: Whether to skip returning the 'all' architecture entry
1946 @type session: Session
1947 @param session: Optional SQL session object (a temporary one will be
1948 generated if not supplied)
1951 @return: list of Architecture objects for the given name (may be empty)
1954 q = session.query(Architecture)
1955 q = q.join(SuiteArchitecture)
1956 q = q.join(Suite).filter_by(suite_name=suite)
1959 q = q.filter(Architecture.arch_string != 'source')
1962 q = q.filter(Architecture.arch_string != 'all')
1964 q = q.order_by('arch_string')
1968 __all__.append('get_suite_architectures')
1970 ################################################################################
1973 def __init__(self, *args, **kwargs):
1976 def __eq__(self, val):
1977 if isinstance(val, str):
1978 return (self.uid == val)
1979 # This signals to use the normal comparison operator
1980 return NotImplemented
1982 def __ne__(self, val):
1983 if isinstance(val, str):
1984 return (self.uid != val)
1985 # This signals to use the normal comparison operator
1986 return NotImplemented
1989 return '<Uid %s (%s)>' % (self.uid, self.name)
1991 __all__.append('Uid')
1993 def add_database_user(uidname, session=None):
1995 Adds a database user
1997 @type uidname: string
1998 @param uidname: The uid of the user to add
2000 @type session: SQLAlchemy
2001 @param session: Optional SQL session object (a temporary one will be
2002 generated if not supplied). If not passed, a commit will be performed at
2003 the end of the function, otherwise the caller is responsible for commiting.
2006 @return: the uid object for the given uidname
2009 privatetrans = False
2011 session = DBConn().session()
2014 session.execute("CREATE USER :uid", {'uid': uidname})
2020 __all__.append('add_database_user')
2022 def get_or_set_uid(uidname, session=None):
2024 Returns uid object for given uidname.
2026 If no matching uidname is found, a row is inserted.
2028 @type uidname: string
2029 @param uidname: The uid to add
2031 @type session: SQLAlchemy
2032 @param session: Optional SQL session object (a temporary one will be
2033 generated if not supplied). If not passed, a commit will be performed at
2034 the end of the function, otherwise the caller is responsible for commiting.
2037 @return: the uid object for the given uidname
2040 privatetrans = False
2042 session = DBConn().session()
2045 q = session.query(Uid).filter_by(uid=uidname)
2049 except NoResultFound:
2064 __all__.append('get_or_set_uid')
2067 def get_uid_from_fingerprint(fpr, session=None):
2068 q = session.query(Uid)
2069 q = q.join(Fingerprint).filter_by(fingerprint=fpr)
2073 except NoResultFound:
2076 __all__.append('get_uid_from_fingerprint')
2078 ################################################################################
2080 class DBConn(Singleton):
2082 database module init.
2084 def __init__(self, *args, **kwargs):
2085 super(DBConn, self).__init__(*args, **kwargs)
2087 def _startup(self, *args, **kwargs):
2089 if kwargs.has_key('debug'):
2093 def __setuptables(self):
2094 self.tbl_architecture = Table('architecture', self.db_meta, autoload=True)
2095 self.tbl_archive = Table('archive', self.db_meta, autoload=True)
2096 self.tbl_bin_associations = Table('bin_associations', self.db_meta, autoload=True)
2097 self.tbl_binaries = Table('binaries', self.db_meta, autoload=True)
2098 self.tbl_component = Table('component', self.db_meta, autoload=True)
2099 self.tbl_config = Table('config', self.db_meta, autoload=True)
2100 self.tbl_content_associations = Table('content_associations', self.db_meta, autoload=True)
2101 self.tbl_content_file_names = Table('content_file_names', self.db_meta, autoload=True)
2102 self.tbl_content_file_paths = Table('content_file_paths', self.db_meta, autoload=True)
2103 self.tbl_dsc_files = Table('dsc_files', self.db_meta, autoload=True)
2104 self.tbl_files = Table('files', self.db_meta, autoload=True)
2105 self.tbl_fingerprint = Table('fingerprint', self.db_meta, autoload=True)
2106 self.tbl_keyrings = Table('keyrings', self.db_meta, autoload=True)
2107 self.tbl_location = Table('location', self.db_meta, autoload=True)
2108 self.tbl_maintainer = Table('maintainer', self.db_meta, autoload=True)
2109 self.tbl_new_comments = Table('new_comments', self.db_meta, autoload=True)
2110 self.tbl_override = Table('override', self.db_meta, autoload=True)
2111 self.tbl_override_type = Table('override_type', self.db_meta, autoload=True)
2112 self.tbl_pending_content_associations = Table('pending_content_associations', self.db_meta, autoload=True)
2113 self.tbl_priority = Table('priority', self.db_meta, autoload=True)
2114 self.tbl_queue = Table('queue', self.db_meta, autoload=True)
2115 self.tbl_queue_build = Table('queue_build', self.db_meta, autoload=True)
2116 self.tbl_section = Table('section', self.db_meta, autoload=True)
2117 self.tbl_source = Table('source', self.db_meta, autoload=True)
2118 self.tbl_src_associations = Table('src_associations', self.db_meta, autoload=True)
2119 self.tbl_src_uploaders = Table('src_uploaders', self.db_meta, autoload=True)
2120 self.tbl_suite = Table('suite', self.db_meta, autoload=True)
2121 self.tbl_suite_architectures = Table('suite_architectures', self.db_meta, autoload=True)
2122 self.tbl_uid = Table('uid', self.db_meta, autoload=True)
2124 def __setupmappers(self):
2125 mapper(Architecture, self.tbl_architecture,
2126 properties = dict(arch_id = self.tbl_architecture.c.id))
2128 mapper(Archive, self.tbl_archive,
2129 properties = dict(archive_id = self.tbl_archive.c.id,
2130 archive_name = self.tbl_archive.c.name))
2132 mapper(BinAssociation, self.tbl_bin_associations,
2133 properties = dict(ba_id = self.tbl_bin_associations.c.id,
2134 suite_id = self.tbl_bin_associations.c.suite,
2135 suite = relation(Suite),
2136 binary_id = self.tbl_bin_associations.c.bin,
2137 binary = relation(DBBinary)))
2139 mapper(DBBinary, self.tbl_binaries,
2140 properties = dict(binary_id = self.tbl_binaries.c.id,
2141 package = self.tbl_binaries.c.package,
2142 version = self.tbl_binaries.c.version,
2143 maintainer_id = self.tbl_binaries.c.maintainer,
2144 maintainer = relation(Maintainer),
2145 source_id = self.tbl_binaries.c.source,
2146 source = relation(DBSource),
2147 arch_id = self.tbl_binaries.c.architecture,
2148 architecture = relation(Architecture),
2149 poolfile_id = self.tbl_binaries.c.file,
2150 poolfile = relation(PoolFile),
2151 binarytype = self.tbl_binaries.c.type,
2152 fingerprint_id = self.tbl_binaries.c.sig_fpr,
2153 fingerprint = relation(Fingerprint),
2154 install_date = self.tbl_binaries.c.install_date,
2155 binassociations = relation(BinAssociation,
2156 primaryjoin=(self.tbl_binaries.c.id==self.tbl_bin_associations.c.bin))))
2158 mapper(Component, self.tbl_component,
2159 properties = dict(component_id = self.tbl_component.c.id,
2160 component_name = self.tbl_component.c.name))
2162 mapper(DBConfig, self.tbl_config,
2163 properties = dict(config_id = self.tbl_config.c.id))
2165 mapper(ContentAssociation, self.tbl_content_associations,
2166 properties = dict(ca_id = self.tbl_content_associations.c.id,
2167 filename_id = self.tbl_content_associations.c.filename,
2168 filename = relation(ContentFilename),
2169 filepath_id = self.tbl_content_associations.c.filepath,
2170 filepath = relation(ContentFilepath),
2171 binary_id = self.tbl_content_associations.c.binary_pkg,
2172 binary = relation(DBBinary)))
2175 mapper(ContentFilename, self.tbl_content_file_names,
2176 properties = dict(cafilename_id = self.tbl_content_file_names.c.id,
2177 filename = self.tbl_content_file_names.c.file))
2179 mapper(ContentFilepath, self.tbl_content_file_paths,
2180 properties = dict(cafilepath_id = self.tbl_content_file_paths.c.id,
2181 filepath = self.tbl_content_file_paths.c.path))
2183 mapper(DSCFile, self.tbl_dsc_files,
2184 properties = dict(dscfile_id = self.tbl_dsc_files.c.id,
2185 source_id = self.tbl_dsc_files.c.source,
2186 source = relation(DBSource),
2187 poolfile_id = self.tbl_dsc_files.c.file,
2188 poolfile = relation(PoolFile)))
2190 mapper(PoolFile, self.tbl_files,
2191 properties = dict(file_id = self.tbl_files.c.id,
2192 filesize = self.tbl_files.c.size,
2193 location_id = self.tbl_files.c.location,
2194 location = relation(Location)))
2196 mapper(Fingerprint, self.tbl_fingerprint,
2197 properties = dict(fingerprint_id = self.tbl_fingerprint.c.id,
2198 uid_id = self.tbl_fingerprint.c.uid,
2199 uid = relation(Uid),
2200 keyring_id = self.tbl_fingerprint.c.keyring,
2201 keyring = relation(Keyring)))
2203 mapper(Keyring, self.tbl_keyrings,
2204 properties = dict(keyring_name = self.tbl_keyrings.c.name,
2205 keyring_id = self.tbl_keyrings.c.id))
2207 mapper(Location, self.tbl_location,
2208 properties = dict(location_id = self.tbl_location.c.id,
2209 component_id = self.tbl_location.c.component,
2210 component = relation(Component),
2211 archive_id = self.tbl_location.c.archive,
2212 archive = relation(Archive),
2213 archive_type = self.tbl_location.c.type))
2215 mapper(Maintainer, self.tbl_maintainer,
2216 properties = dict(maintainer_id = self.tbl_maintainer.c.id))
2218 mapper(NewComment, self.tbl_new_comments,
2219 properties = dict(comment_id = self.tbl_new_comments.c.id))
2221 mapper(Override, self.tbl_override,
2222 properties = dict(suite_id = self.tbl_override.c.suite,
2223 suite = relation(Suite),
2224 component_id = self.tbl_override.c.component,
2225 component = relation(Component),
2226 priority_id = self.tbl_override.c.priority,
2227 priority = relation(Priority),
2228 section_id = self.tbl_override.c.section,
2229 section = relation(Section),
2230 overridetype_id = self.tbl_override.c.type,
2231 overridetype = relation(OverrideType)))
2233 mapper(OverrideType, self.tbl_override_type,
2234 properties = dict(overridetype = self.tbl_override_type.c.type,
2235 overridetype_id = self.tbl_override_type.c.id))
2237 mapper(PendingContentAssociation, self.tbl_pending_content_associations,
2238 properties = dict(pca_id = self.tbl_pending_content_associations.c.id,
2239 filepath_id = self.tbl_pending_content_associations.c.filepath,
2240 filepath = relation(ContentFilepath),
2241 filename_id = self.tbl_pending_content_associations.c.filename,
2242 filename = relation(ContentFilename)))
2244 mapper(Priority, self.tbl_priority,
2245 properties = dict(priority_id = self.tbl_priority.c.id))
2247 mapper(Queue, self.tbl_queue,
2248 properties = dict(queue_id = self.tbl_queue.c.id))
2250 mapper(QueueBuild, self.tbl_queue_build,
2251 properties = dict(suite_id = self.tbl_queue_build.c.suite,
2252 queue_id = self.tbl_queue_build.c.queue,
2253 queue = relation(Queue, backref='queuebuild')))
2255 mapper(Section, self.tbl_section,
2256 properties = dict(section_id = self.tbl_section.c.id))
2258 mapper(DBSource, self.tbl_source,
2259 properties = dict(source_id = self.tbl_source.c.id,
2260 version = self.tbl_source.c.version,
2261 maintainer_id = self.tbl_source.c.maintainer,
2262 maintainer = relation(Maintainer,
2263 primaryjoin=(self.tbl_source.c.maintainer==self.tbl_maintainer.c.id)),
2264 poolfile_id = self.tbl_source.c.file,
2265 poolfile = relation(PoolFile),
2266 fingerprint_id = self.tbl_source.c.sig_fpr,
2267 fingerprint = relation(Fingerprint),
2268 changedby_id = self.tbl_source.c.changedby,
2269 changedby = relation(Maintainer,
2270 primaryjoin=(self.tbl_source.c.changedby==self.tbl_maintainer.c.id)),
2271 srcfiles = relation(DSCFile,
2272 primaryjoin=(self.tbl_source.c.id==self.tbl_dsc_files.c.source)),
2273 srcassociations = relation(SrcAssociation,
2274 primaryjoin=(self.tbl_source.c.id==self.tbl_src_associations.c.source))))
2276 mapper(SrcAssociation, self.tbl_src_associations,
2277 properties = dict(sa_id = self.tbl_src_associations.c.id,
2278 suite_id = self.tbl_src_associations.c.suite,
2279 suite = relation(Suite),
2280 source_id = self.tbl_src_associations.c.source,
2281 source = relation(DBSource)))
2283 mapper(SrcUploader, self.tbl_src_uploaders,
2284 properties = dict(uploader_id = self.tbl_src_uploaders.c.id,
2285 source_id = self.tbl_src_uploaders.c.source,
2286 source = relation(DBSource,
2287 primaryjoin=(self.tbl_src_uploaders.c.source==self.tbl_source.c.id)),
2288 maintainer_id = self.tbl_src_uploaders.c.maintainer,
2289 maintainer = relation(Maintainer,
2290 primaryjoin=(self.tbl_src_uploaders.c.maintainer==self.tbl_maintainer.c.id))))
2292 mapper(Suite, self.tbl_suite,
2293 properties = dict(suite_id = self.tbl_suite.c.id))
2295 mapper(SuiteArchitecture, self.tbl_suite_architectures,
2296 properties = dict(suite_id = self.tbl_suite_architectures.c.suite,
2297 suite = relation(Suite, backref='suitearchitectures'),
2298 arch_id = self.tbl_suite_architectures.c.architecture,
2299 architecture = relation(Architecture)))
2301 mapper(Uid, self.tbl_uid,
2302 properties = dict(uid_id = self.tbl_uid.c.id,
2303 fingerprint = relation(Fingerprint)))
2305 ## Connection functions
2306 def __createconn(self):
2307 from config import Config
2311 connstr = "postgres://%s" % cnf["DB::Host"]
2312 if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
2313 connstr += ":%s" % cnf["DB::Port"]
2314 connstr += "/%s" % cnf["DB::Name"]
2317 connstr = "postgres:///%s" % cnf["DB::Name"]
2318 if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
2319 connstr += "?port=%s" % cnf["DB::Port"]
2321 self.db_pg = create_engine(connstr, echo=self.debug)
2322 self.db_meta = MetaData()
2323 self.db_meta.bind = self.db_pg
2324 self.db_smaker = sessionmaker(bind=self.db_pg,
2328 self.__setuptables()
2329 self.__setupmappers()
2332 return self.db_smaker()
2334 __all__.append('DBConn')