dbconn.py 118.6 KB
Newer Older
1
#!/usr/bin/python
M
Mark Hymers 已提交
2

3 4 5 6 7
""" DB access class

@contact: Debian FTPMaster <ftpmaster@debian.org>
@copyright: 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
@copyright: 2008-2009  Mark Hymers <mhy@debian.org>
J
Joerg Jaspert 已提交
8
@copyright: 2009, 2010  Joerg Jaspert <joerg@debian.org>
9
@copyright: 2009  Mike O'Connor <stew@debian.org>
10 11
@license: GNU General Public License version 2 or later
"""
M
Mark Hymers 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

################################################################################

# < mhy> I need a funny comment
# < sgran> two peanuts were walking down a dark street
# < sgran> one was a-salted
#  * mhy looks up the definition of "funny"

################################################################################

36
import os
37
from os.path import normpath
M
Mark Hymers 已提交
38
import re
M
Mark Hymers 已提交
39
import psycopg2
40
import traceback
J
Joerg Jaspert 已提交
41
import commands
42
import signal
T
Torsten Werner 已提交
43 44 45 46 47 48 49 50

try:
    # python >= 2.6
    import json
except:
    # python <= 2.5
    import simplejson as json

M
Mark Hymers 已提交
51 52 53
from datetime import datetime, timedelta
from errno import ENOENT
from tempfile import mkstemp, mkdtemp
54 55
from subprocess import Popen, PIPE
from tarfile import TarFile
M
Mark Hymers 已提交
56

57 58
from inspect import getargspec

59
import sqlalchemy
60 61
from sqlalchemy import create_engine, Table, MetaData, Column, Integer, desc, \
    Text, ForeignKey
62
from sqlalchemy.orm import sessionmaker, mapper, relation, object_session, \
63
    backref, MapperExtension, EXT_CONTINUE, object_mapper, clear_mappers
64
from sqlalchemy import types as sqltypes
65 66
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
M
Mark Hymers 已提交
67

M
Mark Hymers 已提交
68 69
# Don't remove this, we re-export the exceptions to scripts which import us
from sqlalchemy.exc import *
70
from sqlalchemy.orm.exc import NoResultFound
M
Mark Hymers 已提交
71

72 73 74
# Only import Config until Queue stuff is changed to store its config
# in the database
from config import Config
M
Mark Hymers 已提交
75
from textutils import fix_maintainer
76
from dak_exceptions import DBUpdateError, NoSourceFieldError
M
Mark Hymers 已提交
77

78 79 80 81 82 83 84
# suppress some deprecation warnings in squeeze related to sqlalchemy
import warnings
warnings.filterwarnings('ignore', \
    "The SQLAlchemy PostgreSQL dialect has been renamed from 'postgres' to 'postgresql'.*", \
    SADeprecationWarning)


M
Mark Hymers 已提交
85 86
################################################################################

87 88 89
# Patch in support for the debversion field type so that it works during
# reflection

T
Torsten Werner 已提交
90 91 92 93 94 95 96 97
try:
    # that is for sqlalchemy 0.6
    UserDefinedType = sqltypes.UserDefinedType
except:
    # this one for sqlalchemy 0.5
    UserDefinedType = sqltypes.TypeEngine

class DebVersion(UserDefinedType):
98 99 100
    def get_col_spec(self):
        return "DEBVERSION"

101 102 103
    def bind_processor(self, dialect):
        return None

T
Torsten Werner 已提交
104 105
    # ' = None' is needed for sqlalchemy 0.5:
    def result_processor(self, dialect, coltype = None):
106 107
        return None

108
sa_major_version = sqlalchemy.__version__[0:3]
M
Mark Hymers 已提交
109
if sa_major_version in ["0.5", "0.6"]:
C
Chris Lamb 已提交
110 111
    from sqlalchemy.databases import postgres
    postgres.ischema_names['debversion'] = DebVersion
112
else:
M
Mark Hymers 已提交
113
    raise Exception("dak only ported to SQLA versions 0.5 and 0.6.  See daklib/dbconn.py")
114 115 116

################################################################################

117
__all__ = ['IntegrityError', 'SQLAlchemyError', 'DebVersion']
118 119 120

################################################################################

121
def session_wrapper(fn):
C
Chris Lamb 已提交
122 123 124 125
    """
    Wrapper around common ".., session=None):" handling. If the wrapped
    function is called without passing 'session', we create a local one
    and destroy it when the function ends.
126 127 128 129

    Also attaches a commit_or_flush method to the session; if we created a
    local session, this is a synonym for session.commit(), otherwise it is a
    synonym for session.flush().
C
Chris Lamb 已提交
130 131
    """

132 133 134
    def wrapped(*args, **kwargs):
        private_transaction = False

135
        # Find the session object
C
Chris Lamb 已提交
136 137 138
        session = kwargs.get('session')

        if session is None:
139 140 141 142 143 144 145
            if len(args) <= len(getargspec(fn)[0]) - 1:
                # No session specified as last argument or in kwargs
                private_transaction = True
                session = kwargs['session'] = DBConn().session()
            else:
                # Session is last argument in args
                session = args[-1]
146
                if session is None:
M
fixup  
Mark Hymers 已提交
147
                    args = list(args)
148 149
                    session = args[-1] = DBConn().session()
                    private_transaction = True
150 151 152 153 154

        if private_transaction:
            session.commit_or_flush = session.commit
        else:
            session.commit_or_flush = session.flush
155 156 157 158 159 160

        try:
            return fn(*args, **kwargs)
        finally:
            if private_transaction:
                # We created a session; close it.
161
                session.close()
162

163 164 165
    wrapped.__doc__ = fn.__doc__
    wrapped.func_name = fn.func_name

166 167
    return wrapped

F
Frank Lichtenheld 已提交
168 169
__all__.append('session_wrapper')

170 171
################################################################################

172 173 174
class ORMObject(object):
    """
    ORMObject is a base class for all ORM classes mapped by SQLalchemy. All
T
Torsten Werner 已提交
175
    derived classes must implement the properties() method.
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    """

    def properties(self):
        '''
        This method should be implemented by all derived classes and returns a
        list of the important properties. The properties 'created' and
        'modified' will be added automatically. A suffix '_count' should be
        added to properties that are lists or query objects. The most important
        property name should be returned as the first element in the list
        because it is used by repr().
        '''
        return []

    def json(self):
        '''
        Returns a JSON representation of the object based on the properties
        returned from the properties() method.
        '''
        data = {}
        # add created and modified
        all_properties = self.properties() + ['created', 'modified']
        for property in all_properties:
            # check for list or query
            if property[-6:] == '_count':
200 201 202 203
                real_property = property[:-6]
                if not hasattr(self, real_property):
                    continue
                value = getattr(self, real_property)
204 205 206 207
                if hasattr(value, '__len__'):
                    # list
                    value = len(value)
                elif hasattr(value, 'count'):
208 209 210
                    # query (but not during validation)
                    if self.in_validation:
                        continue
211 212 213 214
                    value = value.count()
                else:
                    raise KeyError('Do not understand property %s.' % property)
            else:
215 216
                if not hasattr(self, property):
                    continue
217 218 219 220
                # plain object
                value = getattr(self, property)
                if value is None:
                    # skip None
221
                    continue
222 223 224 225 226
                elif isinstance(value, ORMObject):
                    # use repr() for ORMObject types
                    value = repr(value)
                else:
                    # we want a string for all other types because json cannot
T
Torsten Werner 已提交
227
                    # encode everything
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
                    value = str(value)
            data[property] = value
        return json.dumps(data)

    def classname(self):
        '''
        Returns the name of the class.
        '''
        return type(self).__name__

    def __repr__(self):
        '''
        Returns a short string representation of the object using the first
        element from the properties() method.
        '''
        primary_property = self.properties()[0]
        value = getattr(self, primary_property)
        return '<%s %s>' % (self.classname(), str(value))

    def __str__(self):
        '''
        Returns a human readable form of the object using the properties()
        method.
        '''
        return '<%s %s>' % (self.classname(), self.json())

254 255 256 257 258 259 260 261 262 263
    def not_null_constraints(self):
        '''
        Returns a list of properties that must be not NULL. Derived classes
        should override this method if needed.
        '''
        return []

    validation_message = \
        "Validation failed because property '%s' must not be empty in object\n%s"

264 265
    in_validation = False

266 267
    def validate(self):
        '''
268 269 270
        This function validates the not NULL constraints as returned by
        not_null_constraints(). It raises the DBUpdateError exception if
        validation fails.
271
        '''
272
        for property in self.not_null_constraints():
273 274 275 276 277 278
            # TODO: It is a bit awkward that the mapper configuration allow
            # directly setting the numeric _id columns. We should get rid of it
            # in the long run.
            if hasattr(self, property + '_id') and \
                getattr(self, property + '_id') is not None:
                continue
279
            if not hasattr(self, property) or getattr(self, property) is None:
280 281 282 283 284
                # str() might lead to races due to a 2nd flush
                self.in_validation = True
                message = self.validation_message % (property, str(self))
                self.in_validation = False
                raise DBUpdateError(message)
285

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    @classmethod
    @session_wrapper
    def get(cls, primary_key,  session = None):
        '''
        This is a support function that allows getting an object by its primary
        key.

        Architecture.get(3[, session])

        instead of the more verbose

        session.query(Architecture).get(3)
        '''
        return session.query(cls).get(primary_key)

301 302 303 304 305 306 307 308 309 310 311 312
    def session(self, replace = False):
        '''
        Returns the current session that is associated with the object. May
        return None is object is in detached state.
        '''

        return object_session(self)

    def clone(self, session = None):
        '''
        Clones the current object in a new session and returns the new clone. A
        fresh session is created if the optional session parameter is not
313 314
        provided. The function will fail if a session is provided and has
        unflushed changes.
315

316 317 318
        RATIONALE: SQLAlchemy's session is not thread safe. This method clones
        an existing object to allow several threads to work with their own
        instances of an ORMObject.
319

320 321 322 323
        WARNING: Only persistent (committed) objects can be cloned. Changes
        made to the original object that are not committed yet will get lost.
        The session of the new object will always be rolled back to avoid
        ressource leaks.
324 325 326
        '''

        if self.session() is None:
327 328
            raise RuntimeError( \
                'Method clone() failed for detached object:\n%s' % self)
329 330 331 332
        self.session().flush()
        mapper = object_mapper(self)
        primary_key = mapper.primary_key_from_instance(self)
        object_class = self.__class__
333 334 335 336 337
        if session is None:
            session = DBConn().session()
        elif len(session.new) + len(session.dirty) + len(session.deleted) > 0:
            raise RuntimeError( \
                'Method clone() failed due to unflushed changes in session.')
338
        new_object = session.query(object_class).get(primary_key)
339
        session.rollback()
340 341 342 343 344
        if new_object is None:
            raise RuntimeError( \
                'Method clone() failed for non-persistent object:\n%s' % self)
        return new_object

345 346 347 348
__all__.append('ORMObject')

################################################################################

349 350 351 352 353 354 355 356
class Validator(MapperExtension):
    '''
    This class calls the validate() method for each instance for the
    'before_update' and 'before_insert' events. A global object validator is
    used for configuring the individual mappers.
    '''

    def before_update(self, mapper, connection, instance):
M
Mark Hymers 已提交
357
        instance.validate()
358 359 360
        return EXT_CONTINUE

    def before_insert(self, mapper, connection, instance):
M
Mark Hymers 已提交
361
        instance.validate()
362 363 364 365 366 367
        return EXT_CONTINUE

validator = Validator()

################################################################################

368
class Architecture(ORMObject):
T
Torsten Werner 已提交
369 370 371
    def __init__(self, arch_string = None, description = None):
        self.arch_string = arch_string
        self.description = description
M
Mark Hymers 已提交
372

373 374 375 376 377 378 379 380 381 382 383 384
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.arch_string== val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.arch_string != val)
        # This signals to use the normal comparison operator
        return NotImplemented

385 386
    def properties(self):
        return ['arch_string', 'arch_id', 'suites_count']
M
Mark Hymers 已提交
387

388 389
    def not_null_constraints(self):
        return ['arch_string']
390

391 392
__all__.append('Architecture')

393
@session_wrapper
394 395 396 397 398 399 400 401 402 403 404 405 406 407
def get_architecture(architecture, session=None):
    """
    Returns database id for given C{architecture}.

    @type architecture: string
    @param architecture: The name of the architecture

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Architecture
    @return: Architecture object for the given arch (None if not present)
    """
408

409
    q = session.query(Architecture).filter_by(arch_string=architecture)
410

411 412 413 414
    try:
        return q.one()
    except NoResultFound:
        return None
415

416 417
__all__.append('get_architecture')

418
# TODO: should be removed because the implementation is too trivial
419
@session_wrapper
M
Mark Hymers 已提交
420 421 422 423
def get_architecture_suites(architecture, session=None):
    """
    Returns list of Suite objects for given C{architecture} name

J
Joerg Jaspert 已提交
424 425
    @type architecture: str
    @param architecture: Architecture name to search for
M
Mark Hymers 已提交
426 427 428 429 430 431 432 433 434

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: list of Suite objects for the given name (may be empty)
    """

435
    return get_architecture(architecture, session).suites
M
Mark Hymers 已提交
436

437 438
__all__.append('get_architecture_suites')

M
Mark Hymers 已提交
439 440
################################################################################

M
Mark Hymers 已提交
441
class Archive(object):
M
Mark Hymers 已提交
442 443
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
444 445

    def __repr__(self):
C
Chris Lamb 已提交
446
        return '<Archive %s>' % self.archive_name
M
Mark Hymers 已提交
447

448 449
__all__.append('Archive')

450
@session_wrapper
451 452
def get_archive(archive, session=None):
    """
F
Frank Lichtenheld 已提交
453
    returns database id for given C{archive}.
454 455 456 457 458 459 460 461 462 463 464 465 466

    @type archive: string
    @param archive: the name of the arhive

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Archive
    @return: Archive object for the given name (None if not present)

    """
    archive = archive.lower()
467

468
    q = session.query(Archive).filter_by(archive_name=archive)
469

470 471 472 473
    try:
        return q.one()
    except NoResultFound:
        return None
474

475
__all__.append('get_archive')
476

M
Mark Hymers 已提交
477 478
################################################################################

479
class BinContents(ORMObject):
480 481 482 483 484
    def __init__(self, file = None, binary = None):
        self.file = file
        self.binary = binary

    def properties(self):
485
        return ['file', 'binary']
M
Mike O'Connor 已提交
486 487 488 489 490

__all__.append('BinContents')

################################################################################

491 492 493 494 495
def subprocess_setup():
    # Python installs a SIGPIPE handler by default. This is usually not what
    # non-Python subprocesses expect.
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)

496 497 498 499 500 501 502 503 504 505 506
class DBBinary(ORMObject):
    def __init__(self, package = None, source = None, version = None, \
        maintainer = None, architecture = None, poolfile = None, \
        binarytype = 'deb'):
        self.package = package
        self.source = source
        self.version = version
        self.maintainer = maintainer
        self.architecture = architecture
        self.poolfile = poolfile
        self.binarytype = binarytype
M
Mark Hymers 已提交
507

M
Mark Hymers 已提交
508 509 510 511
    @property
    def pkid(self):
        return self.binary_id

512 513 514
    def properties(self):
        return ['package', 'version', 'maintainer', 'source', 'architecture', \
            'poolfile', 'binarytype', 'fingerprint', 'install_date', \
M
Mark Hymers 已提交
515
            'suites_count', 'binary_id', 'contents_count', 'extra_sources']
516 517

    def not_null_constraints(self):
518 519
        return ['package', 'version', 'maintainer', 'source',  'poolfile', \
            'binarytype']
M
Mark Hymers 已提交
520

521 522
    metadata = association_proxy('key', 'value')

523 524 525
    def get_component_name(self):
        return self.poolfile.location.component.component_name

526 527 528
    def scan_contents(self):
        '''
        Yields the contents of the package. Only regular files are yielded and
529 530 531
        the path names are normalized after converting them from either utf-8
        or iso8859-1 encoding. It yields the string ' <EMPTY PACKAGE>' if the
        package does not contain any regular file.
532 533
        '''
        fullpath = self.poolfile.fullpath
534 535
        dpkg = Popen(['dpkg-deb', '--fsys-tarfile', fullpath], stdout = PIPE,
            preexec_fn = subprocess_setup)
536
        tar = TarFile.open(fileobj = dpkg.stdout, mode = 'r|')
537
        for member in tar.getmembers():
538
            if not member.isdir():
539 540
                name = normpath(member.name)
                # enforce proper utf-8 encoding
541
                try:
542
                    name.decode('utf-8')
T
bugfix  
Torsten Werner 已提交
543
                except UnicodeDecodeError:
544 545
                    name = name.decode('iso8859-1').encode('utf-8')
                yield name
546
        tar.close()
547 548
        dpkg.stdout.close()
        dpkg.wait()
549

M
Mark Hymers 已提交
550 551 552 553
    def read_control(self):
        '''
        Reads the control information from a binary.

M
Mark Hymers 已提交
554 555
        @rtype: text
        @return: stanza text of the control section.
M
Mark Hymers 已提交
556
        '''
M
Mark Hymers 已提交
557
        import apt_inst
M
Mark Hymers 已提交
558 559
        fullpath = self.poolfile.fullpath
        deb_file = open(fullpath, 'r')
M
Mark Hymers 已提交
560
        stanza = apt_inst.debExtractControl(deb_file)
M
Mark Hymers 已提交
561 562
        deb_file.close()

M
Mark Hymers 已提交
563 564 565 566 567 568
        return stanza

    def read_control_fields(self):
        '''
        Reads the control information from a binary and return
        as a dictionary.
M
Mark Hymers 已提交
569

M
Mark Hymers 已提交
570 571 572 573 574 575
        @rtype: dict
        @return: fields of the control section as a dictionary.
        '''
        import apt_pkg
        stanza = self.read_control()
        return apt_pkg.TagSection(stanza)
M
Mark Hymers 已提交
576

577
__all__.append('DBBinary')
578

579
@session_wrapper
580 581 582 583
def get_suites_binary_in(package, session=None):
    """
    Returns list of Suite objects which given C{package} name is in

J
Joerg Jaspert 已提交
584 585
    @type package: str
    @param package: DBBinary package name to search for
586 587 588 589 590

    @rtype: list
    @return: list of Suite objects for the given package
    """

591
    return session.query(Suite).filter(Suite.binaries.any(DBBinary.package == package)).all()
592 593 594

__all__.append('get_suites_binary_in')

595
@session_wrapper
596
def get_component_by_package_suite(package, suite_list, arch_list=[], session=None):
597 598
    '''
    Returns the component name of the newest binary package in suite_list or
599 600
    None if no package is found. The result can be optionally filtered by a list
    of architecture names.
601 602 603

    @type package: str
    @param package: DBBinary package name to search for
604

605 606 607
    @type suite_list: list of str
    @param suite_list: list of suite_name items

608 609 610
    @type arch_list: list of str
    @param arch_list: optional list of arch_string items that defaults to []

611 612 613 614
    @rtype: str or NoneType
    @return: name of component or None
    '''

615 616 617 618 619 620
    q = session.query(DBBinary).filter_by(package = package). \
        join(DBBinary.suites).filter(Suite.suite_name.in_(suite_list))
    if len(arch_list) > 0:
        q = q.join(DBBinary.architecture). \
            filter(Architecture.arch_string.in_(arch_list))
    binary = q.order_by(desc(DBBinary.version)).first()
621 622 623 624
    if binary is None:
        return None
    else:
        return binary.get_component_name()
625 626

__all__.append('get_component_by_package_suite')
M
Mark Hymers 已提交
627

M
Mark Hymers 已提交
628 629
################################################################################

630 631 632 633
class BinaryACL(object):
    def __init__(self, *args, **kwargs):
        pass

634 635 636
    def __repr__(self):
        return '<BinaryACL %s>' % self.binary_acl_id

637 638 639 640 641 642 643 644
__all__.append('BinaryACL')

################################################################################

class BinaryACLMap(object):
    def __init__(self, *args, **kwargs):
        pass

645 646 647
    def __repr__(self):
        return '<BinaryACLMap %s>' % self.binary_acl_map_id

648 649 650 651
__all__.append('BinaryACLMap')

################################################################################

M
Mark Hymers 已提交
652 653 654 655
MINIMAL_APT_CONF="""
Dir
{
   ArchiveDir "%(archivepath)s";
J
Joerg Jaspert 已提交
656 657
   OverrideDir "%(overridedir)s";
   CacheDir "%(cachedir)s";
M
Mark Hymers 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
};

Default
{
   Packages::Compress ". bzip2 gzip";
   Sources::Compress ". bzip2 gzip";
   DeLinkLimit 0;
   FileMode 0664;
}

bindirectory "incoming"
{
   Packages "Packages";
   Contents " ";

   BinOverride "override.sid.all3";
   BinCacheDB "packages-accepted.db";

   FileList "%(filelist)s";

   PathPrefix "";
   Packages::Extensions ".deb .udeb";
};

bindirectory "incoming/"
{
   Sources "Sources";
   BinOverride "override.sid.all3";
   SrcOverride "override.sid.all3.src";
   FileList "%(filelist)s";
};
"""

691 692 693 694 695
class BuildQueue(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
696
        return '<BuildQueue %s>' % self.queue_name
697

M
Mark Hymers 已提交
698
    def write_metadata(self, starttime, force=False):
M
Mark Hymers 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711
        # Do we write out metafiles?
        if not (force or self.generate_metadata):
            return

        session = DBConn().session().object_session(self)

        fl_fd = fl_name = ac_fd = ac_name = None
        tempdir = None
        arches = " ".join([ a.arch_string for a in session.query(Architecture).all() if a.arch_string != 'source' ])
        startdir = os.getcwd()

        try:
            # Grab files we want to include
M
Mark Hymers 已提交
712
            newer = session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id).filter(BuildQueueFile.lastused + timedelta(seconds=self.stay_of_execution) > starttime).all()
713
            newer += session.query(BuildQueuePolicyFile).filter_by(build_queue_id = self.queue_id).filter(BuildQueuePolicyFile.lastused + timedelta(seconds=self.stay_of_execution) > starttime).all()
M
Mark Hymers 已提交
714 715 716 717 718 719
            # Write file list with newer files
            (fl_fd, fl_name) = mkstemp()
            for n in newer:
                os.write(fl_fd, '%s\n' % n.fullpath)
            os.close(fl_fd)

J
Joerg Jaspert 已提交
720 721
            cnf = Config()

M
Mark Hymers 已提交
722 723 724 725
            # Write minimal apt.conf
            # TODO: Remove hardcoding from template
            (ac_fd, ac_name) = mkstemp()
            os.write(ac_fd, MINIMAL_APT_CONF % {'archivepath': self.path,
J
Joerg Jaspert 已提交
726 727 728 729
                                                'filelist': fl_name,
                                                'cachedir': cnf["Dir::Cache"],
                                                'overridedir': cnf["Dir::Override"],
                                                })
M
Mark Hymers 已提交
730
            os.close(ac_fd)
M
Mark Hymers 已提交
731 732

            # Run apt-ftparchive generate
M
Mark Hymers 已提交
733 734
            os.chdir(os.path.dirname(ac_name))
            os.system('apt-ftparchive -qq -o APT::FTPArchive::Contents=off generate %s' % os.path.basename(ac_name))
M
Mark Hymers 已提交
735 736 737 738 739 740

            # Run apt-ftparchive release
            # TODO: Eww - fix this
            bname = os.path.basename(self.path)
            os.chdir(self.path)
            os.chdir('..')
741 742 743 744 745 746 747 748

            # We have to remove the Release file otherwise it'll be included in the
            # new one
            try:
                os.unlink(os.path.join(bname, 'Release'))
            except OSError:
                pass

M
argh  
Mark Hymers 已提交
749
            os.system("""apt-ftparchive -qq -o APT::FTPArchive::Release::Origin="%s" -o APT::FTPArchive::Release::Label="%s" -o APT::FTPArchive::Release::Description="%s" -o APT::FTPArchive::Release::Architectures="%s" release %s > Release""" % (self.origin, self.label, self.releasedescription, arches, bname))
M
Mark Hymers 已提交
750

J
Joerg Jaspert 已提交
751 752 753 754 755 756
            # Crude hack with open and append, but this whole section is and should be redone.
            if self.notautomatic:
                release=open("Release", "a")
                release.write("NotAutomatic: yes")
                release.close()

M
Mark Hymers 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
            # Sign if necessary
            if self.signingkey:
                keyring = "--secret-keyring \"%s\"" % cnf["Dinstall::SigningKeyring"]
                if cnf.has_key("Dinstall::SigningPubKeyring"):
                    keyring += " --keyring \"%s\"" % cnf["Dinstall::SigningPubKeyring"]

                os.system("gpg %s --no-options --batch --no-tty --armour --default-key %s --detach-sign -o Release.gpg Release""" % (keyring, self.signingkey))

            # Move the files if we got this far
            os.rename('Release', os.path.join(bname, 'Release'))
            if self.signingkey:
                os.rename('Release.gpg', os.path.join(bname, 'Release.gpg'))

        # Clean up any left behind files
        finally:
            os.chdir(startdir)
            if fl_fd:
                try:
                    os.close(fl_fd)
                except OSError:
                    pass

            if fl_name:
                try:
                    os.unlink(fl_name)
                except OSError:
                    pass

            if ac_fd:
                try:
                    os.close(ac_fd)
                except OSError:
                    pass

            if ac_name:
                try:
                    os.unlink(ac_name)
                except OSError:
                    pass

M
Mark Hymers 已提交
797
    def clean_and_update(self, starttime, Logger, dryrun=False):
M
Mark Hymers 已提交
798 799 800
        """WARNING: This routine commits for you"""
        session = DBConn().session().object_session(self)

M
Mark Hymers 已提交
801
        if self.generate_metadata and not dryrun:
M
Mark Hymers 已提交
802
            self.write_metadata(starttime)
M
Mark Hymers 已提交
803 804

        # Grab files older than our execution time
M
Mark Hymers 已提交
805
        older = session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id).filter(BuildQueueFile.lastused + timedelta(seconds=self.stay_of_execution) <= starttime).all()
806
        older += session.query(BuildQueuePolicyFile).filter_by(build_queue_id = self.queue_id).filter(BuildQueuePolicyFile.lastused + timedelta(seconds=self.stay_of_execution) <= starttime).all()
M
Mark Hymers 已提交
807 808 809 810 811

        for o in older:
            killdb = False
            try:
                if dryrun:
M
Mark Hymers 已提交
812
                    Logger.log(["I: Would have removed %s from the queue" % o.fullpath])
M
Mark Hymers 已提交
813
                else:
M
Mark Hymers 已提交
814
                    Logger.log(["I: Removing %s from the queue" % o.fullpath])
M
Mark Hymers 已提交
815 816 817 818 819 820 821 822
                    os.unlink(o.fullpath)
                    killdb = True
            except OSError, e:
                # If it wasn't there, don't worry
                if e.errno == ENOENT:
                    killdb = True
                else:
                    # TODO: Replace with proper logging call
M
Mark Hymers 已提交
823
                    Logger.log(["E: Could not remove %s" % o.fullpath])
M
Mark Hymers 已提交
824 825 826 827 828 829

            if killdb:
                session.delete(o)

        session.commit()

M
Mark Hymers 已提交
830
        for f in os.listdir(self.path):
J
Joerg Jaspert 已提交
831
            if f.startswith('Packages') or f.startswith('Source') or f.startswith('Release') or f.startswith('advisory'):
M
Mark Hymers 已提交
832 833
                continue

834
            if not self.contains_filename(f):
M
Mark Hymers 已提交
835 836
                fp = os.path.join(self.path, f)
                if dryrun:
M
Mark Hymers 已提交
837
                    Logger.log(["I: Would remove unused link %s" % fp])
M
Mark Hymers 已提交
838
                else:
M
Mark Hymers 已提交
839
                    Logger.log(["I: Removing unused link %s" % fp])
M
Mark Hymers 已提交
840 841 842
                    try:
                        os.unlink(fp)
                    except OSError:
M
Mark Hymers 已提交
843
                        Logger.log(["E: Failed to unlink unreferenced file %s" % r.fullpath])
M
Mark Hymers 已提交
844

845 846 847 848 849 850 851 852 853 854 855 856
    def contains_filename(self, filename):
        """
        @rtype Boolean
        @returns True if filename is supposed to be in the queue; False otherwise
        """
        session = DBConn().session().object_session(self)
        if session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id, filename = filename).count() > 0:
            return True
        elif session.query(BuildQueuePolicyFile).filter_by(build_queue = self, filename = filename).count() > 0:
            return True
        return False

857 858 859 860 861 862 863 864 865
    def add_file_from_pool(self, poolfile):
        """Copies a file into the pool.  Assumes that the PoolFile object is
        attached to the same SQLAlchemy session as the Queue object is.

        The caller is responsible for committing after calling this function."""
        poolfile_basename = poolfile.filename[poolfile.filename.rindex(os.sep)+1:]

        # Check if we have a file of this name or this ID already
        for f in self.queuefiles:
866 867
            if (f.fileid is not None and f.fileid == poolfile.file_id) or \
               (f.poolfile is not None and f.poolfile.filename == poolfile_basename):
M
Mark Hymers 已提交
868
                   # In this case, update the BuildQueueFile entry so we
869 870
                   # don't remove it too early
                   f.lastused = datetime.now()
871
                   DBConn().session().object_session(poolfile).add(f)
872 873
                   return f

M
Mark Hymers 已提交
874 875
        # Prepare BuildQueueFile object
        qf = BuildQueueFile()
M
hmm...  
Mark Hymers 已提交
876
        qf.build_queue_id = self.queue_id
877
        qf.lastused = datetime.now()
878
        qf.filename = poolfile_basename
879

M
Mark Hymers 已提交
880
        targetpath = poolfile.fullpath
881 882 883
        queuepath = os.path.join(self.path, poolfile_basename)

        try:
M
Mark Hymers 已提交
884
            if self.copy_files:
885 886
                # We need to copy instead of symlink
                import utils
M
Mark Hymers 已提交
887
                utils.copy(targetpath, queuepath)
888 889 890
                # NULL in the fileid field implies a copy
                qf.fileid = None
            else:
M
Mark Hymers 已提交
891
                os.symlink(targetpath, queuepath)
892 893 894 895 896 897 898 899 900
                qf.fileid = poolfile.file_id
        except OSError:
            return None

        # Get the same session as the PoolFile is using and add the qf to it
        DBConn().session().object_session(poolfile).add(qf)

        return qf

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
    def add_changes_from_policy_queue(self, policyqueue, changes):
        """
        Copies a changes from a policy queue together with its poolfiles.

        @type policyqueue: PolicyQueue
        @param policyqueue: policy queue to copy the changes from

        @type changes: DBChange
        @param changes: changes to copy to this build queue
        """
        for policyqueuefile in changes.files:
            self.add_file_from_policy_queue(policyqueue, policyqueuefile)
        for poolfile in changes.poolfiles:
            self.add_file_from_pool(poolfile)

    def add_file_from_policy_queue(self, policyqueue, policyqueuefile):
        """
        Copies a file from a policy queue.
        Assumes that the policyqueuefile is attached to the same SQLAlchemy
        session as the Queue object is.  The caller is responsible for
        committing after calling this function.

        @type policyqueue: PolicyQueue
        @param policyqueue: policy queue to copy the file from

        @type policyqueuefile: ChangePendingFile
        @param policyqueuefile: file to be added to the build queue
        """
        session = DBConn().session().object_session(policyqueuefile)

        # Is the file already there?
        try:
            f = session.query(BuildQueuePolicyFile).filter_by(build_queue=self, file=policyqueuefile).one()
            f.lastused = datetime.now()
            return f
        except NoResultFound:
            pass # continue below

        # We have to add the file.
        f = BuildQueuePolicyFile()
        f.build_queue = self
        f.file = policyqueuefile
        f.filename = policyqueuefile.filename

        source = os.path.join(policyqueue.path, policyqueuefile.filename)
        target = f.fullpath
        try:
            # Always copy files from policy queues as they might move around.
            import utils
            utils.copy(source, target)
        except OSError:
            return None

        session.add(f)
        return f
956 957 958 959

__all__.append('BuildQueue')

@session_wrapper
960
def get_build_queue(queuename, session=None):
961
    """
962
    Returns BuildQueue object for given C{queue name}, creating it if it does not
963 964 965 966 967 968 969 970 971
    exist.

    @type queuename: string
    @param queuename: The name of the queue

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

972 973
    @rtype: BuildQueue
    @return: BuildQueue object for the given queue
974 975
    """

976
    q = session.query(BuildQueue).filter_by(queue_name=queuename)
977 978 979 980 981 982

    try:
        return q.one()
    except NoResultFound:
        return None

983
__all__.append('get_build_queue')
984 985 986 987

################################################################################

class BuildQueueFile(object):
988 989 990 991
    """
    BuildQueueFile represents a file in a build queue coming from a pool.
    """

992 993 994 995
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
M
Mark Hymers 已提交
996
        return '<BuildQueueFile %s (%s)>' % (self.filename, self.build_queue_id)
997

M
Mark Hymers 已提交
998 999 1000 1001
    @property
    def fullpath(self):
        return os.path.join(self.buildqueue.path, self.filename)

1002 1003 1004 1005 1006

__all__.append('BuildQueueFile')

################################################################################

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
class BuildQueuePolicyFile(object):
    """
    BuildQueuePolicyFile represents a file in a build queue that comes from a
    policy queue (and not a pool).
    """

    def __init__(self, *args, **kwargs):
        pass

    #@property
    #def filename(self):
    #    return self.file.filename

    @property
    def fullpath(self):
        return os.path.join(self.build_queue.path, self.filename)

__all__.append('BuildQueuePolicyFile')

################################################################################

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
class ChangePendingBinary(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<ChangePendingBinary %s>' % self.change_pending_binary_id

__all__.append('ChangePendingBinary')

################################################################################

class ChangePendingFile(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<ChangePendingFile %s>' % self.change_pending_file_id

__all__.append('ChangePendingFile')

################################################################################

class ChangePendingSource(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<ChangePendingSource %s>' % self.change_pending_source_id

__all__.append('ChangePendingSource')

################################################################################

1061 1062 1063
class Component(ORMObject):
    def __init__(self, component_name = None):
        self.component_name = component_name
M
Mark Hymers 已提交
1064

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.component_name == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.component_name != val)
        # This signals to use the normal comparison operator
        return NotImplemented

1077
    def properties(self):
1078 1079
        return ['component_name', 'component_id', 'description', \
            'location_count', 'meets_dfsg', 'overrides_count']
1080 1081 1082

    def not_null_constraints(self):
        return ['component_name']
M
Mark Hymers 已提交
1083

1084 1085 1086

__all__.append('Component')

1087
@session_wrapper
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
def get_component(component, session=None):
    """
    Returns database id for given C{component}.

    @type component: string
    @param component: The name of the override type

    @rtype: int
    @return: the database id for the given component

    """
    component = component.lower()
1100

1101
    q = session.query(Component).filter_by(component_name=component)
1102

1103 1104 1105 1106
    try:
        return q.one()
    except NoResultFound:
        return None
1107

1108 1109
__all__.append('get_component')

M
Mark Hymers 已提交
1110 1111
################################################################################

M
Mark Hymers 已提交
1112
class DBConfig(object):
M
Mark Hymers 已提交
1113 1114
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1115 1116 1117 1118

    def __repr__(self):
        return '<DBConfig %s>' % self.name

1119 1120
__all__.append('DBConfig')

M
Mark Hymers 已提交
1121 1122
################################################################################

1123
@session_wrapper
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
def get_or_set_contents_file_id(filename, session=None):
    """
    Returns database id for given filename.

    If no matching file is found, a row is inserted.

    @type filename: string
    @param filename: The filename
    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
M
Mark Hymers 已提交
1134 1135
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.
1136 1137 1138 1139 1140

    @rtype: int
    @return: the database id for the given component
    """

1141
    q = session.query(ContentFilename).filter_by(filename=filename)
1142 1143 1144 1145

    try:
        ret = q.one().cafilename_id
    except NoResultFound:
1146 1147 1148
        cf = ContentFilename()
        cf.filename = filename
        session.add(cf)
1149
        session.commit_or_flush()
1150
        ret = cf.cafilename_id
1151

1152
    return ret
1153 1154 1155

__all__.append('get_or_set_contents_file_id')

1156
@session_wrapper
M
Mark Hymers 已提交
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
def get_contents(suite, overridetype, section=None, session=None):
    """
    Returns contents for a suite / overridetype combination, limiting
    to a section if not None.

    @type suite: Suite
    @param suite: Suite object

    @type overridetype: OverrideType
    @param overridetype: OverrideType object

    @type section: Section
    @param section: Optional section object to limit results to

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: ResultsProxy
    @return: ResultsProxy object set up to return tuples of (filename, section,
    package, arch_id)
    """

    # find me all of the contents for a given suite
    contents_q = """SELECT (p.path||'/'||n.file) AS fn,
                            s.section,
                            b.package,
                            b.architecture
                   FROM content_associations c join content_file_paths p ON (c.filepath=p.id)
                   JOIN content_file_names n ON (c.filename=n.id)
                   JOIN binaries b ON (b.id=c.binary_pkg)
                   JOIN override o ON (o.package=b.package)
                   JOIN section s ON (s.id=o.section)
                   WHERE o.suite = :suiteid AND o.type = :overridetypeid
                   AND b.type=:overridetypename"""

    vals = {'suiteid': suite.suite_id,
            'overridetypeid': overridetype.overridetype_id,
            'overridetypename': overridetype.overridetype}

    if section is not None:
        contents_q += " AND s.id = :sectionid"
        vals['sectionid'] = section.section_id

    contents_q += " ORDER BY fn"

1203
    return session.execute(contents_q, vals)
M
Mark Hymers 已提交
1204 1205 1206

__all__.append('get_contents')

M
Mark Hymers 已提交
1207 1208
################################################################################

M
Mark Hymers 已提交
1209
class ContentFilepath(object):
M
Mark Hymers 已提交
1210 1211
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1212 1213 1214 1215

    def __repr__(self):
        return '<ContentFilepath %s>' % self.filepath

1216 1217
__all__.append('ContentFilepath')

1218
@session_wrapper
M
Mark Hymers 已提交
1219
def get_or_set_contents_path_id(filepath, session=None):
1220 1221 1222 1223 1224
    """
    Returns database id for given path.

    If no matching file is found, a row is inserted.

J
Joerg Jaspert 已提交
1225 1226 1227
    @type filepath: string
    @param filepath: The filepath

1228 1229
    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
M
Mark Hymers 已提交
1230 1231
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.
1232 1233 1234 1235 1236

    @rtype: int
    @return: the database id for the given path
    """

1237
    q = session.query(ContentFilepath).filter_by(filepath=filepath)
1238 1239 1240 1241

    try:
        ret = q.one().cafilepath_id
    except NoResultFound:
1242 1243 1244
        cf = ContentFilepath()
        cf.filepath = filepath
        session.add(cf)
1245
        session.commit_or_flush()
1246
        ret = cf.cafilepath_id
1247

1248
    return ret
1249 1250 1251

__all__.append('get_or_set_contents_path_id')

M
Mark Hymers 已提交
1252 1253
################################################################################

1254
class ContentAssociation(object):
M
Mark Hymers 已提交
1255 1256
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1257 1258 1259 1260

    def __repr__(self):
        return '<ContentAssociation %s>' % self.ca_id

1261 1262
__all__.append('ContentAssociation')

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
def insert_content_paths(binary_id, fullpaths, session=None):
    """
    Make sure given path is associated with given binary id

    @type binary_id: int
    @param binary_id: the id of the binary
    @type fullpaths: list
    @param fullpaths: the list of paths of the file being associated with the binary
    @type session: SQLAlchemy session
    @param session: Optional SQLAlchemy session.  If this is passed, the caller
    is responsible for ensuring a transaction has begun and committing the
    results or rolling back based on the result code.  If not passed, a commit
M
Mark Hymers 已提交
1275 1276
    will be performed at the end of the function, otherwise the caller is
    responsible for commiting.
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286

    @return: True upon success
    """

    privatetrans = False
    if session is None:
        session = DBConn().session()
        privatetrans = True

    try:
M
Mark Hymers 已提交
1287
        # Insert paths
1288 1289 1290 1291 1292
        def generate_path_dicts():
            for fullpath in fullpaths:
                if fullpath.startswith( './' ):
                    fullpath = fullpath[2:]

1293
                yield {'filename':fullpath, 'id': binary_id }
1294

1295 1296 1297
        for d in generate_path_dicts():
            session.execute( "INSERT INTO bin_contents ( file, binary_id ) VALUES ( :filename, :id )",
                         d )
1298

M
Mike O'Connor 已提交
1299
        session.commit()
1300
        if privatetrans:
M
Mark Hymers 已提交
1301
            session.close()
1302
        return True
M
Mark Hymers 已提交
1303

1304 1305 1306 1307 1308 1309
    except:
        traceback.print_exc()

        # Only rollback if we set up the session ourself
        if privatetrans:
            session.rollback()
M
Mark Hymers 已提交
1310
            session.close()
1311 1312 1313 1314 1315

        return False

__all__.append('insert_content_paths')

M
Mark Hymers 已提交
1316 1317
################################################################################

M
Mark Hymers 已提交
1318
class DSCFile(object):
M
Mark Hymers 已提交
1319 1320
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1321 1322 1323 1324

    def __repr__(self):
        return '<DSCFile %s>' % self.dscfile_id

1325 1326
__all__.append('DSCFile')

1327
@session_wrapper
M
Mark Hymers 已提交
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
def get_dscfiles(dscfile_id=None, source_id=None, poolfile_id=None, session=None):
    """
    Returns a list of DSCFiles which may be empty

    @type dscfile_id: int (optional)
    @param dscfile_id: the dscfile_id of the DSCFiles to find

    @type source_id: int (optional)
    @param source_id: the source id related to the DSCFiles to find

    @type poolfile_id: int (optional)
    @param poolfile_id: the poolfile id related to the DSCFiles to find

    @rtype: list
    @return: Possibly empty list of DSCFiles
    """

    q = session.query(DSCFile)

    if dscfile_id is not None:
        q = q.filter_by(dscfile_id=dscfile_id)

    if source_id is not None:
        q = q.filter_by(source_id=source_id)

    if poolfile_id is not None:
        q = q.filter_by(poolfile_id=poolfile_id)

1356
    return q.all()
M
Mark Hymers 已提交
1357 1358 1359

__all__.append('get_dscfiles')

M
Mark Hymers 已提交
1360 1361
################################################################################

A
Ansgar Burchardt 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
class ExternalOverride(ORMObject):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<ExternalOverride %s = %s: %s>' % (self.package, self.key, self.value)

__all__.append('ExternalOverride')

################################################################################

1373
class PoolFile(ORMObject):
1374 1375 1376 1377 1378 1379
    def __init__(self, filename = None, location = None, filesize = -1, \
        md5sum = None):
        self.filename = filename
        self.location = location
        self.filesize = filesize
        self.md5sum = md5sum
M
Mark Hymers 已提交
1380

M
Mark Hymers 已提交
1381 1382 1383 1384
    @property
    def fullpath(self):
        return os.path.join(self.location.path, self.filename)

1385
    def is_valid(self, filesize = -1, md5sum = None):
1386
        return self.filesize == long(filesize) and self.md5sum == md5sum
T
Torsten Werner 已提交
1387

1388 1389
    def properties(self):
        return ['filename', 'file_id', 'filesize', 'md5sum', 'sha1sum', \
1390
            'sha256sum', 'location', 'source', 'binary', 'last_used']
1391

1392 1393
    def not_null_constraints(self):
        return ['filename', 'md5sum', 'location']
T
Torsten Werner 已提交
1394

1395 1396
__all__.append('PoolFile')

1397
@session_wrapper
1398 1399 1400
def check_poolfile(filename, filesize, md5sum, location_id, session=None):
    """
    Returns a tuple:
T
Torsten Werner 已提交
1401
    (ValidFileFound [boolean], PoolFile object or None)
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

    @type filename: string
    @param filename: the filename of the file to check against the DB

    @type filesize: int
    @param filesize: the size of the file to check against the DB

    @type md5sum: string
    @param md5sum: the md5sum of the file to check against the DB

    @type location_id: int
    @param location_id: the id of the location to look in

    @rtype: tuple
    @return: Tuple of length 2.
J
Joerg Jaspert 已提交
1417 1418 1419 1420
                 - If valid pool file found: (C{True}, C{PoolFile object})
                 - If valid pool file not found:
                     - (C{False}, C{None}) if no file found
                     - (C{False}, C{PoolFile object}) if file found with size/md5sum mismatch
1421 1422
    """

T
Torsten Werner 已提交
1423 1424 1425 1426 1427
    poolfile = session.query(Location).get(location_id). \
        files.filter_by(filename=filename).first()
    valid = False
    if poolfile and poolfile.is_valid(filesize = filesize, md5sum = md5sum):
        valid = True
1428

T
Torsten Werner 已提交
1429
    return (valid, poolfile)
1430 1431 1432

__all__.append('check_poolfile')

T
Torsten Werner 已提交
1433 1434
# TODO: the implementation can trivially be inlined at the place where the
# function is called
1435
@session_wrapper
M
Mark Hymers 已提交
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
def get_poolfile_by_id(file_id, session=None):
    """
    Returns a PoolFile objects or None for the given id

    @type file_id: int
    @param file_id: the id of the file to look for

    @rtype: PoolFile or None
    @return: either the PoolFile object or None
    """

T
Torsten Werner 已提交
1447
    return session.query(PoolFile).get(file_id)
M
Mark Hymers 已提交
1448 1449 1450

__all__.append('get_poolfile_by_id')

1451
@session_wrapper
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
def get_poolfile_like_name(filename, session=None):
    """
    Returns an array of PoolFile objects which are like the given name

    @type filename: string
    @param filename: the filename of the file to check against the DB

    @rtype: array
    @return: array of PoolFile objects
    """

    # TODO: There must be a way of properly using bind parameters with %FOO%
M
Mark Hymers 已提交
1464
    q = session.query(PoolFile).filter(PoolFile.filename.like('%%/%s' % filename))
1465

1466
    return q.all()
1467 1468 1469

__all__.append('get_poolfile_like_name')

1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
@session_wrapper
def add_poolfile(filename, datadict, location_id, session=None):
    """
    Add a new file to the pool

    @type filename: string
    @param filename: filename

    @type datadict: dict
    @param datadict: dict with needed data

    @type location_id: int
    @param location_id: database id of the location

    @rtype: PoolFile
    @return: the PoolFile object created
    """
    poolfile = PoolFile()
    poolfile.filename = filename
    poolfile.filesize = datadict["size"]
    poolfile.md5sum = datadict["md5sum"]
    poolfile.sha1sum = datadict["sha1sum"]
    poolfile.sha256sum = datadict["sha256sum"]
    poolfile.location_id = location_id

    session.add(poolfile)
    # Flush to get a file id (NB: This is not a commit)
    session.flush()

    return poolfile

__all__.append('add_poolfile')

M
Mark Hymers 已提交
1503 1504
################################################################################

1505
class Fingerprint(ORMObject):
T
Torsten Werner 已提交
1506 1507
    def __init__(self, fingerprint = None):
        self.fingerprint = fingerprint
M
Mark Hymers 已提交
1508

1509 1510 1511 1512 1513 1514
    def properties(self):
        return ['fingerprint', 'fingerprint_id', 'keyring', 'uid', \
            'binary_reject']

    def not_null_constraints(self):
        return ['fingerprint']
M
Mark Hymers 已提交
1515

1516 1517
__all__.append('Fingerprint')

M
Mark Hymers 已提交
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
@session_wrapper
def get_fingerprint(fpr, session=None):
    """
    Returns Fingerprint object for given fpr.

    @type fpr: string
    @param fpr: The fpr to find / add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).

    @rtype: Fingerprint
    @return: the Fingerprint object for the given fpr or None
    """

    q = session.query(Fingerprint).filter_by(fingerprint=fpr)

    try:
        ret = q.one()
    except NoResultFound:
        ret = None

    return ret

__all__.append('get_fingerprint')

1545
@session_wrapper
M
Mark Hymers 已提交
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
def get_or_set_fingerprint(fpr, session=None):
    """
    Returns Fingerprint object for given fpr.

    If no matching fpr is found, a row is inserted.

    @type fpr: string
    @param fpr: The fpr to find / add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.
    A flush will be performed either way.

    @rtype: Fingerprint
    @return: the Fingerprint object for the given fpr
    """

1565
    q = session.query(Fingerprint).filter_by(fingerprint=fpr)
1566 1567 1568 1569

    try:
        ret = q.one()
    except NoResultFound:
1570 1571 1572
        fingerprint = Fingerprint()
        fingerprint.fingerprint = fpr
        session.add(fingerprint)
1573
        session.commit_or_flush()
1574
        ret = fingerprint
M
Mark Hymers 已提交
1575

1576
    return ret
M
Mark Hymers 已提交
1577 1578 1579

__all__.append('get_or_set_fingerprint')

M
Mark Hymers 已提交
1580 1581
################################################################################

M
Mark Hymers 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
# Helper routine for Keyring class
def get_ldap_name(entry):
    name = []
    for k in ["cn", "mn", "sn"]:
        ret = entry.get(k)
        if ret and ret[0] != "" and ret[0] != "-":
            name.append(ret[0])
    return " ".join(name)

################################################################################

M
Mark Hymers 已提交
1593
class Keyring(object):
M
Mark Hymers 已提交
1594 1595 1596 1597 1598 1599
    gpg_invocation = "gpg --no-default-keyring --keyring %s" +\
                     " --with-colons --fingerprint --fingerprint"

    keys = {}
    fpr_lookup = {}

M
Mark Hymers 已提交
1600 1601
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1602 1603 1604 1605

    def __repr__(self):
        return '<Keyring %s>' % self.keyring_name

1606 1607
    def de_escape_gpg_str(self, txt):
        esclist = re.split(r'(\\x..)', txt)
M
Mark Hymers 已提交
1608 1609 1610 1611
        for x in range(1,len(esclist),2):
            esclist[x] = "%c" % (int(esclist[x][2:],16))
        return "".join(esclist)

T
Torsten Werner 已提交
1612 1613
    def parse_address(self, uid):
        """parses uid and returns a tuple of real name and email address"""
M
Mark Hymers 已提交
1614
        import email.Utils
T
Torsten Werner 已提交
1615 1616 1617 1618 1619 1620
        (name, address) = email.Utils.parseaddr(uid)
        name = re.sub(r"\s*[(].*[)]", "", name)
        name = self.de_escape_gpg_str(name)
        if name == "":
            name = uid
        return (name, address)
M
Mark Hymers 已提交
1621

T
Torsten Werner 已提交
1622
    def load_keys(self, keyring):
M
Mark Hymers 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
        if not self.keyring_id:
            raise Exception('Must be initialized with database information')

        k = os.popen(self.gpg_invocation % keyring, "r")
        key = None
        signingkey = False

        for line in k.xreadlines():
            field = line.split(":")
            if field[0] == "pub":
                key = field[4]
T
Torsten Werner 已提交
1634 1635 1636 1637
                self.keys[key] = {}
                (name, addr) = self.parse_address(field[9])
                if "@" in addr:
                    self.keys[key]["email"] = addr
M
Mark Hymers 已提交
1638 1639 1640 1641 1642 1643
                    self.keys[key]["name"] = name
                self.keys[key]["fingerprints"] = []
                signingkey = True
            elif key and field[0] == "sub" and len(field) >= 12:
                signingkey = ("s" in field[11])
            elif key and field[0] == "uid":
T
Torsten Werner 已提交
1644 1645 1646 1647
                (name, addr) = self.parse_address(field[9])
                if "email" not in self.keys[key] and "@" in addr:
                    self.keys[key]["email"] = addr
                    self.keys[key]["name"] = name
M
Mark Hymers 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
            elif signingkey and field[0] == "fpr":
                self.keys[key]["fingerprints"].append(field[9])
                self.fpr_lookup[field[9]] = key

    def import_users_from_ldap(self, session):
        import ldap
        cnf = Config()

        LDAPDn = cnf["Import-LDAP-Fingerprints::LDAPDn"]
        LDAPServer = cnf["Import-LDAP-Fingerprints::LDAPServer"]

        l = ldap.open(LDAPServer)
        l.simple_bind_s("","")
        Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
               "(&(keyfingerprint=*)(gidnumber=%s))" % (cnf["Import-Users-From-Passwd::ValidGID"]),
               ["uid", "keyfingerprint", "cn", "mn", "sn"])

        ldap_fin_uid_id = {}

        byuid = {}
        byname = {}

        for i in Attrs:
            entry = i[1]
            uid = entry["uid"][0]
            name = get_ldap_name(entry)
            fingerprints = entry["keyFingerPrint"]
            keyid = None
            for f in fingerprints:
                key = self.fpr_lookup.get(f, None)
                if key not in self.keys:
                    continue
                self.keys[key]["uid"] = uid

                if keyid != None:
                    continue
                keyid = get_or_set_uid(uid, session).uid_id
                byuid[keyid] = (uid, name)
                byname[uid] = (keyid, name)

        return (byname, byuid)

    def generate_users_from_keyring(self, format, session):
        byuid = {}
        byname = {}
        any_invalid = False
        for x in self.keys.keys():
T
Torsten Werner 已提交
1695
            if "email" not in self.keys[x]:
M
Mark Hymers 已提交
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
                any_invalid = True
                self.keys[x]["uid"] = format % "invalid-uid"
            else:
                uid = format % self.keys[x]["email"]
                keyid = get_or_set_uid(uid, session).uid_id
                byuid[keyid] = (uid, self.keys[x]["name"])
                byname[uid] = (keyid, self.keys[x]["name"])
                self.keys[x]["uid"] = uid

        if any_invalid:
            uid = format % "invalid-uid"
            keyid = get_or_set_uid(uid, session).uid_id
            byuid[keyid] = (uid, "ungeneratable user id")
            byname[uid] = (keyid, "ungeneratable user id")

        return (byname, byuid)

1713 1714
__all__.append('Keyring')

1715
@session_wrapper
M
Mark Hymers 已提交
1716
def get_keyring(keyring, session=None):
1717
    """
M
Mark Hymers 已提交
1718
    If C{keyring} does not have an entry in the C{keyrings} table yet, return None
1719 1720 1721 1722 1723 1724 1725 1726 1727
    If C{keyring} already has an entry, simply return the existing Keyring

    @type keyring: string
    @param keyring: the keyring name

    @rtype: Keyring
    @return: the Keyring object for this keyring
    """

1728
    q = session.query(Keyring).filter_by(keyring_name=keyring)
1729

1730 1731 1732
    try:
        return q.one()
    except NoResultFound:
M
Mark Hymers 已提交
1733
        return None
1734

M
Mark Hymers 已提交
1735
__all__.append('get_keyring')
1736

M
Mark Hymers 已提交
1737
################################################################################
1738

M
Mark Hymers 已提交
1739 1740 1741 1742 1743 1744 1745 1746
class KeyringACLMap(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<KeyringACLMap %s>' % self.keyring_acl_map_id

__all__.append('KeyringACLMap')
1747

M
Mark Hymers 已提交
1748 1749
################################################################################

M
Mark Hymers 已提交
1750
class DBChange(object):
J
Joerg Jaspert 已提交
1751 1752 1753 1754
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
M
Mark Hymers 已提交
1755
        return '<DBChange %s>' % self.changesname
J
Joerg Jaspert 已提交
1756

1757 1758 1759 1760
    def clean_from_queue(self):
        session = DBConn().session().object_session(self)

        # Remove changes_pool_files entries
M
Mark Hymers 已提交
1761
        self.poolfiles = []
1762

M
Mark Hymers 已提交
1763 1764
        # Remove changes_pending_files references
        self.files = []
1765 1766 1767 1768 1769

        # Clear out of queue
        self.in_queue = None
        self.approved_for_id = None

M
Mark Hymers 已提交
1770
__all__.append('DBChange')
J
Joerg Jaspert 已提交
1771 1772

@session_wrapper
M
Mark Hymers 已提交
1773
def get_dbchange(filename, session=None):
J
Joerg Jaspert 已提交
1774
    """
M
Mark Hymers 已提交
1775
    returns DBChange object for given C{filename}.
J
Joerg Jaspert 已提交
1776

J
Joerg Jaspert 已提交
1777 1778
    @type filename: string
    @param filename: the name of the file
J
Joerg Jaspert 已提交
1779 1780 1781 1782 1783

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

J
Joerg Jaspert 已提交
1784 1785
    @rtype: DBChange
    @return:  DBChange object for the given filename (C{None} if not present)
1786

J
Joerg Jaspert 已提交
1787
    """
M
Mark Hymers 已提交
1788
    q = session.query(DBChange).filter_by(changesname=filename)
J
Joerg Jaspert 已提交
1789 1790 1791 1792 1793 1794

    try:
        return q.one()
    except NoResultFound:
        return None

M
Mark Hymers 已提交
1795
__all__.append('get_dbchange')
1796

M
Mark Hymers 已提交
1797 1798
################################################################################

1799
class Location(ORMObject):
1800
    def __init__(self, path = None, component = None):
1801
        self.path = path
1802
        self.component = component
1803 1804
        # the column 'type' should go away, see comment at mapper
        self.archive_type = 'pool'
M
Mark Hymers 已提交
1805

1806
    def properties(self):
1807 1808
        return ['path', 'location_id', 'archive_type', 'component', \
            'files_count']
1809 1810 1811

    def not_null_constraints(self):
        return ['path', 'archive_type']
M
Mark Hymers 已提交
1812

1813 1814
__all__.append('Location')

1815
@session_wrapper
1816 1817 1818 1819 1820 1821
def get_location(location, component=None, archive=None, session=None):
    """
    Returns Location object for the given combination of location, component
    and archive

    @type location: string
J
Joerg Jaspert 已提交
1822
    @param location: the path of the location, e.g. I{/srv/ftp-master.debian.org/ftp/pool/}
1823 1824 1825 1826 1827

    @type component: string
    @param component: the component name (if None, no restriction applied)

    @type archive: string
J
Joerg Jaspert 已提交
1828
    @param archive: the archive name (if None, no restriction applied)
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841

    @rtype: Location / None
    @return: Either a Location object or None if one can't be found
    """

    q = session.query(Location).filter_by(path=location)

    if archive is not None:
        q = q.join(Archive).filter_by(archive_name=archive)

    if component is not None:
        q = q.join(Component).filter_by(component_name=component)

1842 1843 1844 1845
    try:
        return q.one()
    except NoResultFound:
        return None
1846 1847 1848

__all__.append('get_location')

M
Mark Hymers 已提交
1849 1850
################################################################################

1851
class Maintainer(ORMObject):
1852 1853
    def __init__(self, name = None):
        self.name = name
M
Mark Hymers 已提交
1854

1855 1856 1857 1858 1859
    def properties(self):
        return ['name', 'maintainer_id']

    def not_null_constraints(self):
        return ['name']
M
Mark Hymers 已提交
1860

M
Mark Hymers 已提交
1861 1862 1863 1864 1865 1866
    def get_split_maintainer(self):
        if not hasattr(self, 'name') or self.name is None:
            return ('', '', '', '')

        return fix_maintainer(self.name.strip())

1867 1868
__all__.append('Maintainer')

1869
@session_wrapper
M
Mark Hymers 已提交
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
def get_or_set_maintainer(name, session=None):
    """
    Returns Maintainer object for given maintainer name.

    If no matching maintainer name is found, a row is inserted.

    @type name: string
    @param name: The maintainer name to add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.
    A flush will be performed either way.

    @rtype: Maintainer
    @return: the Maintainer object for the given maintainer
    """

1889
    q = session.query(Maintainer).filter_by(name=name)
1890 1891 1892
    try:
        ret = q.one()
    except NoResultFound:
1893 1894 1895
        maintainer = Maintainer()
        maintainer.name = name
        session.add(maintainer)
1896
        session.commit_or_flush()
1897
        ret = maintainer
M
Mark Hymers 已提交
1898

1899
    return ret
M
Mark Hymers 已提交
1900 1901 1902

__all__.append('get_or_set_maintainer')

1903
@session_wrapper
C
Chris Lamb 已提交
1904
def get_maintainer(maintainer_id, session=None):
C
Chris Lamb 已提交
1905
    """
1906 1907
    Return the name of the maintainer behind C{maintainer_id} or None if that
    maintainer_id is invalid.
C
Chris Lamb 已提交
1908 1909 1910 1911

    @type maintainer_id: int
    @param maintainer_id: the id of the maintainer

1912 1913
    @rtype: Maintainer
    @return: the Maintainer with this C{maintainer_id}
C
Chris Lamb 已提交
1914 1915
    """

1916
    return session.query(Maintainer).get(maintainer_id)
C
Chris Lamb 已提交
1917 1918 1919

__all__.append('get_maintainer')

M
Mark Hymers 已提交
1920 1921
################################################################################

M
Mark Hymers 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930
class NewComment(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '''<NewComment for '%s %s' (%s)>''' % (self.package, self.version, self.comment_id)

__all__.append('NewComment')

1931
@session_wrapper
M
Mark Hymers 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
def has_new_comment(package, version, session=None):
    """
    Returns true if the given combination of C{package}, C{version} has a comment.

    @type package: string
    @param package: name of the package

    @type version: string
    @param version: package version

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: boolean
    @return: true/false
    """

    q = session.query(NewComment)
    q = q.filter_by(package=package)
    q = q.filter_by(version=version)
1953

1954
    return bool(q.count() > 0)
M
Mark Hymers 已提交
1955 1956 1957

__all__.append('has_new_comment')

1958
@session_wrapper
M
Mark Hymers 已提交
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
def get_new_comments(package=None, version=None, comment_id=None, session=None):
    """
    Returns (possibly empty) list of NewComment objects for the given
    parameters

    @type package: string (optional)
    @param package: name of the package

    @type version: string (optional)
    @param version: package version

    @type comment_id: int (optional)
    @param comment_id: An id of a comment

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: A (possibly empty) list of NewComment objects will be returned
    """

    q = session.query(NewComment)
    if package is not None: q = q.filter_by(package=package)
    if version is not None: q = q.filter_by(version=version)
    if comment_id is not None: q = q.filter_by(comment_id=comment_id)

1986
    return q.all()
M
Mark Hymers 已提交
1987 1988 1989 1990 1991

__all__.append('get_new_comments')

################################################################################

1992 1993 1994 1995 1996 1997 1998 1999 2000
class Override(ORMObject):
    def __init__(self, package = None, suite = None, component = None, overridetype = None, \
        section = None, priority = None):
        self.package = package
        self.suite = suite
        self.component = component
        self.overridetype = overridetype
        self.section = section
        self.priority = priority
M
Mark Hymers 已提交
2001

2002 2003 2004 2005 2006 2007
    def properties(self):
        return ['package', 'suite', 'component', 'overridetype', 'section', \
            'priority']

    def not_null_constraints(self):
        return ['package', 'suite', 'component', 'overridetype', 'section']
M
Mark Hymers 已提交
2008

2009 2010
__all__.append('Override')

2011
@session_wrapper
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
def get_override(package, suite=None, component=None, overridetype=None, session=None):
    """
    Returns Override object for the given parameters

    @type package: string
    @param package: The name of the package

    @type suite: string, list or None
    @param suite: The name of the suite (or suites if a list) to limit to.  If
                  None, don't limit.  Defaults to None.

    @type component: string, list or None
    @param component: The name of the component (or components if a list) to
                      limit to.  If None, don't limit.  Defaults to None.

    @type overridetype: string, list or None
    @param overridetype: The name of the overridetype (or overridetypes if a list) to
                         limit to.  If None, don't limit.  Defaults to None.

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: A (possibly empty) list of Override objects will be returned
    """

    q = session.query(Override)
    q = q.filter_by(package=package)

    if suite is not None:
        if not isinstance(suite, list): suite = [suite]
        q = q.join(Suite).filter(Suite.suite_name.in_(suite))

    if component is not None:
        if not isinstance(component, list): component = [component]
        q = q.join(Component).filter(Component.component_name.in_(component))

    if overridetype is not None:
        if not isinstance(overridetype, list): overridetype = [overridetype]
        q = q.join(OverrideType).filter(OverrideType.overridetype.in_(overridetype))

2054
    return q.all()
2055 2056 2057 2058

__all__.append('get_override')


M
Mark Hymers 已提交
2059 2060
################################################################################

2061 2062 2063
class OverrideType(ORMObject):
    def __init__(self, overridetype = None):
        self.overridetype = overridetype
M
Mark Hymers 已提交
2064

2065
    def properties(self):
2066
        return ['overridetype', 'overridetype_id', 'overrides_count']
2067 2068 2069

    def not_null_constraints(self):
        return ['overridetype']
M
Mark Hymers 已提交
2070

2071 2072
__all__.append('OverrideType')

2073
@session_wrapper
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
def get_override_type(override_type, session=None):
    """
    Returns OverrideType object for given C{override type}.

    @type override_type: string
    @param override_type: The name of the override type

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: int
    @return: the database id for the given override type
    """
2088

M
Mark Hymers 已提交
2089
    q = session.query(OverrideType).filter_by(overridetype=override_type)
2090

2091 2092 2093 2094
    try:
        return q.one()
    except NoResultFound:
        return None
2095

2096 2097
__all__.append('get_override_type')

M
Mark Hymers 已提交
2098 2099
################################################################################

2100 2101 2102 2103 2104 2105 2106 2107 2108
class PolicyQueue(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<PolicyQueue %s>' % self.queue_name

__all__.append('PolicyQueue')

2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
@session_wrapper
def get_policy_queue(queuename, session=None):
    """
    Returns PolicyQueue object for given C{queue name}

    @type queuename: string
    @param queuename: The name of the queue

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: PolicyQueue
    @return: PolicyQueue object for the given queue
    """

    q = session.query(PolicyQueue).filter_by(queue_name=queuename)

    try:
        return q.one()
    except NoResultFound:
        return None

__all__.append('get_policy_queue')

M
Mark Hymers 已提交
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
@session_wrapper
def get_policy_queue_from_path(pathname, session=None):
    """
    Returns PolicyQueue object for given C{path name}

    @type queuename: string
    @param queuename: The path

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: PolicyQueue
    @return: PolicyQueue object for the given queue
    """

    q = session.query(PolicyQueue).filter_by(path=pathname)

    try:
        return q.one()
    except NoResultFound:
        return None

__all__.append('get_policy_queue_from_path')

2159 2160
################################################################################

2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
class Priority(ORMObject):
    def __init__(self, priority = None, level = None):
        self.priority = priority
        self.level = level

    def properties(self):
        return ['priority', 'priority_id', 'level', 'overrides_count']

    def not_null_constraints(self):
        return ['priority', 'level']
M
Mark Hymers 已提交
2171

2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.priority == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.priority != val)
        # This signals to use the normal comparison operator
        return NotImplemented

2184 2185
__all__.append('Priority')

2186
@session_wrapper
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
def get_priority(priority, session=None):
    """
    Returns Priority object for given C{priority name}.

    @type priority: string
    @param priority: The name of the priority

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Priority
    @return: Priority object for the given priority
    """
2201

2202
    q = session.query(Priority).filter_by(priority=priority)
2203

2204 2205 2206 2207
    try:
        return q.one()
    except NoResultFound:
        return None
2208

2209 2210
__all__.append('get_priority')

2211
@session_wrapper
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
def get_priorities(session=None):
    """
    Returns dictionary of priority names -> id mappings

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: dictionary
    @return: dictionary of priority names -> id mappings
    """

    ret = {}
    q = session.query(Priority)
    for x in q.all():
        ret[x.priority] = x.priority_id

    return ret

__all__.append('get_priorities')

M
Mark Hymers 已提交
2233 2234
################################################################################

2235 2236 2237 2238 2239 2240 2241 2242 2243
class Section(ORMObject):
    def __init__(self, section = None):
        self.section = section

    def properties(self):
        return ['section', 'section_id', 'overrides_count']

    def not_null_constraints(self):
        return ['section']
M
Mark Hymers 已提交
2244

2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.section == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.section != val)
        # This signals to use the normal comparison operator
        return NotImplemented

2257 2258
__all__.append('Section')

2259
@session_wrapper
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
def get_section(section, session=None):
    """
    Returns Section object for given C{section name}.

    @type section: string
    @param section: The name of the section

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Section
    @return: Section object for the given section name
    """
2274

2275
    q = session.query(Section).filter_by(section=section)
2276

2277 2278 2279 2280
    try:
        return q.one()
    except NoResultFound:
        return None
2281

2282 2283
__all__.append('get_section')

2284
@session_wrapper
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
def get_sections(session=None):
    """
    Returns dictionary of section names -> id mappings

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: dictionary
    @return: dictionary of section names -> id mappings
    """

    ret = {}
    q = session.query(Section)
    for x in q.all():
        ret[x.section] = x.section_id

    return ret

__all__.append('get_sections')

M
Mark Hymers 已提交
2306 2307
################################################################################

2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
class SrcContents(ORMObject):
    def __init__(self, file = None, source = None):
        self.file = file
        self.source = source

    def properties(self):
        return ['file', 'source']

__all__.append('SrcContents')

################################################################################

M
Mark Hymers 已提交
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
from debian.debfile import Deb822

# Temporary Deb822 subclass to fix bugs with : handling; see #597249
class Dak822(Deb822):
    def _internal_parser(self, sequence, fields=None):
        # The key is non-whitespace, non-colon characters before any colon.
        key_part = r"^(?P<key>[^: \t\n\r\f\v]+)\s*:\s*"
        single = re.compile(key_part + r"(?P<data>\S.*?)\s*$")
        multi = re.compile(key_part + r"$")
        multidata = re.compile(r"^\s(?P<data>.+?)\s*$")

        wanted_field = lambda f: fields is None or f in fields

        if isinstance(sequence, basestring):
            sequence = sequence.splitlines()

        curkey = None
        content = ""
        for line in self.gpg_stripped_paragraph(sequence):
            m = single.match(line)
            if m:
                if curkey:
                    self[curkey] = content

                if not wanted_field(m.group('key')):
                    curkey = None
                    continue

                curkey = m.group('key')
                content = m.group('data')
                continue

            m = multi.match(line)
            if m:
                if curkey:
                    self[curkey] = content

                if not wanted_field(m.group('key')):
                    curkey = None
                    continue

                curkey = m.group('key')
                content = ""
                continue

            m = multidata.match(line)
            if m:
                content += '\n' + line # XXX not m.group('data')?
                continue

        if curkey:
            self[curkey] = content


2374
class DBSource(ORMObject):
T
Torsten Werner 已提交
2375 2376 2377 2378
    def __init__(self, source = None, version = None, maintainer = None, \
        changedby = None, poolfile = None, install_date = None):
        self.source = source
        self.version = version
2379 2380
        self.maintainer = maintainer
        self.changedby = changedby
T
Torsten Werner 已提交
2381 2382
        self.poolfile = poolfile
        self.install_date = install_date
M
Mark Hymers 已提交
2383

M
Mark Hymers 已提交
2384 2385 2386 2387
    @property
    def pkid(self):
        return self.source_id

2388 2389 2390
    def properties(self):
        return ['source', 'source_id', 'maintainer', 'changedby', \
            'fingerprint', 'poolfile', 'version', 'suites_count', \
2391
            'install_date', 'binaries_count', 'uploaders_count']
2392 2393

    def not_null_constraints(self):
2394 2395
        return ['source', 'version', 'install_date', 'maintainer', \
            'changedby', 'poolfile', 'install_date']
M
Mark Hymers 已提交
2396

M
Mark Hymers 已提交
2397
    def read_control_fields(self):
M
Mark Hymers 已提交
2398 2399 2400 2401
        '''
        Reads the control information from a dsc

        @rtype: tuple
M
Mark Hymers 已提交
2402
        @return: fields is the dsc information in a dictionary form
M
Mark Hymers 已提交
2403 2404
        '''
        fullpath = self.poolfile.fullpath
M
Mark Hymers 已提交
2405
        fields = Dak822(open(self.poolfile.fullpath, 'r'))
M
Mark Hymers 已提交
2406 2407
        return fields

2408 2409
    metadata = association_proxy('key', 'value')

2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
    def scan_contents(self):
        '''
        Returns a set of names for non directories. The path names are
        normalized after converting them from either utf-8 or iso8859-1
        encoding.
        '''
        fullpath = self.poolfile.fullpath
        from daklib.contents import UnpackedSource
        unpacked = UnpackedSource(fullpath)
        fileset = set()
        for name in unpacked.get_all_filenames():
            # enforce proper utf-8 encoding
            try:
                name.decode('utf-8')
            except UnicodeDecodeError:
                name = name.decode('iso8859-1').encode('utf-8')
            fileset.add(name)
        return fileset

2429
__all__.append('DBSource')
2430

2431
@session_wrapper
2432 2433 2434 2435 2436 2437 2438
def source_exists(source, source_version, suites = ["any"], session=None):
    """
    Ensure that source exists somewhere in the archive for the binary
    upload being processed.
      1. exact match     => 1.0-3
      2. bin-only NMU    => 1.0-3+b1 , 1.0-3.1+b1

J
Joerg Jaspert 已提交
2439 2440
    @type source: string
    @param source: source name
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457

    @type source_version: string
    @param source_version: expected source version

    @type suites: list
    @param suites: list of suites to check in, default I{any}

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: int
    @return: returns 1 if a source with expected version is found, otherwise 0

    """

    cnf = Config()
2458 2459 2460 2461
    ret = True

    from daklib.regexes import re_bin_only_nmu
    orig_source_version = re_bin_only_nmu.sub('', source_version)
2462 2463

    for suite in suites:
2464 2465
        q = session.query(DBSource).filter_by(source=source). \
            filter(DBSource.version.in_([source_version, orig_source_version]))
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
        if suite != "any":
            # source must exist in suite X, or in some other suite that's
            # mapped to X, recursively... silent-maps are counted too,
            # unreleased-maps aren't.
            maps = cnf.ValueList("SuiteMappings")[:]
            maps.reverse()
            maps = [ m.split() for m in maps ]
            maps = [ (x[1], x[2]) for x in maps
                            if x[0] == "map" or x[0] == "silent-map" ]
            s = [suite]
J
Joerg Jaspert 已提交
2476 2477 2478
            for (from_, to) in maps:
                if from_ in s and to not in s:
                    s.append(to)
2479

2480
            q = q.filter(DBSource.suites.any(Suite.suite_name.in_(s)))
2481

2482
        if q.count() > 0:
2483 2484 2485
            continue

        # No source found so return not ok
2486
        ret = False
2487 2488

    return ret
2489 2490 2491

__all__.append('source_exists')

2492
@session_wrapper
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
def get_suites_source_in(source, session=None):
    """
    Returns list of Suite objects which given C{source} name is in

    @type source: str
    @param source: DBSource package name to search for

    @rtype: list
    @return: list of Suite objects for the given source
    """

2504
    return session.query(Suite).filter(Suite.sources.any(source=source)).all()
2505 2506 2507

__all__.append('get_suites_source_in')

2508
@session_wrapper
2509
def get_sources_from_name(source, version=None, dm_upload_allowed=None, session=None):
M
Mark Hymers 已提交
2510
    """
2511
    Returns list of DBSource objects for given C{source} name and other parameters
M
Mark Hymers 已提交
2512 2513

    @type source: str
2514
    @param source: DBSource package name to search for
M
Mark Hymers 已提交
2515

J
Joerg Jaspert 已提交
2516 2517
    @type version: str or None
    @param version: DBSource version name to search for or None if not applicable
2518

2519 2520 2521 2522
    @type dm_upload_allowed: bool
    @param dm_upload_allowed: If None, no effect.  If True or False, only
    return packages with that dm_upload_allowed setting

M
Mark Hymers 已提交
2523 2524 2525 2526 2527
    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
2528
    @return: list of DBSource objects for the given name (may be empty)
M
Mark Hymers 已提交
2529
    """
2530 2531

    q = session.query(DBSource).filter_by(source=source)
2532 2533 2534 2535

    if version is not None:
        q = q.filter_by(version=version)

2536 2537 2538
    if dm_upload_allowed is not None:
        q = q.filter_by(dm_upload_allowed=dm_upload_allowed)

2539
    return q.all()
M
Mark Hymers 已提交
2540

2541 2542
__all__.append('get_sources_from_name')

T
Torsten Werner 已提交
2543 2544
# FIXME: This function fails badly if it finds more than 1 source package and
# its implementation is trivial enough to be inlined.
2545
@session_wrapper
2546 2547
def get_source_in_suite(source, suite, session=None):
    """
2548
    Returns a DBSource object for a combination of C{source} and C{suite}.
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562

      - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
      - B{suite} - a suite name, eg. I{unstable}

    @type source: string
    @param source: source package name

    @type suite: string
    @param suite: the suite name

    @rtype: string
    @return: the version for I{source} in I{suite}

    """
2563

T
Torsten Werner 已提交
2564
    q = get_suite(suite, session).get_sources(source)
2565
    try:
2566
        return q.one()
2567 2568
    except NoResultFound:
        return None
2569

2570 2571
__all__.append('get_source_in_suite')

M
Mark Hymers 已提交
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
@session_wrapper
def import_metadata_into_db(obj, session=None):
    """
    This routine works on either DBBinary or DBSource objects and imports
    their metadata into the database
    """
    fields = obj.read_control_fields()
    for k in fields.keys():
        try:
            # Try raw ASCII
            val = str(fields[k])
        except UnicodeEncodeError:
            # Fall back to UTF-8
            try:
                val = fields[k].encode('utf-8')
            except UnicodeEncodeError:
                # Finally try iso8859-1
                val = fields[k].encode('iso8859-1')
                # Otherwise we allow the exception to percolate up and we cause
                # a reject as someone is playing silly buggers

        obj.metadata[get_or_set_metadatakey(k, session)] = val

    session.commit_or_flush()

__all__.append('import_metadata_into_db')


M
Mark Hymers 已提交
2600 2601
################################################################################

2602 2603 2604 2605
@session_wrapper
def add_dsc_to_db(u, filename, session=None):
    entry = u.pkg.files[filename]
    source = DBSource()
2606
    pfs = []
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623

    source.source = u.pkg.dsc["source"]
    source.version = u.pkg.dsc["version"] # NB: not files[file]["version"], that has no epoch
    source.maintainer_id = get_or_set_maintainer(u.pkg.dsc["maintainer"], session).maintainer_id
    source.changedby_id = get_or_set_maintainer(u.pkg.changes["changed-by"], session).maintainer_id
    source.fingerprint_id = get_or_set_fingerprint(u.pkg.changes["fingerprint"], session).fingerprint_id
    source.install_date = datetime.now().date()

    dsc_component = entry["component"]
    dsc_location_id = entry["location id"]

    source.dm_upload_allowed = (u.pkg.dsc.get("dm-upload-allowed", '') == "yes")

    # Set up a new poolfile if necessary
    if not entry.has_key("files id") or not entry["files id"]:
        filename = entry["pool name"] + filename
        poolfile = add_poolfile(filename, entry, dsc_location_id, session)
F
Frank Lichtenheld 已提交
2624
        session.flush()
2625
        pfs.append(poolfile)
2626 2627 2628 2629 2630
        entry["files id"] = poolfile.file_id

    source.poolfile_id = entry["files id"]
    session.add(source)

T
Torsten Werner 已提交
2631 2632 2633
    suite_names = u.pkg.changes["distribution"].keys()
    source.suites = session.query(Suite). \
        filter(Suite.suite_name.in_(suite_names)).all()
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663

    # Add the source files to the DB (files and dsc_files)
    dscfile = DSCFile()
    dscfile.source_id = source.source_id
    dscfile.poolfile_id = entry["files id"]
    session.add(dscfile)

    for dsc_file, dentry in u.pkg.dsc_files.items():
        df = DSCFile()
        df.source_id = source.source_id

        # If the .orig tarball is already in the pool, it's
        # files id is stored in dsc_files by check_dsc().
        files_id = dentry.get("files id", None)

        # Find the entry in the files hash
        # TODO: Bail out here properly
        dfentry = None
        for f, e in u.pkg.files.items():
            if f == dsc_file:
                dfentry = e
                break

        if files_id is None:
            filename = dfentry["pool name"] + dsc_file

            (found, obj) = check_poolfile(filename, dentry["size"], dentry["md5sum"], dsc_location_id)
            # FIXME: needs to check for -1/-2 and or handle exception
            if found and obj is not None:
                files_id = obj.file_id
2664
                pfs.append(obj)
2665 2666 2667 2668 2669 2670 2671

            # If still not found, add it
            if files_id is None:
                # HACK: Force sha1sum etc into dentry
                dentry["sha1sum"] = dfentry["sha1sum"]
                dentry["sha256sum"] = dfentry["sha256sum"]
                poolfile = add_poolfile(filename, dentry, dsc_location_id, session)
2672
                pfs.append(poolfile)
2673
                files_id = poolfile.file_id
2674 2675 2676 2677 2678
        else:
            poolfile = get_poolfile_by_id(files_id, session)
            if poolfile is None:
                utils.fubar("INTERNAL ERROR. Found no poolfile with id %d" % files_id)
            pfs.append(poolfile)
2679 2680 2681 2682 2683

        df.poolfile_id = files_id
        session.add(df)

    # Add the src_uploaders to the DB
2684
    source.uploaders = [source.maintainer]
2685
    if u.pkg.dsc.has_key("uploaders"):
2686
        for up in u.pkg.dsc["uploaders"].replace(">, ", ">\t").split("\t"):
2687
            up = up.strip()
2688
            source.uploaders.append(get_or_set_maintainer(up, session))
2689 2690 2691

    session.flush()

M
Mark Hymers 已提交
2692
    return source, dsc_component, dsc_location_id, pfs
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717

__all__.append('add_dsc_to_db')

@session_wrapper
def add_deb_to_db(u, filename, session=None):
    """
    Contrary to what you might expect, this routine deals with both
    debs and udebs.  That info is in 'dbtype', whilst 'type' is
    'deb' for both of them
    """
    cnf = Config()
    entry = u.pkg.files[filename]

    bin = DBBinary()
    bin.package = entry["package"]
    bin.version = entry["version"]
    bin.maintainer_id = get_or_set_maintainer(entry["maintainer"], session).maintainer_id
    bin.fingerprint_id = get_or_set_fingerprint(u.pkg.changes["fingerprint"], session).fingerprint_id
    bin.arch_id = get_architecture(entry["architecture"], session).arch_id
    bin.binarytype = entry["dbtype"]

    # Find poolfile id
    filename = entry["pool name"] + filename
    fullpath = os.path.join(cnf["Dir::Pool"], filename)
    if not entry.get("location id", None):
2718
        entry["location id"] = get_location(cnf["Dir::Pool"], entry["component"], session=session).location_id
2719

2720 2721 2722 2723
    if entry.get("files id", None):
        poolfile = get_poolfile_by_id(bin.poolfile_id)
        bin.poolfile_id = entry["files id"]
    else:
2724
        poolfile = add_poolfile(filename, entry, entry["location id"], session)
2725
        bin.poolfile_id = entry["files id"] = poolfile.file_id
2726 2727 2728 2729 2730

    # Find source id
    bin_sources = get_sources_from_name(entry["source package"], entry["source version"], session=session)
    if len(bin_sources) != 1:
        raise NoSourceFieldError, "Unable to find a unique source id for %s (%s), %s, file %s, type %s, signed by %s" % \
2731
                                  (bin.package, bin.version, entry["architecture"],
2732 2733 2734 2735
                                   filename, bin.binarytype, u.pkg.changes["fingerprint"])

    bin.source_id = bin_sources[0].source_id

M
Mark Hymers 已提交
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
    if entry.has_key("built-using"):
        for srcname, version in entry["built-using"]:
            exsources = get_sources_from_name(srcname, version, session=session)
            if len(exsources) != 1:
                raise NoSourceFieldError, "Unable to find source package (%s = %s) in Built-Using for %s (%s), %s, file %s, type %s, signed by %s" % \
                                          (srcname, version, bin.package, bin.version, entry["architecture"],
                                           filename, bin.binarytype, u.pkg.changes["fingerprint"])

            bin.extra_sources.append(exsources[0])

2746 2747 2748
    # Add and flush object so it has an ID
    session.add(bin)

2749 2750 2751
    suite_names = u.pkg.changes["distribution"].keys()
    bin.suites = session.query(Suite). \
        filter(Suite.suite_name.in_(suite_names)).all()
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761

    session.flush()

    # Deal with contents - disabled for now
    #contents = copy_temporary_contents(bin.package, bin.version, bin.architecture.arch_string, os.path.basename(filename), None, session)
    #if not contents:
    #    print "REJECT\nCould not determine contents of package %s" % bin.package
    #    session.rollback()
    #    raise MissingContents, "No contents stored for package %s, and couldn't determine contents of %s" % (bin.package, filename)

M
Mark Hymers 已提交
2762
    return bin, poolfile
2763

2764 2765 2766 2767
__all__.append('add_deb_to_db')

################################################################################

2768 2769 2770 2771
class SourceACL(object):
    def __init__(self, *args, **kwargs):
        pass

2772 2773 2774
    def __repr__(self):
        return '<SourceACL %s>' % self.source_acl_id

2775 2776 2777 2778
__all__.append('SourceACL')

################################################################################

2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789
class SrcFormat(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<SrcFormat %s>' % (self.format_name)

__all__.append('SrcFormat')

################################################################################

M
Mark Hymers 已提交
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
SUITE_FIELDS = [ ('SuiteName', 'suite_name'),
                 ('SuiteID', 'suite_id'),
                 ('Version', 'version'),
                 ('Origin', 'origin'),
                 ('Label', 'label'),
                 ('Description', 'description'),
                 ('Untouchable', 'untouchable'),
                 ('Announce', 'announce'),
                 ('Codename', 'codename'),
                 ('OverrideCodename', 'overridecodename'),
                 ('ValidTime', 'validtime'),
                 ('Priority', 'priority'),
                 ('NotAutomatic', 'notautomatic'),
                 ('CopyChanges', 'copychanges'),
J
Joerg Jaspert 已提交
2804
                 ('OverrideSuite', 'overridesuite')]
M
Mark Hymers 已提交
2805

T
Torsten Werner 已提交
2806 2807
# Why the heck don't we have any UNIQUE constraints in table suite?
# TODO: Add UNIQUE constraints for appropriate columns.
2808
class Suite(ORMObject):
2809 2810 2811
    def __init__(self, suite_name = None, version = None):
        self.suite_name = suite_name
        self.version = version
M
Mark Hymers 已提交
2812

2813
    def properties(self):
T
Torsten Werner 已提交
2814 2815
        return ['suite_name', 'version', 'sources_count', 'binaries_count', \
            'overrides_count']
2816 2817

    def not_null_constraints(self):
M
Mark Hymers 已提交
2818
        return ['suite_name']
M
Mark Hymers 已提交
2819

2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.suite_name == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.suite_name != val)
        # This signals to use the normal comparison operator
        return NotImplemented

M
Mark Hymers 已提交
2832 2833 2834 2835 2836 2837 2838 2839 2840
    def details(self):
        ret = []
        for disp, field in SUITE_FIELDS:
            val = getattr(self, field, None)
            if val is not None:
                ret.append("%s: %s" % (disp, val))

        return "\n".join(ret)

2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
    def get_architectures(self, skipsrc=False, skipall=False):
        """
        Returns list of Architecture objects

        @type skipsrc: boolean
        @param skipsrc: Whether to skip returning the 'source' architecture entry
        (Default False)

        @type skipall: boolean
        @param skipall: Whether to skip returning the 'all' architecture entry
        (Default False)

        @rtype: list
        @return: list of Architecture objects for the given name (may be empty)
        """

2857
        q = object_session(self).query(Architecture).with_parent(self)
2858 2859 2860 2861 2862 2863
        if skipsrc:
            q = q.filter(Architecture.arch_string != 'source')
        if skipall:
            q = q.filter(Architecture.arch_string != 'all')
        return q.order_by(Architecture.arch_string).all()

T
Torsten Werner 已提交
2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
    def get_sources(self, source):
        """
        Returns a query object representing DBSource that is part of C{suite}.

          - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}

        @type source: string
        @param source: source package name

        @rtype: sqlalchemy.orm.query.Query
        @return: a query of DBSource

        """

        session = object_session(self)
        return session.query(DBSource).filter_by(source = source). \
2880
            with_parent(self)
T
Torsten Werner 已提交
2881

2882 2883 2884 2885 2886 2887
    def get_overridesuite(self):
        if self.overridesuite is None:
            return self
        else:
            return object_session(self).query(Suite).filter_by(suite_name=self.overridesuite).one()

2888 2889
__all__.append('Suite')

2890
@session_wrapper
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
def get_suite(suite, session=None):
    """
    Returns Suite object for given C{suite name}.

    @type suite: string
    @param suite: The name of the suite

    @type session: Session
    @param session: Optional SQLA session object (a temporary one will be
    generated if not supplied)

    @rtype: Suite
F
Frank Lichtenheld 已提交
2903
    @return: Suite object for the requested suite name (None if not present)
2904
    """
2905

2906
    q = session.query(Suite).filter_by(suite_name=suite)
2907

2908 2909 2910 2911
    try:
        return q.one()
    except NoResultFound:
        return None
2912

2913 2914
__all__.append('get_suite')

M
Mark Hymers 已提交
2915 2916
################################################################################

2917
# TODO: should be removed because the implementation is too trivial
2918
@session_wrapper
2919
def get_suite_architectures(suite, skipsrc=False, skipall=False, session=None):
M
Mark Hymers 已提交
2920 2921 2922
    """
    Returns list of Architecture objects for given C{suite} name

J
Joerg Jaspert 已提交
2923 2924
    @type suite: str
    @param suite: Suite name to search for
M
Mark Hymers 已提交
2925

2926 2927 2928 2929 2930 2931 2932 2933
    @type skipsrc: boolean
    @param skipsrc: Whether to skip returning the 'source' architecture entry
    (Default False)

    @type skipall: boolean
    @param skipall: Whether to skip returning the 'all' architecture entry
    (Default False)

M
Mark Hymers 已提交
2934 2935 2936 2937 2938 2939 2940 2941
    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: list of Architecture objects for the given name (may be empty)
    """

2942
    return get_suite(suite, session).get_architectures(skipsrc, skipall)
M
Mark Hymers 已提交
2943

2944
__all__.append('get_suite_architectures')
M
Mark Hymers 已提交
2945

M
Mark Hymers 已提交
2946 2947
################################################################################

2948 2949 2950 2951 2952 2953 2954 2955 2956
class SuiteSrcFormat(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<SuiteSrcFormat (%s, %s)>' % (self.suite_id, self.src_format_id)

__all__.append('SuiteSrcFormat')

2957
@session_wrapper
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
def get_suite_src_formats(suite, session=None):
    """
    Returns list of allowed SrcFormat for C{suite}.

    @type suite: str
    @param suite: Suite name to search for

    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
    @return: the list of allowed source formats for I{suite}
    """

    q = session.query(SrcFormat)
    q = q.join(SuiteSrcFormat)
    q = q.join(Suite).filter_by(suite_name=suite)
    q = q.order_by('format_name')

2978
    return q.all()
2979 2980 2981 2982 2983

__all__.append('get_suite_src_formats')

################################################################################

2984
class Uid(ORMObject):
T
Torsten Werner 已提交
2985 2986 2987
    def __init__(self, uid = None, name = None):
        self.uid = uid
        self.name = name
M
Mark Hymers 已提交
2988

2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.uid == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
            return (self.uid != val)
        # This signals to use the normal comparison operator
        return NotImplemented

3001 3002 3003 3004 3005
    def properties(self):
        return ['uid', 'name', 'fingerprint']

    def not_null_constraints(self):
        return ['uid']
M
Mark Hymers 已提交
3006

3007 3008
__all__.append('Uid')

3009
@session_wrapper
M
Mark Hymers 已提交
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026
def get_or_set_uid(uidname, session=None):
    """
    Returns uid object for given uidname.

    If no matching uidname is found, a row is inserted.

    @type uidname: string
    @param uidname: The uid to add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.

    @rtype: Uid
    @return: the uid object for the given uidname
    """
3027 3028 3029

    q = session.query(Uid).filter_by(uid=uidname)

3030 3031 3032
    try:
        ret = q.one()
    except NoResultFound:
3033 3034 3035
        uid = Uid()
        uid.uid = uidname
        session.add(uid)
3036
        session.commit_or_flush()
3037
        ret = uid
M
Mark Hymers 已提交
3038

3039
    return ret
M
Mark Hymers 已提交
3040 3041 3042

__all__.append('get_or_set_uid')

3043
@session_wrapper
3044 3045 3046 3047
def get_uid_from_fingerprint(fpr, session=None):
    q = session.query(Uid)
    q = q.join(Fingerprint).filter_by(fingerprint=fpr)

3048 3049 3050 3051
    try:
        return q.one()
    except NoResultFound:
        return None
3052 3053 3054

__all__.append('get_uid_from_fingerprint')

M
Mark Hymers 已提交
3055 3056
################################################################################

3057 3058 3059 3060
class UploadBlock(object):
    def __init__(self, *args, **kwargs):
        pass

3061 3062 3063
    def __repr__(self):
        return '<UploadBlock %s (%s)>' % (self.source, self.upload_block_id)

3064 3065 3066 3067
__all__.append('UploadBlock')

################################################################################

T
Torsten Werner 已提交
3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
class MetadataKey(ORMObject):
    def __init__(self, key = None):
        self.key = key

    def properties(self):
        return ['key']

    def not_null_constraints(self):
        return ['key']

__all__.append('MetadataKey')

M
Mark Hymers 已提交
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111
@session_wrapper
def get_or_set_metadatakey(keyname, session=None):
    """
    Returns MetadataKey object for given uidname.

    If no matching keyname is found, a row is inserted.

    @type uidname: string
    @param uidname: The keyname to add

    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied).  If not passed, a commit will be performed at
    the end of the function, otherwise the caller is responsible for commiting.

    @rtype: MetadataKey
    @return: the metadatakey object for the given keyname
    """

    q = session.query(MetadataKey).filter_by(key=keyname)

    try:
        ret = q.one()
    except NoResultFound:
        ret = MetadataKey(keyname)
        session.add(ret)
        session.commit_or_flush()

    return ret

__all__.append('get_or_set_metadatakey')

T
Torsten Werner 已提交
3112 3113 3114
################################################################################

class BinaryMetadata(ORMObject):
3115
    def __init__(self, key = None, value = None, binary = None):
T
Torsten Werner 已提交
3116 3117
        self.key = key
        self.value = value
3118
        self.binary = binary
T
Torsten Werner 已提交
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130

    def properties(self):
        return ['binary', 'key', 'value']

    def not_null_constraints(self):
        return ['value']

__all__.append('BinaryMetadata')

################################################################################

class SourceMetadata(ORMObject):
3131
    def __init__(self, key = None, value = None, source = None):
T
Torsten Werner 已提交
3132 3133
        self.key = key
        self.value = value
3134
        self.source = source
T
Torsten Werner 已提交
3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145

    def properties(self):
        return ['source', 'key', 'value']

    def not_null_constraints(self):
        return ['value']

__all__.append('SourceMetadata')

################################################################################

3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
class VersionCheck(ORMObject):
    def __init__(self, *args, **kwargs):
	pass

    def properties(self):
        #return ['suite_id', 'check', 'reference_id']
        return ['check']

    def not_null_constraints(self):
        return ['suite', 'check', 'reference']

__all__.append('VersionCheck')

@session_wrapper
def get_version_checks(suite_name, check = None, session = None):
    suite = get_suite(suite_name, session)
    if not suite:
M
Mark Hymers 已提交
3163 3164 3165
        # Make sure that what we return is iterable so that list comprehensions
        # involving this don't cause a traceback
        return []
3166 3167 3168 3169 3170 3171 3172 3173 3174
    q = session.query(VersionCheck).filter_by(suite=suite)
    if check:
        q = q.filter_by(check=check)
    return q.all()

__all__.append('get_version_checks')

################################################################################

3175
class DBConn(object):
M
Mark Hymers 已提交
3176
    """
3177
    database module init.
M
Mark Hymers 已提交
3178
    """
3179 3180
    __shared_state = {}

M
Mark Hymers 已提交
3181
    def __init__(self, *args, **kwargs):
3182
        self.__dict__ = self.__shared_state
M
Mark Hymers 已提交
3183

3184 3185 3186 3187
        if not getattr(self, 'initialised', False):
            self.initialised = True
            self.debug = kwargs.has_key('debug')
            self.__createconn()
M
Mark Hymers 已提交
3188

M
Mark Hymers 已提交
3189
    def __setuptables(self):
T
Torsten Werner 已提交
3190
        tables = (
C
Chris Lamb 已提交
3191 3192 3193
            'architecture',
            'archive',
            'bin_associations',
T
Torsten Werner 已提交
3194
            'bin_contents',
C
Chris Lamb 已提交
3195
            'binaries',
T
Torsten Werner 已提交
3196
            'binaries_metadata',
C
Chris Lamb 已提交
3197 3198 3199
            'binary_acl',
            'binary_acl_map',
            'build_queue',
3200
            'build_queue_files',
3201
            'build_queue_policy_files',
3202
            'changelogs_text',
3203
            'changes',
C
Chris Lamb 已提交
3204 3205 3206 3207 3208
            'component',
            'config',
            'changes_pending_binaries',
            'changes_pending_files',
            'changes_pending_source',
T
Torsten Werner 已提交
3209 3210 3211
            'changes_pending_files_map',
            'changes_pending_source_files',
            'changes_pool_files',
C
Chris Lamb 已提交
3212
            'dsc_files',
A
Ansgar Burchardt 已提交
3213
            'external_overrides',
T
Torsten Werner 已提交
3214
            'extra_src_references',
C
Chris Lamb 已提交
3215 3216 3217 3218 3219 3220
            'files',
            'fingerprint',
            'keyrings',
            'keyring_acl_map',
            'location',
            'maintainer',
T
Torsten Werner 已提交
3221
            'metadata_keys',
C
Chris Lamb 已提交
3222
            'new_comments',
T
Torsten Werner 已提交
3223 3224
            # TODO: the maintainer column in table override should be removed.
            'override',
C
Chris Lamb 已提交
3225 3226 3227 3228 3229 3230
            'override_type',
            'policy_queue',
            'priority',
            'section',
            'source',
            'source_acl',
T
Torsten Werner 已提交
3231
            'source_metadata',
C
Chris Lamb 已提交
3232
            'src_associations',
3233
            'src_contents',
C
Chris Lamb 已提交
3234 3235 3236 3237 3238
            'src_format',
            'src_uploaders',
            'suite',
            'suite_architectures',
            'suite_build_queue_copy',
T
Torsten Werner 已提交
3239 3240 3241
            'suite_src_formats',
            'uid',
            'upload_blocks',
3242
            'version_check',
C
Chris Lamb 已提交
3243 3244
        )

3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
        views = (
            'almost_obsolete_all_associations',
            'almost_obsolete_src_associations',
            'any_associations_source',
            'bin_associations_binaries',
            'binaries_suite_arch',
            'binfiles_suite_component_arch',
            'changelogs',
            'file_arch_suite',
            'newest_all_associations',
            'newest_any_associations',
            'newest_source',
            'newest_src_association',
            'obsolete_all_associations',
            'obsolete_any_associations',
            'obsolete_any_by_all_associations',
            'obsolete_src_associations',
            'source_suite',
            'src_associations_bin',
            'src_associations_src',
            'suite_arch_by_name',
        )

T
Torsten Werner 已提交
3268
        for table_name in tables:
3269 3270 3271 3272
            table = Table(table_name, self.db_meta, \
                autoload=True, useexisting=True)
            setattr(self, 'tbl_%s' % table_name, table)

3273 3274 3275 3276
        for view_name in views:
            view = Table(view_name, self.db_meta, autoload=True)
            setattr(self, 'view_%s' % view_name, view)

M
Mark Hymers 已提交
3277
    def __setupmappers(self):
M
Mark Hymers 已提交
3278
        mapper(Architecture, self.tbl_architecture,
3279
            properties = dict(arch_id = self.tbl_architecture.c.id,
3280 3281
               suites = relation(Suite, secondary=self.tbl_suite_architectures,
                   order_by='suite_name',
3282 3283
                   backref=backref('architectures', order_by='arch_string'))),
            extension = validator)
M
Mark Hymers 已提交
3284 3285 3286 3287

        mapper(Archive, self.tbl_archive,
               properties = dict(archive_id = self.tbl_archive.c.id,
                                 archive_name = self.tbl_archive.c.name))
M
Mike O'Connor 已提交
3288

3289 3290 3291 3292 3293 3294 3295
        mapper(BuildQueue, self.tbl_build_queue,
               properties = dict(queue_id = self.tbl_build_queue.c.id))

        mapper(BuildQueueFile, self.tbl_build_queue_files,
               properties = dict(buildqueue = relation(BuildQueue, backref='queuefiles'),
                                 poolfile = relation(PoolFile, backref='buildqueueinstances')))

3296 3297 3298 3299 3300
        mapper(BuildQueuePolicyFile, self.tbl_build_queue_policy_files,
               properties = dict(
                build_queue = relation(BuildQueue, backref='policy_queue_files'),
                file = relation(ChangePendingFile, lazy='joined')))

3301
        mapper(DBBinary, self.tbl_binaries,
M
Mark Hymers 已提交
3302
               properties = dict(binary_id = self.tbl_binaries.c.id,
M
Mark Hymers 已提交
3303 3304
                                 package = self.tbl_binaries.c.package,
                                 version = self.tbl_binaries.c.version,
M
Mark Hymers 已提交
3305
                                 maintainer_id = self.tbl_binaries.c.maintainer,
M
Mark Hymers 已提交
3306
                                 maintainer = relation(Maintainer),
M
Mark Hymers 已提交
3307
                                 source_id = self.tbl_binaries.c.source,
3308
                                 source = relation(DBSource, backref='binaries'),
M
Mark Hymers 已提交
3309
                                 arch_id = self.tbl_binaries.c.architecture,
M
Mark Hymers 已提交
3310 3311
                                 architecture = relation(Architecture),
                                 poolfile_id = self.tbl_binaries.c.file,
3312
                                 poolfile = relation(PoolFile, backref=backref('binary', uselist = False)),
M
Mark Hymers 已提交
3313 3314 3315 3316
                                 binarytype = self.tbl_binaries.c.type,
                                 fingerprint_id = self.tbl_binaries.c.sig_fpr,
                                 fingerprint = relation(Fingerprint),
                                 install_date = self.tbl_binaries.c.install_date,
3317
                                 suites = relation(Suite, secondary=self.tbl_bin_associations,
M
Mark Hymers 已提交
3318 3319
                                     backref=backref('binaries', lazy='dynamic')),
                                 extra_sources = relation(DBSource, secondary=self.tbl_extra_src_references,
3320
                                     backref=backref('extra_binary_references', lazy='dynamic')),
3321
                                 key = relation(BinaryMetadata, cascade='all',
3322
                                     collection_class=attribute_mapped_collection('key'))),
3323
                extension = validator)
M
Mark Hymers 已提交
3324

3325 3326 3327 3328
        mapper(BinaryACL, self.tbl_binary_acl,
               properties = dict(binary_acl_id = self.tbl_binary_acl.c.id))

        mapper(BinaryACLMap, self.tbl_binary_acl_map,
3329 3330 3331
               properties = dict(binary_acl_map_id = self.tbl_binary_acl_map.c.id,
                                 fingerprint = relation(Fingerprint, backref="binary_acl_map"),
                                 architecture = relation(Architecture)))
3332

M
Mark Hymers 已提交
3333 3334
        mapper(Component, self.tbl_component,
               properties = dict(component_id = self.tbl_component.c.id,
3335 3336
                                 component_name = self.tbl_component.c.name),
               extension = validator)
M
Mark Hymers 已提交
3337 3338 3339 3340 3341 3342 3343

        mapper(DBConfig, self.tbl_config,
               properties = dict(config_id = self.tbl_config.c.id))

        mapper(DSCFile, self.tbl_dsc_files,
               properties = dict(dscfile_id = self.tbl_dsc_files.c.id,
                                 source_id = self.tbl_dsc_files.c.source,
3344
                                 source = relation(DBSource),
M
Mark Hymers 已提交
3345 3346
                                 poolfile_id = self.tbl_dsc_files.c.file,
                                 poolfile = relation(PoolFile)))
M
Mark Hymers 已提交
3347

A
Ansgar Burchardt 已提交
3348 3349
        mapper(ExternalOverride, self.tbl_external_overrides)

M
Mark Hymers 已提交
3350 3351 3352
        mapper(PoolFile, self.tbl_files,
               properties = dict(file_id = self.tbl_files.c.id,
                                 filesize = self.tbl_files.c.size,
M
Mark Hymers 已提交
3353
                                 location_id = self.tbl_files.c.location,
3354 3355 3356 3357
                                 location = relation(Location,
                                     # using lazy='dynamic' in the back
                                     # reference because we have A LOT of
                                     # files in one location
3358 3359
                                     backref=backref('files', lazy='dynamic'))),
                extension = validator)
M
Mark Hymers 已提交
3360 3361 3362 3363

        mapper(Fingerprint, self.tbl_fingerprint,
               properties = dict(fingerprint_id = self.tbl_fingerprint.c.id,
                                 uid_id = self.tbl_fingerprint.c.uid,
M
Mark Hymers 已提交
3364 3365
                                 uid = relation(Uid),
                                 keyring_id = self.tbl_fingerprint.c.keyring,
3366 3367
                                 keyring = relation(Keyring),
                                 source_acl = relation(SourceACL),
3368 3369
                                 binary_acl = relation(BinaryACL)),
               extension = validator)
M
Mark Hymers 已提交
3370 3371 3372 3373 3374

        mapper(Keyring, self.tbl_keyrings,
               properties = dict(keyring_name = self.tbl_keyrings.c.name,
                                 keyring_id = self.tbl_keyrings.c.id))

M
Mark Hymers 已提交
3375 3376
        mapper(DBChange, self.tbl_changes,
               properties = dict(change_id = self.tbl_changes.c.id,
M
Mark Hymers 已提交
3377 3378 3379
                                 poolfiles = relation(PoolFile,
                                                      secondary=self.tbl_changes_pool_files,
                                                      backref="changeslinks"),
3380
                                 seen = self.tbl_changes.c.seen,
3381 3382 3383 3384 3385 3386 3387 3388
                                 source = self.tbl_changes.c.source,
                                 binaries = self.tbl_changes.c.binaries,
                                 architecture = self.tbl_changes.c.architecture,
                                 distribution = self.tbl_changes.c.distribution,
                                 urgency = self.tbl_changes.c.urgency,
                                 maintainer = self.tbl_changes.c.maintainer,
                                 changedby = self.tbl_changes.c.changedby,
                                 date = self.tbl_changes.c.date,
M
Mike O'Connor 已提交
3389
                                 version = self.tbl_changes.c.version,
3390 3391 3392 3393 3394 3395 3396
                                 files = relation(ChangePendingFile,
                                                  secondary=self.tbl_changes_pending_files_map,
                                                  backref="changesfile"),
                                 in_queue_id = self.tbl_changes.c.in_queue,
                                 in_queue = relation(PolicyQueue,
                                                     primaryjoin=(self.tbl_changes.c.in_queue==self.tbl_policy_queue.c.id)),
                                 approved_for_id = self.tbl_changes.c.approved_for))
3397

M
Mark Hymers 已提交
3398 3399
        mapper(ChangePendingBinary, self.tbl_changes_pending_binaries,
               properties = dict(change_pending_binary_id = self.tbl_changes_pending_binaries.c.id))
M
Mark Hymers 已提交
3400

3401
        mapper(ChangePendingFile, self.tbl_changes_pending_files,
3402 3403 3404 3405 3406 3407
               properties = dict(change_pending_file_id = self.tbl_changes_pending_files.c.id,
                                 filename = self.tbl_changes_pending_files.c.filename,
                                 size = self.tbl_changes_pending_files.c.size,
                                 md5sum = self.tbl_changes_pending_files.c.md5sum,
                                 sha1sum = self.tbl_changes_pending_files.c.sha1sum,
                                 sha256sum = self.tbl_changes_pending_files.c.sha256sum))
3408 3409 3410

        mapper(ChangePendingSource, self.tbl_changes_pending_source,
               properties = dict(change_pending_source_id = self.tbl_changes_pending_source.c.id,
M
Mark Hymers 已提交
3411
                                 change = relation(DBChange),
3412 3413 3414 3415 3416 3417 3418
                                 maintainer = relation(Maintainer,
                                                       primaryjoin=(self.tbl_changes_pending_source.c.maintainer_id==self.tbl_maintainer.c.id)),
                                 changedby = relation(Maintainer,
                                                      primaryjoin=(self.tbl_changes_pending_source.c.changedby_id==self.tbl_maintainer.c.id)),
                                 fingerprint = relation(Fingerprint),
                                 source_files = relation(ChangePendingFile,
                                                         secondary=self.tbl_changes_pending_source_files,
3419
                                                         backref="pending_sources")))
M
Mark Hymers 已提交
3420

J
Joerg Jaspert 已提交
3421

M
Mark Hymers 已提交
3422 3423 3424 3425 3426
        mapper(KeyringACLMap, self.tbl_keyring_acl_map,
               properties = dict(keyring_acl_map_id = self.tbl_keyring_acl_map.c.id,
                                 keyring = relation(Keyring, backref="keyring_acl_map"),
                                 architecture = relation(Architecture)))

M
Mark Hymers 已提交
3427 3428 3429
        mapper(Location, self.tbl_location,
               properties = dict(location_id = self.tbl_location.c.id,
                                 component_id = self.tbl_location.c.component,
3430
                                 component = relation(Component, backref='location'),
M
Mark Hymers 已提交
3431
                                 archive_id = self.tbl_location.c.archive,
M
Mark Hymers 已提交
3432
                                 archive = relation(Archive),
3433 3434
                                 # FIXME: the 'type' column is old cruft and
                                 # should be removed in the future.
3435 3436
                                 archive_type = self.tbl_location.c.type),
               extension = validator)
M
Mark Hymers 已提交
3437 3438

        mapper(Maintainer, self.tbl_maintainer,
3439 3440 3441 3442
               properties = dict(maintainer_id = self.tbl_maintainer.c.id,
                   maintains_sources = relation(DBSource, backref='maintainer',
                       primaryjoin=(self.tbl_maintainer.c.id==self.tbl_source.c.maintainer)),
                   changed_sources = relation(DBSource, backref='changedby',
3443 3444
                       primaryjoin=(self.tbl_maintainer.c.id==self.tbl_source.c.changedby))),
                extension = validator)
M
Mark Hymers 已提交
3445

M
Mark Hymers 已提交
3446 3447 3448
        mapper(NewComment, self.tbl_new_comments,
               properties = dict(comment_id = self.tbl_new_comments.c.id))

M
Mark Hymers 已提交
3449 3450
        mapper(Override, self.tbl_override,
               properties = dict(suite_id = self.tbl_override.c.suite,
T
Torsten Werner 已提交
3451 3452
                                 suite = relation(Suite, \
                                    backref=backref('overrides', lazy='dynamic')),
3453
                                 package = self.tbl_override.c.package,
M
Mark Hymers 已提交
3454
                                 component_id = self.tbl_override.c.component,
3455 3456
                                 component = relation(Component, \
                                    backref=backref('overrides', lazy='dynamic')),
M
Mark Hymers 已提交
3457
                                 priority_id = self.tbl_override.c.priority,
3458 3459
                                 priority = relation(Priority, \
                                    backref=backref('overrides', lazy='dynamic')),
M
Mark Hymers 已提交
3460
                                 section_id = self.tbl_override.c.section,
3461 3462
                                 section = relation(Section, \
                                    backref=backref('overrides', lazy='dynamic')),
M
Mark Hymers 已提交
3463
                                 overridetype_id = self.tbl_override.c.type,
3464 3465
                                 overridetype = relation(OverrideType, \
                                    backref=backref('overrides', lazy='dynamic'))))
M
Mark Hymers 已提交
3466 3467 3468 3469 3470

        mapper(OverrideType, self.tbl_override_type,
               properties = dict(overridetype = self.tbl_override_type.c.type,
                                 overridetype_id = self.tbl_override_type.c.id))

3471 3472 3473
        mapper(PolicyQueue, self.tbl_policy_queue,
               properties = dict(policy_queue_id = self.tbl_policy_queue.c.id))

M
Mark Hymers 已提交
3474 3475 3476 3477
        mapper(Priority, self.tbl_priority,
               properties = dict(priority_id = self.tbl_priority.c.id))

        mapper(Section, self.tbl_section,
M
Mike O'Connor 已提交
3478 3479
               properties = dict(section_id = self.tbl_section.c.id,
                                 section=self.tbl_section.c.section))
M
Mark Hymers 已提交
3480

3481
        mapper(DBSource, self.tbl_source,
M
Mark Hymers 已提交
3482
               properties = dict(source_id = self.tbl_source.c.id,
M
Mark Hymers 已提交
3483
                                 version = self.tbl_source.c.version,
M
Mark Hymers 已提交
3484
                                 maintainer_id = self.tbl_source.c.maintainer,
M
Mark Hymers 已提交
3485
                                 poolfile_id = self.tbl_source.c.file,
3486
                                 poolfile = relation(PoolFile, backref=backref('source', uselist = False)),
M
Mark Hymers 已提交
3487
                                 fingerprint_id = self.tbl_source.c.sig_fpr,
M
Mark Hymers 已提交
3488 3489 3490 3491
                                 fingerprint = relation(Fingerprint),
                                 changedby_id = self.tbl_source.c.changedby,
                                 srcfiles = relation(DSCFile,
                                                     primaryjoin=(self.tbl_source.c.id==self.tbl_dsc_files.c.source)),
3492
                                 suites = relation(Suite, secondary=self.tbl_src_associations,
3493
                                     backref=backref('sources', lazy='dynamic')),
3494 3495
                                 uploaders = relation(Maintainer,
                                     secondary=self.tbl_src_uploaders),
3496
                                 key = relation(SourceMetadata, cascade='all',
3497
                                     collection_class=attribute_mapped_collection('key'))),
3498
               extension = validator)
M
Mark Hymers 已提交
3499

3500 3501
        mapper(SourceACL, self.tbl_source_acl,
               properties = dict(source_acl_id = self.tbl_source_acl.c.id))
M
Mark Hymers 已提交
3502

3503 3504 3505 3506
        mapper(SrcFormat, self.tbl_src_format,
               properties = dict(src_format_id = self.tbl_src_format.c.id,
                                 format_name = self.tbl_src_format.c.format_name))

M
Mark Hymers 已提交
3507
        mapper(Suite, self.tbl_suite,
3508
               properties = dict(suite_id = self.tbl_suite.c.id,
3509
                                 policy_queue = relation(PolicyQueue),
3510 3511 3512
                                 copy_queues = relation(BuildQueue,
                                     secondary=self.tbl_suite_build_queue_copy)),
                extension = validator)
M
Mark Hymers 已提交
3513

3514 3515 3516 3517 3518 3519
        mapper(SuiteSrcFormat, self.tbl_suite_src_formats,
               properties = dict(suite_id = self.tbl_suite_src_formats.c.suite,
                                 suite = relation(Suite, backref='suitesrcformats'),
                                 src_format_id = self.tbl_suite_src_formats.c.src_format,
                                 src_format = relation(SrcFormat)))

M
Mark Hymers 已提交
3520
        mapper(Uid, self.tbl_uid,
3521
               properties = dict(uid_id = self.tbl_uid.c.id,
3522 3523
                                 fingerprint = relation(Fingerprint)),
               extension = validator)
M
Mark Hymers 已提交
3524

3525
        mapper(UploadBlock, self.tbl_upload_blocks,
3526 3527 3528
               properties = dict(upload_block_id = self.tbl_upload_blocks.c.id,
                                 fingerprint = relation(Fingerprint, backref="uploadblocks"),
                                 uid = relation(Uid, backref="uploadblocks")))
3529

3530 3531 3532
        mapper(BinContents, self.tbl_bin_contents,
            properties = dict(
                binary = relation(DBBinary,
3533
                    backref=backref('contents', lazy='dynamic', cascade='all')),
3534 3535
                file = self.tbl_bin_contents.c.file))

3536 3537 3538 3539 3540 3541
        mapper(SrcContents, self.tbl_src_contents,
            properties = dict(
                source = relation(DBSource,
                    backref=backref('contents', lazy='dynamic', cascade='all')),
                file = self.tbl_src_contents.c.file))

T
Torsten Werner 已提交
3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562
        mapper(MetadataKey, self.tbl_metadata_keys,
            properties = dict(
                key_id = self.tbl_metadata_keys.c.key_id,
                key = self.tbl_metadata_keys.c.key))

        mapper(BinaryMetadata, self.tbl_binaries_metadata,
            properties = dict(
                binary_id = self.tbl_binaries_metadata.c.bin_id,
                binary = relation(DBBinary),
                key_id = self.tbl_binaries_metadata.c.key_id,
                key = relation(MetadataKey),
                value = self.tbl_binaries_metadata.c.value))

        mapper(SourceMetadata, self.tbl_source_metadata,
            properties = dict(
                source_id = self.tbl_source_metadata.c.src_id,
                source = relation(DBSource),
                key_id = self.tbl_source_metadata.c.key_id,
                key = relation(MetadataKey),
                value = self.tbl_source_metadata.c.value))

3563 3564 3565 3566 3567 3568 3569
	mapper(VersionCheck, self.tbl_version_check,
	    properties = dict(
		suite_id = self.tbl_version_check.c.suite,
		suite = relation(Suite, primaryjoin=self.tbl_version_check.c.suite==self.tbl_suite.c.id),
		reference_id = self.tbl_version_check.c.reference,
		reference = relation(Suite, primaryjoin=self.tbl_version_check.c.reference==self.tbl_suite.c.id, lazy='joined')))

M
Mark Hymers 已提交
3570 3571
    ## Connection functions
    def __createconn(self):
M
Mark Hymers 已提交
3572
        from config import Config
3573
        cnf = Config()
M
Mark Hymers 已提交
3574
        if cnf.has_key("DB::Service"):
3575
            connstr = "postgresql://service=%s" % cnf["DB::Service"]
M
Mark Hymers 已提交
3576
        elif cnf.has_key("DB::Host"):
M
Mark Hymers 已提交
3577
            # TCP/IP
3578
            connstr = "postgresql://%s" % cnf["DB::Host"]
M
Mark Hymers 已提交
3579
            if cnf.has_key("DB::Port") and cnf["DB::Port"] != "-1":
M
Mark Hymers 已提交
3580 3581 3582 3583
                connstr += ":%s" % cnf["DB::Port"]
            connstr += "/%s" % cnf["DB::Name"]
        else:
            # Unix Socket
3584
            connstr = "postgresql:///%s" % cnf["DB::Name"]
M
Mark Hymers 已提交
3585
            if cnf.has_key("DB::Port") and cnf["DB::Port"] != "-1":
M
Mark Hymers 已提交
3586
                connstr += "?port=%s" % cnf["DB::Port"]
3587 3588 3589 3590 3591 3592

        engine_args = { 'echo': self.debug }
        if cnf.has_key('DB::PoolSize'):
            engine_args['pool_size'] = int(cnf['DB::PoolSize'])
        if cnf.has_key('DB::MaxOverflow'):
            engine_args['max_overflow'] = int(cnf['DB::MaxOverflow'])
T
bugfix  
Torsten Werner 已提交
3593
        if sa_major_version == '0.6' and cnf.has_key('DB::Unicode') and \
3594 3595 3596
            cnf['DB::Unicode'] == 'false':
            engine_args['use_native_unicode'] = False

3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610
        # Monkey patch a new dialect in in order to support service= syntax
        import sqlalchemy.dialects.postgresql
        from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
        class PGDialect_psycopg2_dak(PGDialect_psycopg2):
            def create_connect_args(self, url):
                if str(url).startswith('postgresql://service='):
                    # Eww
                    servicename = str(url)[21:]
                    return (['service=%s' % servicename], {})
                else:
                    return PGDialect_psycopg2.create_connect_args(self, url)

        sqlalchemy.dialects.postgresql.base.dialect = PGDialect_psycopg2_dak

3611
        self.db_pg   = create_engine(connstr, **engine_args)
M
Mark Hymers 已提交
3612 3613 3614 3615
        self.db_meta = MetaData()
        self.db_meta.bind = self.db_pg
        self.db_smaker = sessionmaker(bind=self.db_pg,
                                      autoflush=True,
3616
                                      autocommit=False)
M
Mark Hymers 已提交
3617

M
Mark Hymers 已提交
3618
        self.__setuptables()
M
Mark Hymers 已提交
3619
        self.__setupmappers()
3620
        self.pid = os.getpid()
M
Mark Hymers 已提交
3621

3622 3623 3624 3625 3626 3627 3628
    def session(self, work_mem = 0):
        '''
        Returns a new session object. If a work_mem parameter is provided a new
        transaction is started and the work_mem parameter is set for this
        transaction. The work_mem parameter is measured in MB. A default value
        will be used if the parameter is not set.
        '''
3629 3630 3631 3632
        # reinitialize DBConn in new processes
        if self.pid != os.getpid():
            clear_mappers()
            self.__createconn()
3633 3634 3635 3636
        session = self.db_smaker()
        if work_mem > 0:
            session.execute("SET LOCAL work_mem TO '%d MB'" % work_mem)
        return session
M
Mark Hymers 已提交
3637

M
Mark Hymers 已提交
3638
__all__.append('DBConn')
M
Mike O'Connor 已提交
3639

3640