dbconn.py 77.1 KB
Newer Older
1 2 3 4 5
""" 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 已提交
6
@copyright: 2009, 2010  Joerg Jaspert <joerg@debian.org>
7
@copyright: 2009  Mike O'Connor <stew@debian.org>
8 9
@license: GNU General Public License version 2 or later
"""
M
Mark Hymers 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

# 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"

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

34
import apt_pkg
35
import daklib.daksubprocess
36
from daklib.gpg import GpgException
37
import functools
38
import os
39
from os.path import normpath
M
Mark Hymers 已提交
40
import re
41
import six
42
import subprocess
43
import warnings
T
Torsten Werner 已提交
44

45
from debian.debfile import Deb822
46
from tarfile import TarFile
M
Mark Hymers 已提交
47

48 49
from inspect import getargspec

50
import sqlalchemy
A
Ansgar Burchardt 已提交
51
from sqlalchemy import create_engine, Table, desc
52
from sqlalchemy.orm import sessionmaker, mapper, relation, object_session, \
A
Ansgar Burchardt 已提交
53
    backref, object_mapper
54
import sqlalchemy.types
55 56
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
M
Mark Hymers 已提交
57

M
Mark Hymers 已提交
58 59
# Don't remove this, we re-export the exceptions to scripts which import us
from sqlalchemy.exc import *
60
from sqlalchemy.orm.exc import NoResultFound
M
Mark Hymers 已提交
61

62
from .aptversion import AptVersion
63 64
# Only import Config until Queue stuff is changed to store its config
# in the database
65
from .config import Config
66
from .textutils import fix_maintainer, force_to_utf8
M
Mark Hymers 已提交
67

68
# suppress some deprecation warnings in squeeze related to sqlalchemy
69 70
warnings.filterwarnings('ignore',
    "Predicate of partial index .* ignored during reflection",
71
    SAWarning)
72

B
Bastian Blank 已提交
73 74
from .database.base import Base

75

M
Mark Hymers 已提交
76 77
################################################################################

78 79 80
# Patch in support for the debversion field type so that it works during
# reflection

81
class DebVersion(sqlalchemy.types.UserDefinedType):
82 83 84
    def get_col_spec(self):
        return "DEBVERSION"

85 86 87
    def bind_processor(self, dialect):
        return None

88
    def result_processor(self, dialect, coltype):
89 90
        return None

91

92 93
from sqlalchemy.databases import postgresql
postgresql.ischema_names['debversion'] = DebVersion
94 95 96

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

97
__all__ = ['IntegrityError', 'SQLAlchemyError', 'DebVersion']
98 99 100

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

101

102
def session_wrapper(fn):
C
Chris Lamb 已提交
103 104 105 106
    """
    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.
107 108 109 110

    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 已提交
111 112
    """

113 114 115
    def wrapped(*args, **kwargs):
        private_transaction = False

116
        # Find the session object
C
Chris Lamb 已提交
117 118 119
        session = kwargs.get('session')

        if session is None:
120 121 122 123 124 125 126
            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]
127
                if session is None:
M
fixup  
Mark Hymers 已提交
128
                    args = list(args)
129 130
                    session = args[-1] = DBConn().session()
                    private_transaction = True
131 132 133 134 135

        if private_transaction:
            session.commit_or_flush = session.commit
        else:
            session.commit_or_flush = session.flush
136 137 138 139 140 141

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

144
    wrapped.__doc__ = fn.__doc__
145
    wrapped.__name__ = fn.__name__
146

147 148
    return wrapped

149

F
Frank Lichtenheld 已提交
150 151
__all__.append('session_wrapper')

152 153
################################################################################

154

155 156 157
class ORMObject(object):
    """
    ORMObject is a base class for all ORM classes mapped by SQLalchemy. All
T
Torsten Werner 已提交
158
    derived classes must implement the properties() method.
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    """

    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 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.
        '''
192
        return '<%s(...)>' % (self.classname())
193

194 195
    @classmethod
    @session_wrapper
196
    def get(cls, primary_key,  session=None):
197 198 199 200 201 202 203 204 205 206 207 208
        '''
        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)

209
    def session(self):
210 211 212 213 214 215 216
        '''
        Returns the current session that is associated with the object. May
        return None is object is in detached state.
        '''

        return object_session(self)

217
    def clone(self, session=None):
T
Tollef Fog Heen 已提交
218
        """
219 220
        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
221 222
        provided. The function will fail if a session is provided and has
        unflushed changes.
223

224 225 226
        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.
227

228 229 230
        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
T
Tollef Fog Heen 已提交
231 232
        resource leaks.
        """
233 234

        if self.session() is None:
235
            raise RuntimeError(
236
                'Method clone() failed for detached object:\n%s' % self)
237 238 239 240
        self.session().flush()
        mapper = object_mapper(self)
        primary_key = mapper.primary_key_from_instance(self)
        object_class = self.__class__
241 242 243
        if session is None:
            session = DBConn().session()
        elif len(session.new) + len(session.dirty) + len(session.deleted) > 0:
244
            raise RuntimeError(
245
                'Method clone() failed due to unflushed changes in session.')
246
        new_object = session.query(object_class).get(primary_key)
247
        session.rollback()
248
        if new_object is None:
249
            raise RuntimeError(
250 251 252
                'Method clone() failed for non-persistent object:\n%s' % self)
        return new_object

253

254 255 256 257
__all__.append('ORMObject')

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

258

259 260 261 262
class ACL(ORMObject):
    def __repr__(self):
        return "<ACL {0}>".format(self.name)

263

264 265
__all__.append('ACL')

266

267 268 269 270
class ACLPerSource(ORMObject):
    def __repr__(self):
        return "<ACLPerSource acl={0} fingerprint={1} source={2} reason={3}>".format(self.acl.name, self.fingerprint.fingerprint, self.source, self.reason)

271

272 273 274 275
__all__.append('ACLPerSource')

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

276

277
from .database.architecture import Architecture
M
Mark Hymers 已提交
278

279 280
__all__.append('Architecture')

281

282
@session_wrapper
283 284 285 286 287 288 289 290 291 292 293 294 295 296
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)
    """
297

298
    q = session.query(Architecture).filter_by(arch_string=architecture)
A
Ansgar 已提交
299
    return q.one_or_none()
300

301

302 303
__all__.append('get_architecture')

M
Mark Hymers 已提交
304 305
################################################################################

306

M
Mark Hymers 已提交
307
class Archive(object):
M
Mark Hymers 已提交
308 309
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
310 311

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

314

315 316
__all__.append('Archive')

317

318
@session_wrapper
319 320
def get_archive(archive, session=None):
    """
F
Frank Lichtenheld 已提交
321
    returns database id for given C{archive}.
322 323 324 325 326 327 328 329 330 331 332 333 334

    @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()
335

336
    q = session.query(Archive).filter_by(archive_name=archive)
A
Ansgar 已提交
337
    return q.one_or_none()
338

339

340
__all__.append('get_archive')
341

M
Mark Hymers 已提交
342 343
################################################################################

344

345 346 347 348 349
class ArchiveFile(object):
    def __init__(self, archive=None, component=None, file=None):
        self.archive = archive
        self.component = component
        self.file = file
350

351 352 353 354
    @property
    def path(self):
        return os.path.join(self.archive.path, 'pool', self.component.component_name, self.file.filename)

355

356 357 358 359
__all__.append('ArchiveFile')

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

360

361
class BinContents(ORMObject):
362
    def __init__(self, file=None, binary=None):
363 364 365 366
        self.file = file
        self.binary = binary

    def properties(self):
367
        return ['file', 'binary']
M
Mike O'Connor 已提交
368

369

M
Mike O'Connor 已提交
370 371 372 373
__all__.append('BinContents')

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

374

375
class DBBinary(ORMObject):
376 377
    def __init__(self, package=None, source=None, version=None,
        maintainer=None, architecture=None, poolfile=None,
378
        binarytype='deb', fingerprint=None):
379 380 381 382 383 384 385
        self.package = package
        self.source = source
        self.version = version
        self.maintainer = maintainer
        self.architecture = architecture
        self.poolfile = poolfile
        self.binarytype = binarytype
386
        self.fingerprint = fingerprint
M
Mark Hymers 已提交
387

M
Mark Hymers 已提交
388 389 390 391
    @property
    def pkid(self):
        return self.binary_id

392 393 394 395 396 397 398 399
    @property
    def name(self):
        return self.package

    @property
    def arch_string(self):
        return "%s" % self.architecture

400
    def properties(self):
401 402
        return ['package', 'version', 'maintainer', 'source', 'architecture',
            'poolfile', 'binarytype', 'fingerprint', 'install_date',
M
Mark Hymers 已提交
403
            'suites_count', 'binary_id', 'contents_count', 'extra_sources']
404

405 406
    metadata = association_proxy('key', 'value')

407 408 409
    def scan_contents(self):
        '''
        Yields the contents of the package. Only regular files are yielded and
410 411 412
        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.
413 414
        '''
        fullpath = self.poolfile.fullpath
415 416
        dpkg_cmd = ('dpkg-deb', '--fsys-tarfile', fullpath)
        dpkg = daklib.daksubprocess.Popen(dpkg_cmd, stdout=subprocess.PIPE)
417
        tar = TarFile.open(fileobj=dpkg.stdout, mode='r|')
418
        for member in tar.getmembers():
419
            if not member.isdir():
420
                name = normpath(member.name)
421
                name = force_to_utf8(name)
422
                yield name
423
        tar.close()
424 425
        dpkg.stdout.close()
        dpkg.wait()
426

M
Mark Hymers 已提交
427 428 429 430
    def read_control(self):
        '''
        Reads the control information from a binary.

M
Mark Hymers 已提交
431 432
        @rtype: text
        @return: stanza text of the control section.
M
Mark Hymers 已提交
433
        '''
B
Bastian Blank 已提交
434
        from . import utils
M
Mark Hymers 已提交
435
        fullpath = self.poolfile.fullpath
436 437
        with open(fullpath, 'r') as deb_file:
            return utils.deb_extract_control(deb_file)
M
Mark Hymers 已提交
438 439 440 441 442

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

M
Mark Hymers 已提交
444 445 446 447 448
        @rtype: dict
        @return: fields of the control section as a dictionary.
        '''
        stanza = self.read_control()
        return apt_pkg.TagSection(stanza)
M
Mark Hymers 已提交
449

450 451 452 453 454 455
    @property
    def proxy(self):
        session = object_session(self)
        query = session.query(BinaryMetadata).filter_by(binary=self)
        return MetadataProxy(session, query)

456

457
__all__.append('DBBinary')
458

459

460
@session_wrapper
461 462 463 464
def get_suites_binary_in(package, session=None):
    """
    Returns list of Suite objects which given C{package} name is in

J
Joerg Jaspert 已提交
465 466
    @type package: str
    @param package: DBBinary package name to search for
467 468 469 470 471

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

472
    return session.query(Suite).filter(Suite.binaries.any(DBBinary.package == package)).all()
473

474

475 476
__all__.append('get_suites_binary_in')

477

478
@session_wrapper
N
Niels Thykier 已提交
479
def get_component_by_package_suite(package, suite_list, arch_list=None, session=None):
480 481
    '''
    Returns the component name of the newest binary package in suite_list or
482 483
    None if no package is found. The result can be optionally filtered by a list
    of architecture names.
484 485 486

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

488 489 490
    @type suite_list: list of str
    @param suite_list: list of suite_name items

491 492 493
    @type arch_list: list of str
    @param arch_list: optional list of arch_string items that defaults to []

494 495 496 497
    @rtype: str or NoneType
    @return: name of component or None
    '''

498
    q = session.query(DBBinary).filter_by(package=package). \
499
        join(DBBinary.suites).filter(Suite.suite_name.in_(suite_list))
N
Niels Thykier 已提交
500
    if arch_list:
501 502 503
        q = q.join(DBBinary.architecture). \
            filter(Architecture.arch_string.in_(arch_list))
    binary = q.order_by(desc(DBBinary.version)).first()
504 505 506
    if binary is None:
        return None
    else:
507
        return binary.poolfile.component.component_name
508

509

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

M
Mark Hymers 已提交
512 513
################################################################################

514

515 516 517 518 519
class BuildQueue(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
520
        return '<BuildQueue %s>' % self.queue_name
521

522

523 524 525 526
__all__.append('BuildQueue')

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

527

528
class Component(ORMObject):
529
    def __init__(self, component_name=None):
530
        self.component_name = component_name
M
Mark Hymers 已提交
531

532 533
    def __eq__(self, val):
        if isinstance(val, str):
A
Ansgar 已提交
534
            warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
535 536 537 538 539 540
            return (self.component_name == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
A
Ansgar 已提交
541
            warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
542 543 544 545
            return (self.component_name != val)
        # This signals to use the normal comparison operator
        return NotImplemented

546 547
    __hash__ = ORMObject.__hash__

548
    def properties(self):
549
        return ['component_name', 'component_id', 'description',
A
Ansgar Burchardt 已提交
550
            'meets_dfsg', 'overrides_count']
551

552

553 554
__all__.append('Component')

555

556
@session_wrapper
557 558 559 560 561 562 563 564 565 566 567 568
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()
569

570
    q = session.query(Component).filter_by(component_name=component)
571

A
Ansgar 已提交
572
    return q.one_or_none()
573

574

575 576
__all__.append('get_component')

577

578 579 580 581 582 583 584 585
def get_mapped_component_name(component_name):
    cnf = Config()
    for m in cnf.value_list("ComponentMappings"):
        (src, dst) = m.split()
        if component_name == src:
            component_name = dst
    return component_name

586

587 588
__all__.append('get_mapped_component_name')

589

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
@session_wrapper
def get_mapped_component(component_name, session=None):
    """get component after mappings

    Evaluate component mappings from ComponentMappings in dak.conf for the
    given component name.

    @todo: ansgar wants to get rid of this. It's currently only used for
           the security archive

    @type  component_name: str
    @param component_name: component name

    @param session: database session

    @rtype:  L{daklib.dbconn.Component} or C{None}
    @return: component after applying maps or C{None}
    """
608
    component_name = get_mapped_component_name(component_name)
609 610 611
    component = session.query(Component).filter_by(component_name=component_name).first()
    return component

612

613 614
__all__.append('get_mapped_component')

615

M
Mark Hymers 已提交
616 617 618 619 620 621 622 623 624
@session_wrapper
def get_component_names(session=None):
    """
    Returns list of strings of component names.

    @rtype: list
    @return: list of strings of component names
    """

B
Bastian Blank 已提交
625
    return [x.component_name for x in session.query(Component).all()]
M
Mark Hymers 已提交
626

627

M
Mark Hymers 已提交
628 629
__all__.append('get_component_names')

M
Mark Hymers 已提交
630 631
################################################################################

632

M
Mark Hymers 已提交
633
class DBConfig(object):
M
Mark Hymers 已提交
634 635
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
636 637 638 639

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

640

641 642
__all__.append('DBConfig')

M
Mark Hymers 已提交
643 644
################################################################################

645

M
Mark Hymers 已提交
646
class DSCFile(object):
M
Mark Hymers 已提交
647 648
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
649 650 651 652

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

653

654 655
__all__.append('DSCFile')

656

657
@session_wrapper
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
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)

686
    return q.all()
M
Mark Hymers 已提交
687

688

M
Mark Hymers 已提交
689 690
__all__.append('get_dscfiles')

M
Mark Hymers 已提交
691 692
################################################################################

693

A
Ansgar Burchardt 已提交
694 695 696 697 698 699 700
class ExternalOverride(ORMObject):
    def __init__(self, *args, **kwargs):
        pass

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

701

A
Ansgar Burchardt 已提交
702 703 704 705
__all__.append('ExternalOverride')

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

706

707
class PoolFile(ORMObject):
708
    def __init__(self, filename=None, filesize=-1,
709
        md5sum=None):
710 711 712
        self.filename = filename
        self.filesize = filesize
        self.md5sum = md5sum
M
Mark Hymers 已提交
713

M
Mark Hymers 已提交
714 715
    @property
    def fullpath(self):
716
        session = DBConn().session().object_session(self)
717 718 719
        af = session.query(ArchiveFile).join(Archive) \
                    .filter(ArchiveFile.file == self) \
                    .order_by(Archive.tainted.desc()).first()
720
        return af.path
M
Mark Hymers 已提交
721

722 723 724 725 726 727 728
    @property
    def component(self):
        session = DBConn().session().object_session(self)
        component_id = session.query(ArchiveFile.component_id).filter(ArchiveFile.file == self) \
                              .group_by(ArchiveFile.component_id).one()
        return session.query(Component).get(component_id)

729 730 731 732
    @property
    def basename(self):
        return os.path.basename(self.filename)

733
    def properties(self):
734
        return ['filename', 'file_id', 'filesize', 'md5sum', 'sha1sum',
735
            'sha256sum', 'source', 'binary', 'last_used']
736

737

738 739
__all__.append('PoolFile')

M
Mark Hymers 已提交
740 741
################################################################################

742

743
class Fingerprint(ORMObject):
744
    def __init__(self, fingerprint=None):
T
Torsten Werner 已提交
745
        self.fingerprint = fingerprint
M
Mark Hymers 已提交
746

747
    def properties(self):
748
        return ['fingerprint', 'fingerprint_id', 'keyring', 'uid',
749 750
            'binary_reject']

751

752 753
__all__.append('Fingerprint')

754

M
Mark Hymers 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
@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)
A
Ansgar 已提交
772
    return q.one_or_none()
M
Mark Hymers 已提交
773

774

M
Mark Hymers 已提交
775 776
__all__.append('get_fingerprint')

777

778
@session_wrapper
M
Mark Hymers 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
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
    """

798
    q = session.query(Fingerprint).filter_by(fingerprint=fpr)
799 800 801 802

    try:
        ret = q.one()
    except NoResultFound:
803 804 805
        fingerprint = Fingerprint()
        fingerprint.fingerprint = fpr
        session.add(fingerprint)
806
        session.commit_or_flush()
807
        ret = fingerprint
M
Mark Hymers 已提交
808

809
    return ret
M
Mark Hymers 已提交
810

811

M
Mark Hymers 已提交
812 813
__all__.append('get_or_set_fingerprint')

M
Mark Hymers 已提交
814 815
################################################################################

M
Mark Hymers 已提交
816
# Helper routine for Keyring class
817 818


M
Mark Hymers 已提交
819 820 821
def get_ldap_name(entry):
    name = []
    for k in ["cn", "mn", "sn"]:
822 823 824 825 826 827
        ret = entry.get(k)
        if not ret:
            continue
        value = six.ensure_str(ret[0])
        if value and value[0] != "-":
            name.append(value)
M
Mark Hymers 已提交
828 829 830 831
    return " ".join(name)

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

832

M
Mark Hymers 已提交
833
class Keyring(object):
M
Mark Hymers 已提交
834 835 836
    keys = {}
    fpr_lookup = {}

M
Mark Hymers 已提交
837 838
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
839 840 841 842

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

843 844
    def de_escape_gpg_str(self, txt):
        esclist = re.split(r'(\\x..)', txt)
845 846
        for x in range(1, len(esclist), 2):
            esclist[x] = "%c" % (int(esclist[x][2:], 16))
M
Mark Hymers 已提交
847 848
        return "".join(esclist)

T
Torsten Werner 已提交
849 850
    def parse_address(self, uid):
        """parses uid and returns a tuple of real name and email address"""
851 852
        import email.utils
        (name, address) = email.utils.parseaddr(uid)
T
Torsten Werner 已提交
853 854 855 856 857
        name = re.sub(r"\s*[(].*[)]", "", name)
        name = self.de_escape_gpg_str(name)
        if name == "":
            name = uid
        return (name, address)
M
Mark Hymers 已提交
858

T
Torsten Werner 已提交
859
    def load_keys(self, keyring):
M
Mark Hymers 已提交
860 861 862
        if not self.keyring_id:
            raise Exception('Must be initialized with database information')

863 864
        cmd = ["gpg", "--no-default-keyring", "--keyring", keyring,
               "--with-colons", "--fingerprint", "--fingerprint"]
865
        p = daklib.daksubprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
866

M
Mark Hymers 已提交
867
        key = None
868
        need_fingerprint = False
M
Mark Hymers 已提交
869

870
        for line_raw in p.stdout:
871 872 873 874 875 876
            try:
                line = six.ensure_str(line_raw)
            except UnicodeDecodeError:
                # Some old UIDs might not use UTF-8 encoding. We assume they
                # use latin1.
                line = six.ensure_str(line_raw, encoding='latin1')
M
Mark Hymers 已提交
877 878 879
            field = line.split(":")
            if field[0] == "pub":
                key = field[4]
T
Torsten Werner 已提交
880 881 882 883
                self.keys[key] = {}
                (name, addr) = self.parse_address(field[9])
                if "@" in addr:
                    self.keys[key]["email"] = addr
M
Mark Hymers 已提交
884
                    self.keys[key]["name"] = name
885
                need_fingerprint = True
M
Mark Hymers 已提交
886
            elif key and field[0] == "uid":
T
Torsten Werner 已提交
887 888 889 890
                (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
891 892
            elif need_fingerprint and field[0] == "fpr":
                self.keys[key]["fingerprints"] = [field[9]]
M
Mark Hymers 已提交
893
                self.fpr_lookup[field[9]] = key
894
                need_fingerprint = False
M
Mark Hymers 已提交
895

896 897
        (out, err) = p.communicate()
        r = p.returncode
898
        if r != 0:
899
            raise GpgException("command failed: %s\nstdout: %s\nstderr: %s\n" % (cmd, out, err))
900

M
Mark Hymers 已提交
901
    def import_users_from_ldap(self, session):
902
        from .utils import open_ldap_connection
903
        import ldap
904
        l = open_ldap_connection()
M
Mark Hymers 已提交
905
        cnf = Config()
A
Ansgar 已提交
906
        LDAPDn = cnf["Import-LDAP-Fingerprints::LDAPDn"]
M
Mark Hymers 已提交
907
        Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
908
               "(&(keyfingerprint=*)(supplementaryGid=%s))" % (cnf["Import-Users-From-Passwd::ValidGID"]),
M
Mark Hymers 已提交
909 910 911 912 913 914 915
               ["uid", "keyfingerprint", "cn", "mn", "sn"])

        byuid = {}
        byname = {}

        for i in Attrs:
            entry = i[1]
A
Ansgar 已提交
916
            uid = six.ensure_str(entry["uid"][0])
M
Mark Hymers 已提交
917 918 919 920
            name = get_ldap_name(entry)
            fingerprints = entry["keyFingerPrint"]
            keyid = None
            for f in fingerprints:
A
Ansgar 已提交
921
                f = six.ensure_str(f)
M
Mark Hymers 已提交
922 923 924 925 926
                key = self.fpr_lookup.get(f, None)
                if key not in self.keys:
                    continue
                self.keys[key]["uid"] = uid

927
                if keyid is not None:
M
Mark Hymers 已提交
928 929 930 931 932 933 934 935 936 937 938
                    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
939
        for x in list(self.keys.keys()):
T
Torsten Werner 已提交
940
            if "email" not in self.keys[x]:
M
Mark Hymers 已提交
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
                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)

958

959 960
__all__.append('Keyring')

961

962
@session_wrapper
M
Mark Hymers 已提交
963
def get_keyring(keyring, session=None):
964
    """
M
Mark Hymers 已提交
965
    If C{keyring} does not have an entry in the C{keyrings} table yet, return None
966 967 968 969 970 971 972 973 974
    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
    """

975
    q = session.query(Keyring).filter_by(keyring_name=keyring)
A
Ansgar 已提交
976
    return q.one_or_none()
977

978

M
Mark Hymers 已提交
979
__all__.append('get_keyring')
980

981

M
Mark Hymers 已提交
982 983 984 985 986 987
@session_wrapper
def get_active_keyring_paths(session=None):
    """
    @rtype: list
    @return: list of active keyring paths
    """
B
Bastian Blank 已提交
988
    return [x.keyring_name for x in session.query(Keyring).filter(Keyring.active == True).order_by(desc(Keyring.priority)).all()]  # noqa:E712
M
Mark Hymers 已提交
989

990

M
Mark Hymers 已提交
991 992
__all__.append('get_active_keyring_paths')

M
Mark Hymers 已提交
993
################################################################################
994

995

M
Mark Hymers 已提交
996
class DBChange(object):
J
Joerg Jaspert 已提交
997 998 999 1000
    def __init__(self, *args, **kwargs):
        pass

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

1003

M
Mark Hymers 已提交
1004
__all__.append('DBChange')
J
Joerg Jaspert 已提交
1005

1006

J
Joerg Jaspert 已提交
1007
@session_wrapper
M
Mark Hymers 已提交
1008
def get_dbchange(filename, session=None):
J
Joerg Jaspert 已提交
1009
    """
M
Mark Hymers 已提交
1010
    returns DBChange object for given C{filename}.
J
Joerg Jaspert 已提交
1011

J
Joerg Jaspert 已提交
1012 1013
    @type filename: string
    @param filename: the name of the file
J
Joerg Jaspert 已提交
1014 1015 1016 1017 1018

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

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

J
Joerg Jaspert 已提交
1022
    """
M
Mark Hymers 已提交
1023
    q = session.query(DBChange).filter_by(changesname=filename)
A
Ansgar 已提交
1024
    return q.one_or_none()
J
Joerg Jaspert 已提交
1025

1026

M
Mark Hymers 已提交
1027
__all__.append('get_dbchange')
1028

M
Mark Hymers 已提交
1029 1030
################################################################################

1031

1032
class Maintainer(ORMObject):
1033
    def __init__(self, name=None):
1034
        self.name = name
M
Mark Hymers 已提交
1035

1036 1037 1038
    def properties(self):
        return ['name', 'maintainer_id']

M
Mark Hymers 已提交
1039 1040 1041 1042 1043 1044
    def get_split_maintainer(self):
        if not hasattr(self, 'name') or self.name is None:
            return ('', '', '', '')

        return fix_maintainer(self.name.strip())

1045

1046 1047
__all__.append('Maintainer')

1048

1049
@session_wrapper
M
Mark Hymers 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
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
    """

1069
    q = session.query(Maintainer).filter_by(name=name)
1070 1071 1072
    try:
        ret = q.one()
    except NoResultFound:
1073 1074 1075
        maintainer = Maintainer()
        maintainer.name = name
        session.add(maintainer)
1076
        session.commit_or_flush()
1077
        ret = maintainer
M
Mark Hymers 已提交
1078

1079
    return ret
M
Mark Hymers 已提交
1080

1081

M
Mark Hymers 已提交
1082 1083
__all__.append('get_or_set_maintainer')

1084

1085
@session_wrapper
C
Chris Lamb 已提交
1086
def get_maintainer(maintainer_id, session=None):
C
Chris Lamb 已提交
1087
    """
1088 1089
    Return the name of the maintainer behind C{maintainer_id} or None if that
    maintainer_id is invalid.
C
Chris Lamb 已提交
1090 1091 1092 1093

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

1094 1095
    @rtype: Maintainer
    @return: the Maintainer with this C{maintainer_id}
C
Chris Lamb 已提交
1096 1097
    """

1098
    return session.query(Maintainer).get(maintainer_id)
C
Chris Lamb 已提交
1099

1100

C
Chris Lamb 已提交
1101 1102
__all__.append('get_maintainer')

M
Mark Hymers 已提交
1103 1104
################################################################################

1105

M
Mark Hymers 已提交
1106 1107 1108 1109 1110 1111 1112
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)

1113

M
Mark Hymers 已提交
1114 1115
__all__.append('NewComment')

1116

1117
@session_wrapper
1118
def has_new_comment(policy_queue, package, version, session=None):
M
Mark Hymers 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    """
    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
    """

1136
    q = session.query(NewComment).filter_by(policy_queue=policy_queue)
M
Mark Hymers 已提交
1137 1138
    q = q.filter_by(package=package)
    q = q.filter_by(version=version)
1139

1140
    return bool(q.count() > 0)
M
Mark Hymers 已提交
1141

1142

M
Mark Hymers 已提交
1143 1144
__all__.append('has_new_comment')

1145

1146
@session_wrapper
1147
def get_new_comments(policy_queue, package=None, version=None, comment_id=None, session=None):
M
Mark Hymers 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    """
    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
    """

1169
    q = session.query(NewComment).filter_by(policy_queue=policy_queue)
1170 1171 1172 1173 1174 1175
    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)
M
Mark Hymers 已提交
1176

1177
    return q.all()
M
Mark Hymers 已提交
1178

1179

M
Mark Hymers 已提交
1180 1181 1182 1183
__all__.append('get_new_comments')

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

1184

1185
class Override(ORMObject):
1186
    def __init__(self, package=None, suite=None, component=None, overridetype=None,
1187
        section=None, priority=None):
1188 1189 1190 1191 1192 1193
        self.package = package
        self.suite = suite
        self.component = component
        self.overridetype = overridetype
        self.section = section
        self.priority = priority
M
Mark Hymers 已提交
1194

1195
    def properties(self):
1196
        return ['package', 'suite', 'component', 'overridetype', 'section',
1197 1198
            'priority']

1199

1200 1201
__all__.append('Override')

1202

1203
@session_wrapper
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
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:
1235 1236
        if not isinstance(suite, list):
            suite = [suite]
1237 1238 1239
        q = q.join(Suite).filter(Suite.suite_name.in_(suite))

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

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

1249
    return q.all()
1250

1251

1252 1253 1254
__all__.append('get_override')


M
Mark Hymers 已提交
1255 1256
################################################################################

1257
class OverrideType(ORMObject):
1258
    def __init__(self, overridetype=None):
1259
        self.overridetype = overridetype
M
Mark Hymers 已提交
1260

1261
    def properties(self):
1262
        return ['overridetype', 'overridetype_id', 'overrides_count']
1263

1264

1265 1266
__all__.append('OverrideType')

1267

1268
@session_wrapper
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
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
    """
1283

M
Mark Hymers 已提交
1284
    q = session.query(OverrideType).filter_by(overridetype=override_type)
A
Ansgar 已提交
1285
    return q.one_or_none()
1286

1287

1288 1289
__all__.append('get_override_type')

M
Mark Hymers 已提交
1290 1291
################################################################################

1292

1293 1294 1295 1296 1297 1298 1299
class PolicyQueue(object):
    def __init__(self, *args, **kwargs):
        pass

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

1300

1301 1302
__all__.append('PolicyQueue')

1303

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
@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)
A
Ansgar 已提交
1321
    return q.one_or_none()
1322

1323

1324 1325
__all__.append('get_policy_queue')

1326 1327
################################################################################

1328

1329
@functools.total_ordering
1330
class PolicyQueueUpload(object):
1331 1332 1333 1334 1335 1336 1337 1338
    def _key(self):
        return (
            self.changes.source,
            AptVersion(self.changes.version),
            self.source is None,
            self.changes.changesname
        )

1339
    def __eq__(self, other):
1340
        return self._key() == other._key()
1341 1342

    def __lt__(self, other):
1343
        return self._key() < other._key()
1344

1345

1346 1347 1348 1349
__all__.append('PolicyQueueUpload')

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

1350

1351 1352 1353
class PolicyQueueByhandFile(object):
    pass

1354

1355 1356 1357 1358
__all__.append('PolicyQueueByhandFile')

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

1359

1360
class Priority(ORMObject):
1361
    def __init__(self, priority=None, level=None):
1362 1363 1364 1365 1366 1367
        self.priority = priority
        self.level = level

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

1368 1369
    def __eq__(self, val):
        if isinstance(val, str):
A
Ansgar 已提交
1370
            warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
1371 1372 1373 1374 1375 1376
            return (self.priority == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
A
Ansgar 已提交
1377
            warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
1378 1379 1380 1381
            return (self.priority != val)
        # This signals to use the normal comparison operator
        return NotImplemented

1382 1383
    __hash__ = ORMObject.__hash__

1384

1385 1386
__all__.append('Priority')

1387

1388
@session_wrapper
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
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
    """
1403

1404
    q = session.query(Priority).filter_by(priority=priority)
A
Ansgar 已提交
1405
    return q.one_or_none()
1406

1407

1408 1409
__all__.append('get_priority')

1410

1411
@session_wrapper
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
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

1431

1432 1433
__all__.append('get_priorities')

M
Mark Hymers 已提交
1434 1435
################################################################################

1436

1437
from .database.section import Section
1438

1439 1440
__all__.append('Section')

1441

1442
@session_wrapper
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
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
    """
1457

1458
    q = session.query(Section).filter_by(section=section)
A
Ansgar 已提交
1459
    return q.one_or_none()
1460

1461

1462 1463
__all__.append('get_section')

1464

1465
@session_wrapper
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
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

1485

1486 1487
__all__.append('get_sections')

M
Mark Hymers 已提交
1488 1489
################################################################################

1490

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
class SignatureHistory(ORMObject):
    @classmethod
    def from_signed_file(cls, signed_file):
        """signature history entry from signed file

        @type  signed_file: L{daklib.gpg.SignedFile}
        @param signed_file: signed file

        @rtype: L{SignatureHistory}
        """
        self = cls()
        self.fingerprint = signed_file.primary_fingerprint
        self.signature_timestamp = signed_file.signature_timestamp
        self.contents_sha1 = signed_file.contents_sha1()
        return self

1507 1508 1509
    def query(self, session):
        return session.query(SignatureHistory).filter_by(fingerprint=self.fingerprint, signature_timestamp=self.signature_timestamp, contents_sha1=self.contents_sha1).first()

1510

1511 1512 1513 1514
__all__.append('SignatureHistory')

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

1515

1516
class SrcContents(ORMObject):
1517
    def __init__(self, file=None, source=None):
1518 1519 1520 1521 1522 1523
        self.file = file
        self.source = source

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

1524

1525 1526 1527 1528
__all__.append('SrcContents')

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

A
Ansgar Burchardt 已提交
1529

1530
class DBSource(ORMObject):
1531
    def __init__(self, source=None, version=None, maintainer=None,
1532
        changedby=None, poolfile=None, install_date=None, fingerprint=None):
T
Torsten Werner 已提交
1533 1534
        self.source = source
        self.version = version
1535 1536
        self.maintainer = maintainer
        self.changedby = changedby
T
Torsten Werner 已提交
1537 1538
        self.poolfile = poolfile
        self.install_date = install_date
1539
        self.fingerprint = fingerprint
M
Mark Hymers 已提交
1540

M
Mark Hymers 已提交
1541 1542 1543 1544
    @property
    def pkid(self):
        return self.source_id

1545 1546 1547 1548 1549 1550 1551 1552
    @property
    def name(self):
        return self.source

    @property
    def arch_string(self):
        return 'source'

1553
    def properties(self):
1554 1555
        return ['source', 'source_id', 'maintainer', 'changedby',
            'fingerprint', 'poolfile', 'version', 'suites_count',
1556
            'install_date', 'binaries_count', 'uploaders_count']
1557

M
Mark Hymers 已提交
1558
    def read_control_fields(self):
M
Mark Hymers 已提交
1559 1560 1561 1562
        '''
        Reads the control information from a dsc

        @rtype: tuple
M
Mark Hymers 已提交
1563
        @return: fields is the dsc information in a dictionary form
M
Mark Hymers 已提交
1564
        '''
1565 1566
        with open(self.poolfile.fullpath, 'r') as fd:
            fields = Deb822(fd)
M
Mark Hymers 已提交
1567 1568
        return fields

1569 1570
    metadata = association_proxy('key', 'value')

1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
    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():
1582
            name = force_to_utf8(name)
1583 1584 1585
            fileset.add(name)
        return fileset

1586 1587 1588 1589 1590 1591
    @property
    def proxy(self):
        session = object_session(self)
        query = session.query(SourceMetadata).filter_by(source=self)
        return MetadataProxy(session, query)

1592

1593
__all__.append('DBSource')
1594

1595

1596
@session_wrapper
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
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
    """

1608
    return session.query(Suite).filter(Suite.sources.any(source=source)).all()
1609

1610

1611 1612
__all__.append('get_suites_source_in')

T
Torsten Werner 已提交
1613 1614
# FIXME: This function fails badly if it finds more than 1 source package and
# its implementation is trivial enough to be inlined.
1615 1616


1617
@session_wrapper
1618
def get_source_in_suite(source, suite_name, session=None):
1619
    """
1620
    Returns a DBSource object for a combination of C{source} and C{suite_name}.
1621 1622

      - B{source} - source package name, eg. I{mailfilter}, I{bbdb}, I{glibc}
1623
      - B{suite_name} - a suite name, eg. I{unstable}
1624 1625 1626 1627

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

1628
    @type suite_name: string
1629
    @param suite_name: the suite name
1630 1631 1632 1633 1634

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

    """
1635 1636 1637
    suite = get_suite(suite_name, session)
    if suite is None:
        return None
A
Ansgar 已提交
1638
    return suite.get_sources(source).one_or_none()
1639

1640

1641 1642
__all__.append('get_source_in_suite')

1643

M
Mark Hymers 已提交
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
@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()

1669

M
Mark Hymers 已提交
1670 1671
__all__.append('import_metadata_into_db')

1672 1673
################################################################################

1674

1675 1676 1677 1678 1679 1680 1681
class SrcFormat(object):
    def __init__(self, *args, **kwargs):
        pass

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

1682

1683 1684 1685 1686
__all__.append('SrcFormat')

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

B
Bastian Blank 已提交
1687
SUITE_FIELDS = [('SuiteName', 'suite_name'),
M
Mark Hymers 已提交
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
                 ('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 已提交
1701
                 ('OverrideSuite', 'overridesuite')]
M
Mark Hymers 已提交
1702

T
Torsten Werner 已提交
1703 1704
# Why the heck don't we have any UNIQUE constraints in table suite?
# TODO: Add UNIQUE constraints for appropriate columns.
1705 1706


1707
class Suite(ORMObject):
1708
    def __init__(self, suite_name=None, version=None):
1709 1710
        self.suite_name = suite_name
        self.version = version
M
Mark Hymers 已提交
1711

1712
    def properties(self):
1713
        return ['suite_name', 'version', 'sources_count', 'binaries_count',
T
Torsten Werner 已提交
1714
            'overrides_count']
1715

1716 1717
    def __eq__(self, val):
        if isinstance(val, str):
A
Ansgar 已提交
1718
            warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
1719 1720 1721 1722 1723 1724
            return (self.suite_name == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
A
Ansgar 已提交
1725
            warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
1726 1727 1728 1729
            return (self.suite_name != val)
        # This signals to use the normal comparison operator
        return NotImplemented

1730 1731
    __hash__ = ORMObject.__hash__

M
Mark Hymers 已提交
1732 1733 1734 1735 1736 1737 1738 1739 1740
    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)

1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
    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)
        """

1757
        q = object_session(self).query(Architecture).with_parent(self)
1758 1759 1760 1761 1762 1763
        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 已提交
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
    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)
1779
        return session.query(DBSource).filter_by(source=source). \
1780
            with_parent(self)
T
Torsten Werner 已提交
1781

1782 1783 1784 1785 1786 1787
    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()

1788 1789 1790
    def update_last_changed(self):
        self.last_changed = sqlalchemy.func.now()

1791 1792 1793 1794
    @property
    def path(self):
        return os.path.join(self.archive.path, 'dists', self.suite_name)

1795 1796 1797 1798 1799 1800
    @property
    def release_suite_output(self):
        if self.release_suite is not None:
            return self.release_suite
        return self.suite_name

1801

1802 1803
__all__.append('Suite')

1804

1805
@session_wrapper
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
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 已提交
1818
    @return: Suite object for the requested suite name (None if not present)
1819
    """
1820

1821
    # Start by looking for the dak internal name
1822
    q = session.query(Suite).filter_by(suite_name=suite)
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
    try:
        return q.one()
    except NoResultFound:
        pass

    # Now try codename
    q = session.query(Suite).filter_by(codename=suite)
    try:
        return q.one()
    except NoResultFound:
        pass
1834

1835 1836
    # Finally give release_suite a try
    q = session.query(Suite).filter_by(release_suite=suite)
A
Ansgar 已提交
1837
    return q.one_or_none()
1838

1839

1840 1841
__all__.append('get_suite')

M
Mark Hymers 已提交
1842 1843
################################################################################

1844

1845
@session_wrapper
1846
def get_suite_architectures(suite, skipsrc=False, skipall=False, session=None):
M
Mark Hymers 已提交
1847
    """
1848 1849
    Returns list of Architecture objects for given C{suite} name. The list is
    empty if suite does not exist.
M
Mark Hymers 已提交
1850

J
Joerg Jaspert 已提交
1851 1852
    @type suite: str
    @param suite: Suite name to search for
M
Mark Hymers 已提交
1853

1854 1855 1856 1857 1858 1859 1860 1861
    @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 已提交
1862 1863 1864 1865 1866 1867 1868 1869
    @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)
    """

1870 1871 1872
    try:
        return get_suite(suite, session).get_architectures(skipsrc, skipall)
    except AttributeError:
1873
        return []
M
Mark Hymers 已提交
1874

1875

1876
__all__.append('get_suite_architectures')
M
Mark Hymers 已提交
1877

M
Mark Hymers 已提交
1878 1879
################################################################################

1880

1881
class Uid(ORMObject):
1882
    def __init__(self, uid=None, name=None):
T
Torsten Werner 已提交
1883 1884
        self.uid = uid
        self.name = name
M
Mark Hymers 已提交
1885

1886 1887
    def __eq__(self, val):
        if isinstance(val, str):
A
Ansgar 已提交
1888
            warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
1889 1890 1891 1892 1893 1894
            return (self.uid == val)
        # This signals to use the normal comparison operator
        return NotImplemented

    def __ne__(self, val):
        if isinstance(val, str):
A
Ansgar 已提交
1895
            warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
1896 1897 1898 1899
            return (self.uid != val)
        # This signals to use the normal comparison operator
        return NotImplemented

1900 1901
    __hash__ = ORMObject.__hash__

1902 1903 1904
    def properties(self):
        return ['uid', 'name', 'fingerprint']

1905

1906 1907
__all__.append('Uid')

1908

1909
@session_wrapper
M
Mark Hymers 已提交
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
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
    """
1927 1928 1929

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

1930 1931 1932
    try:
        ret = q.one()
    except NoResultFound:
1933 1934 1935
        uid = Uid()
        uid.uid = uidname
        session.add(uid)
1936
        session.commit_or_flush()
1937
        ret = uid
M
Mark Hymers 已提交
1938

1939
    return ret
M
Mark Hymers 已提交
1940

1941

M
Mark Hymers 已提交
1942 1943
__all__.append('get_or_set_uid')

1944

1945
@session_wrapper
1946 1947 1948 1949
def get_uid_from_fingerprint(fpr, session=None):
    q = session.query(Uid)
    q = q.join(Fingerprint).filter_by(fingerprint=fpr)

A
Ansgar 已提交
1950
    return q.one_or_none()
1951

1952

1953 1954
__all__.append('get_uid_from_fingerprint')

M
Mark Hymers 已提交
1955 1956
################################################################################

1957

T
Torsten Werner 已提交
1958
class MetadataKey(ORMObject):
1959
    def __init__(self, key=None):
T
Torsten Werner 已提交
1960 1961 1962 1963 1964
        self.key = key

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

1965

T
Torsten Werner 已提交
1966 1967
__all__.append('MetadataKey')

1968

M
Mark Hymers 已提交
1969 1970 1971 1972 1973 1974 1975
@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.

1976 1977
    @type keyname: string
    @param keyname: The keyname to add
M
Mark Hymers 已提交
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998

    @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

1999

M
Mark Hymers 已提交
2000 2001
__all__.append('get_or_set_metadatakey')

T
Torsten Werner 已提交
2002 2003
################################################################################

2004

T
Torsten Werner 已提交
2005
class BinaryMetadata(ORMObject):
2006
    def __init__(self, key=None, value=None, binary=None):
T
Torsten Werner 已提交
2007 2008
        self.key = key
        self.value = value
2009 2010
        if binary is not None:
            self.binary = binary
T
Torsten Werner 已提交
2011 2012 2013 2014

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

2015

T
Torsten Werner 已提交
2016 2017 2018 2019
__all__.append('BinaryMetadata')

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

2020

T
Torsten Werner 已提交
2021
class SourceMetadata(ORMObject):
2022
    def __init__(self, key=None, value=None, source=None):
T
Torsten Werner 已提交
2023 2024
        self.key = key
        self.value = value
2025 2026
        if source is not None:
            self.source = source
T
Torsten Werner 已提交
2027 2028 2029 2030

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

2031

T
Torsten Werner 已提交
2032 2033 2034 2035
__all__.append('SourceMetadata')

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

2036

2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
class MetadataProxy(object):
    def __init__(self, session, query):
        self.session = session
        self.query = query

    def _get(self, key):
        metadata_key = self.session.query(MetadataKey).filter_by(key=key).first()
        if metadata_key is None:
            return None
        metadata = self.query.filter_by(key=metadata_key).first()
        return metadata

    def __contains__(self, key):
        if self._get(key) is not None:
            return True
        return False

    def __getitem__(self, key):
        metadata = self._get(key)
        if metadata is None:
            raise KeyError
        return metadata.value

    def get(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            return default

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

2068

2069 2070
class VersionCheck(ORMObject):
    def __init__(self, *args, **kwargs):
2071
        pass
2072 2073 2074 2075 2076

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

2077

2078 2079
__all__.append('VersionCheck')

2080

2081
@session_wrapper
2082
def get_version_checks(suite_name, check=None, session=None):
2083 2084
    suite = get_suite(suite_name, session)
    if not suite:
M
Mark Hymers 已提交
2085 2086 2087
        # Make sure that what we return is iterable so that list comprehensions
        # involving this don't cause a traceback
        return []
2088 2089 2090 2091 2092
    q = session.query(VersionCheck).filter_by(suite=suite)
    if check:
        q = q.filter_by(check=check)
    return q.all()

2093

2094 2095 2096 2097
__all__.append('get_version_checks')

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

2098

2099
class DBConn(object):
M
Mark Hymers 已提交
2100
    """
2101
    database module init.
M
Mark Hymers 已提交
2102
    """
2103 2104
    __shared_state = {}

B
Bastian Blank 已提交
2105 2106
    db_meta = None

2107 2108
    tbl_architecture = Architecture.__table__

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 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 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
    tables = (
        'acl',
        'acl_architecture_map',
        'acl_fingerprint_map',
        'acl_per_source',
        'archive',
        'bin_associations',
        'bin_contents',
        'binaries',
        'binaries_metadata',
        'build_queue',
        'changelogs_text',
        'changes',
        'component',
        'component_suite',
        'config',
        'dsc_files',
        'external_files',
        'external_overrides',
        'external_signature_requests',
        'extra_src_references',
        'files',
        'files_archive_map',
        'fingerprint',
        'hashfile',
        'keyrings',
        'maintainer',
        'metadata_keys',
        'new_comments',
        # TODO: the maintainer column in table override should be removed.
        'override',
        'override_type',
        'policy_queue',
        'policy_queue_upload',
        'policy_queue_upload_binaries_map',
        'policy_queue_byhand_file',
        'priority',
        'signature_history',
        'source',
        'source_metadata',
        'src_associations',
        'src_contents',
        'src_format',
        'src_uploaders',
        'suite',
        'suite_acl_map',
        'suite_architectures',
        'suite_build_queue_copy',
        'suite_permission',
        'suite_src_formats',
        'uid',
        'version_check',
    )

    views = (
        'bin_associations_binaries',
        'changelogs',
        'newest_source',
        'newest_src_association',
        'package_list',
        'source_suite',
        'src_associations_src',
    )

M
Mark Hymers 已提交
2173
    def __init__(self, *args, **kwargs):
2174
        self.__dict__ = self.__shared_state
M
Mark Hymers 已提交
2175

2176 2177
        if not getattr(self, 'initialised', False):
            self.initialised = True
2178
            self.debug = 'debug' in kwargs
2179
            self.__createconn()
M
Mark Hymers 已提交
2180

M
Mark Hymers 已提交
2181
    def __setuptables(self):
2182
        for table_name in self.tables:
2183
            table = Table(table_name, self.db_meta,
2184
                autoload=True, extend_existing=True)
2185 2186
            setattr(self, 'tbl_%s' % table_name, table)

2187
        for view_name in self.views:
2188 2189 2190
            view = Table(view_name, self.db_meta, autoload=True)
            setattr(self, 'view_%s' % view_name, view)

M
Mark Hymers 已提交
2191
    def __setupmappers(self):
2192
        mapper(ACL, self.tbl_acl,
2193
               properties=dict(
2194 2195 2196 2197 2198
                   architectures=relation(Architecture, secondary=self.tbl_acl_architecture_map, collection_class=set),
                   fingerprints=relation(Fingerprint, secondary=self.tbl_acl_fingerprint_map, collection_class=set),
                   match_keyring=relation(Keyring, primaryjoin=(self.tbl_acl.c.match_keyring_id == self.tbl_keyrings.c.id)),
                   per_source=relation(ACLPerSource, collection_class=set),
                   ))
2199 2200

        mapper(ACLPerSource, self.tbl_acl_per_source,
2201
               properties=dict(
2202 2203 2204 2205
                   acl=relation(ACL),
                   fingerprint=relation(Fingerprint, primaryjoin=(self.tbl_acl_per_source.c.fingerprint_id == self.tbl_fingerprint.c.id)),
                   created_by=relation(Fingerprint, primaryjoin=(self.tbl_acl_per_source.c.created_by_id == self.tbl_fingerprint.c.id)),
                   ))
2206

M
Mark Hymers 已提交
2207
        mapper(Archive, self.tbl_archive,
2208 2209
               properties=dict(archive_id=self.tbl_archive.c.id,
                                 archive_name=self.tbl_archive.c.name))
M
Mike O'Connor 已提交
2210

2211
        mapper(ArchiveFile, self.tbl_files_archive_map,
2212 2213 2214
               properties=dict(archive=relation(Archive, backref='files'),
                                 component=relation(Component),
                                 file=relation(PoolFile, backref='archives')))
2215

2216
        mapper(BuildQueue, self.tbl_build_queue,
2217
               properties=dict(queue_id=self.tbl_build_queue.c.id,
2218
                                 suite=relation(Suite, primaryjoin=(self.tbl_build_queue.c.suite_id == self.tbl_suite.c.id))))
2219

2220
        mapper(DBBinary, self.tbl_binaries,
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
               properties=dict(binary_id=self.tbl_binaries.c.id,
                                 package=self.tbl_binaries.c.package,
                                 version=self.tbl_binaries.c.version,
                                 maintainer_id=self.tbl_binaries.c.maintainer,
                                 maintainer=relation(Maintainer),
                                 source_id=self.tbl_binaries.c.source,
                                 source=relation(DBSource, backref='binaries'),
                                 arch_id=self.tbl_binaries.c.architecture,
                                 architecture=relation(Architecture),
                                 poolfile_id=self.tbl_binaries.c.file,
                                 poolfile=relation(PoolFile),
                                 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,
                                 suites=relation(Suite, secondary=self.tbl_bin_associations,
M
Mark Hymers 已提交
2237
                                     backref=backref('binaries', lazy='dynamic')),
2238
                                 extra_sources=relation(DBSource, secondary=self.tbl_extra_src_references,
2239
                                     backref=backref('extra_binary_references', lazy='dynamic')),
2240
                                 key=relation(BinaryMetadata, cascade='all',
2241
                                     collection_class=attribute_mapped_collection('key'))),
2242
        )
M
Mark Hymers 已提交
2243 2244

        mapper(Component, self.tbl_component,
2245 2246
               properties=dict(component_id=self.tbl_component.c.id,
                                 component_name=self.tbl_component.c.name),
2247
        )
M
Mark Hymers 已提交
2248 2249

        mapper(DBConfig, self.tbl_config,
2250
               properties=dict(config_id=self.tbl_config.c.id))
M
Mark Hymers 已提交
2251 2252

        mapper(DSCFile, self.tbl_dsc_files,
2253 2254 2255 2256 2257
               properties=dict(dscfile_id=self.tbl_dsc_files.c.id,
                                 source_id=self.tbl_dsc_files.c.source,
                                 source=relation(DBSource),
                                 poolfile_id=self.tbl_dsc_files.c.file,
                                 poolfile=relation(PoolFile)))
M
Mark Hymers 已提交
2258

2259
        mapper(ExternalOverride, self.tbl_external_overrides,
2260 2261 2262 2263 2264
                properties=dict(
                    suite_id=self.tbl_external_overrides.c.suite,
                    suite=relation(Suite),
                    component_id=self.tbl_external_overrides.c.component,
                    component=relation(Component)))
A
Ansgar Burchardt 已提交
2265

M
Mark Hymers 已提交
2266
        mapper(PoolFile, self.tbl_files,
2267 2268
               properties=dict(file_id=self.tbl_files.c.id,
                                 filesize=self.tbl_files.c.size),
2269
        )
M
Mark Hymers 已提交
2270 2271

        mapper(Fingerprint, self.tbl_fingerprint,
2272 2273 2274 2275 2276 2277
               properties=dict(fingerprint_id=self.tbl_fingerprint.c.id,
                                 uid_id=self.tbl_fingerprint.c.uid,
                                 uid=relation(Uid),
                                 keyring_id=self.tbl_fingerprint.c.keyring,
                                 keyring=relation(Keyring),
                                 acl=relation(ACL)),
2278
        )
M
Mark Hymers 已提交
2279 2280

        mapper(Keyring, self.tbl_keyrings,
2281 2282 2283
               properties=dict(keyring_name=self.tbl_keyrings.c.name,
                                 keyring_id=self.tbl_keyrings.c.id,
                                 acl=relation(ACL, primaryjoin=(self.tbl_keyrings.c.acl_id == self.tbl_acl.c.id)))),
M
Mark Hymers 已提交
2284

M
Mark Hymers 已提交
2285
        mapper(DBChange, self.tbl_changes,
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
               properties=dict(change_id=self.tbl_changes.c.id,
                                 seen=self.tbl_changes.c.seen,
                                 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,
                                 version=self.tbl_changes.c.version))
J
Joerg Jaspert 已提交
2297

M
Mark Hymers 已提交
2298
        mapper(Maintainer, self.tbl_maintainer,
2299 2300
               properties=dict(maintainer_id=self.tbl_maintainer.c.id,
                   maintains_sources=relation(DBSource, backref='maintainer',
2301
                       primaryjoin=(self.tbl_maintainer.c.id == self.tbl_source.c.maintainer)),
2302
                   changed_sources=relation(DBSource, backref='changedby',
2303
                       primaryjoin=(self.tbl_maintainer.c.id == self.tbl_source.c.changedby))),
2304
        )
M
Mark Hymers 已提交
2305

M
Mark Hymers 已提交
2306
        mapper(NewComment, self.tbl_new_comments,
2307 2308
               properties=dict(comment_id=self.tbl_new_comments.c.id,
                                 policy_queue=relation(PolicyQueue)))
M
Mark Hymers 已提交
2309

M
Mark Hymers 已提交
2310
        mapper(Override, self.tbl_override,
2311
               properties=dict(suite_id=self.tbl_override.c.suite,
2312
                                 suite=relation(Suite,
T
Torsten Werner 已提交
2313
                                    backref=backref('overrides', lazy='dynamic')),
2314 2315
                                 package=self.tbl_override.c.package,
                                 component_id=self.tbl_override.c.component,
2316
                                 component=relation(Component,
2317
                                    backref=backref('overrides', lazy='dynamic')),
2318
                                 priority_id=self.tbl_override.c.priority,
2319
                                 priority=relation(Priority,
2320
                                    backref=backref('overrides', lazy='dynamic')),
2321
                                 section_id=self.tbl_override.c.section,
2322
                                 section=relation(Section,
2323
                                    backref=backref('overrides', lazy='dynamic')),
2324
                                 overridetype_id=self.tbl_override.c.type,
2325
                                 overridetype=relation(OverrideType,
2326
                                    backref=backref('overrides', lazy='dynamic'))))
M
Mark Hymers 已提交
2327 2328

        mapper(OverrideType, self.tbl_override_type,
2329 2330
               properties=dict(overridetype=self.tbl_override_type.c.type,
                                 overridetype_id=self.tbl_override_type.c.id))
M
Mark Hymers 已提交
2331

2332
        mapper(PolicyQueue, self.tbl_policy_queue,
2333 2334
               properties=dict(policy_queue_id=self.tbl_policy_queue.c.id,
                                 suite=relation(Suite, primaryjoin=(self.tbl_policy_queue.c.suite_id == self.tbl_suite.c.id))))
2335

2336
        mapper(PolicyQueueUpload, self.tbl_policy_queue_upload,
2337 2338 2339 2340 2341 2342
               properties=dict(
                   changes=relation(DBChange),
                   policy_queue=relation(PolicyQueue, backref='uploads'),
                   target_suite=relation(Suite),
                   source=relation(DBSource),
                   binaries=relation(DBBinary, secondary=self.tbl_policy_queue_upload_binaries_map),
2343
                   ))
2344 2345

        mapper(PolicyQueueByhandFile, self.tbl_policy_queue_byhand_file,
2346 2347
               properties=dict(
                   upload=relation(PolicyQueueUpload, backref='byhand'),
2348 2349 2350
                   )
               )

M
Mark Hymers 已提交
2351
        mapper(Priority, self.tbl_priority,
2352
               properties=dict(priority_id=self.tbl_priority.c.id))
M
Mark Hymers 已提交
2353

2354 2355
        mapper(SignatureHistory, self.tbl_signature_history)

2356
        mapper(DBSource, self.tbl_source,
2357 2358 2359 2360 2361 2362 2363 2364 2365
               properties=dict(source_id=self.tbl_source.c.id,
                                 version=self.tbl_source.c.version,
                                 maintainer_id=self.tbl_source.c.maintainer,
                                 poolfile_id=self.tbl_source.c.file,
                                 poolfile=relation(PoolFile),
                                 fingerprint_id=self.tbl_source.c.sig_fpr,
                                 fingerprint=relation(Fingerprint),
                                 changedby_id=self.tbl_source.c.changedby,
                                 srcfiles=relation(DSCFile,
2366
                                                     primaryjoin=(self.tbl_source.c.id == self.tbl_dsc_files.c.source)),
2367
                                 suites=relation(Suite, secondary=self.tbl_src_associations,
2368
                                     backref=backref('sources', lazy='dynamic')),
2369
                                 uploaders=relation(Maintainer,
2370
                                     secondary=self.tbl_src_uploaders),
2371
                                 key=relation(SourceMetadata, cascade='all',
2372
                                     collection_class=attribute_mapped_collection('key'))),
2373
        )
M
Mark Hymers 已提交
2374

2375
        mapper(SrcFormat, self.tbl_src_format,
2376 2377
               properties=dict(src_format_id=self.tbl_src_format.c.id,
                                 format_name=self.tbl_src_format.c.format_name))
2378

M
Mark Hymers 已提交
2379
        mapper(Suite, self.tbl_suite,
2380 2381 2382 2383 2384
               properties=dict(suite_id=self.tbl_suite.c.id,
                                 policy_queue=relation(PolicyQueue, primaryjoin=(self.tbl_suite.c.policy_queue_id == self.tbl_policy_queue.c.id)),
                                 new_queue=relation(PolicyQueue, primaryjoin=(self.tbl_suite.c.new_queue_id == self.tbl_policy_queue.c.id)),
                                 debug_suite=relation(Suite, remote_side=[self.tbl_suite.c.id]),
                                 copy_queues=relation(BuildQueue,
M
Mark Hymers 已提交
2385
                                     secondary=self.tbl_suite_build_queue_copy),
2386
                                 srcformats=relation(SrcFormat, secondary=self.tbl_suite_src_formats,
2387
                                     backref=backref('suites', lazy='dynamic')),
2388 2389 2390
                                 archive=relation(Archive, backref='suites'),
                                 acls=relation(ACL, secondary=self.tbl_suite_acl_map, collection_class=set),
                                 components=relation(Component, secondary=self.tbl_component_suite,
2391
                                                   order_by=self.tbl_component.c.ordering,
2392 2393 2394
                                                   backref=backref('suites')),
                                 architectures=relation(Architecture, secondary=self.tbl_suite_architectures,
                                     backref=backref('suites'))),
2395
        )
M
Mark Hymers 已提交
2396 2397

        mapper(Uid, self.tbl_uid,
2398 2399
               properties=dict(uid_id=self.tbl_uid.c.id,
                                 fingerprint=relation(Fingerprint)),
2400
        )
M
Mark Hymers 已提交
2401

2402
        mapper(BinContents, self.tbl_bin_contents,
2403 2404
            properties=dict(
                binary=relation(DBBinary,
2405
                    backref=backref('contents', lazy='dynamic', cascade='all')),
2406
                file=self.tbl_bin_contents.c.file))
2407

2408
        mapper(SrcContents, self.tbl_src_contents,
2409 2410
            properties=dict(
                source=relation(DBSource,
2411
                    backref=backref('contents', lazy='dynamic', cascade='all')),
2412
                file=self.tbl_src_contents.c.file))
2413

T
Torsten Werner 已提交
2414
        mapper(MetadataKey, self.tbl_metadata_keys,
2415 2416 2417
            properties=dict(
                key_id=self.tbl_metadata_keys.c.key_id,
                key=self.tbl_metadata_keys.c.key))
T
Torsten Werner 已提交
2418 2419

        mapper(BinaryMetadata, self.tbl_binaries_metadata,
2420 2421 2422 2423 2424 2425
            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))
T
Torsten Werner 已提交
2426 2427

        mapper(SourceMetadata, self.tbl_source_metadata,
2428 2429 2430 2431 2432 2433
            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))
T
Torsten Werner 已提交
2434

2435
        mapper(VersionCheck, self.tbl_version_check,
2436 2437
            properties=dict(
                suite_id=self.tbl_version_check.c.suite,
2438
                suite=relation(Suite, primaryjoin=self.tbl_version_check.c.suite == self.tbl_suite.c.id),
2439
                reference_id=self.tbl_version_check.c.reference,
2440
                reference=relation(Suite, primaryjoin=self.tbl_version_check.c.reference == self.tbl_suite.c.id, lazy='joined')))
2441

M
Mark Hymers 已提交
2442 2443
    ## Connection functions
    def __createconn(self):
2444
        from .config import Config
2445
        cnf = Config()
2446
        if "DB::Service" in cnf:
2447
            connstr = "postgresql://service=%s" % cnf["DB::Service"]
2448
        elif "DB::Host" in cnf:
M
Mark Hymers 已提交
2449
            # TCP/IP
2450
            connstr = "postgresql://%s" % cnf["DB::Host"]
2451
            if "DB::Port" in cnf and cnf["DB::Port"] != "-1":
M
Mark Hymers 已提交
2452 2453 2454 2455
                connstr += ":%s" % cnf["DB::Port"]
            connstr += "/%s" % cnf["DB::Name"]
        else:
            # Unix Socket
2456
            connstr = "postgresql:///%s" % cnf["DB::Name"]
2457
            if "DB::Port" in cnf and cnf["DB::Port"] != "-1":
M
Mark Hymers 已提交
2458
                connstr += "?port=%s" % cnf["DB::Port"]
2459

B
Bastian Blank 已提交
2460
        engine_args = {'echo': self.debug}
2461
        if 'DB::PoolSize' in cnf:
2462
            engine_args['pool_size'] = int(cnf['DB::PoolSize'])
2463
        if 'DB::MaxOverflow' in cnf:
2464
            engine_args['max_overflow'] = int(cnf['DB::MaxOverflow'])
2465 2466 2467 2468 2469 2470 2471 2472
        if six.PY2:
            # in python2, we want to get str() from the database
            # if we use the native unicode, we get unicode()
            if cnf.get('DB::Unicode') == 'false':
                engine_args['use_native_unicode'] = False
        else:
            # in python3, we don't support non-utf-8 connections
            engine_args['client_encoding'] = 'utf-8'
2473

2474 2475 2476
        # Monkey patch a new dialect in in order to support service= syntax
        import sqlalchemy.dialects.postgresql
        from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
2477

2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
        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

2489
        try:
2490
            self.db_pg = create_engine(connstr, **engine_args)
2491 2492 2493 2494
            self.db_smaker = sessionmaker(bind=self.db_pg,
                                          autoflush=True,
                                          autocommit=False)

B
Bastian Blank 已提交
2495 2496 2497 2498 2499
            if self.db_meta is None:
                self.__class__.db_meta = Base.metadata
                self.__class__.db_meta.bind = self.db_pg
                self.__setuptables()
                self.__setupmappers()
2500

2501
        except OperationalError as e:
B
Bastian Blank 已提交
2502
            from . import utils
2503
            utils.fubar("Cannot connect to database (%s)" % str(e))
M
Mark Hymers 已提交
2504

2505
        self.pid = os.getpid()
M
Mark Hymers 已提交
2506

2507
    def session(self, work_mem=0):
2508 2509 2510 2511 2512 2513
        '''
        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.
        '''
2514 2515 2516
        # reinitialize DBConn in new processes
        if self.pid != os.getpid():
            self.__createconn()
2517 2518 2519 2520
        session = self.db_smaker()
        if work_mem > 0:
            session.execute("SET LOCAL work_mem TO '%d MB'" % work_mem)
        return session
M
Mark Hymers 已提交
2521

2522

M
Mark Hymers 已提交
2523
__all__.append('DBConn')