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

3 4 5 6 7
""" DB access class

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

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

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

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

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

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

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

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

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

M
Mark Hymers 已提交
49 50 51
from datetime import datetime, timedelta
from errno import ENOENT
from tempfile import mkstemp, mkdtemp
M
Mark Hymers 已提交
52

53 54
from inspect import getargspec

55
import sqlalchemy
56
from sqlalchemy import create_engine, Table, MetaData, Column, Integer, desc
57
from sqlalchemy.orm import sessionmaker, mapper, relation, object_session, \
58
    backref, MapperExtension, EXT_CONTINUE, object_mapper
59
from sqlalchemy import types as sqltypes
M
Mark Hymers 已提交
60

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

65 66 67
# Only import Config until Queue stuff is changed to store its config
# in the database
from config import Config
M
Mark Hymers 已提交
68
from textutils import fix_maintainer
69
from dak_exceptions import DBUpdateError, NoSourceFieldError
M
Mark Hymers 已提交
70

71 72 73 74 75 76 77 78 79 80
# suppress some deprecation warnings in squeeze related to sqlalchemy
import warnings
warnings.filterwarnings('ignore', \
    "The SQLAlchemy PostgreSQL dialect has been renamed from 'postgres' to 'postgresql'.*", \
    SADeprecationWarning)
# TODO: sqlalchemy needs some extra configuration to correctly reflect
# the ind_deb_contents_* indexes - we ignore the warnings at the moment
warnings.filterwarnings("ignore", 'Predicate of partial index', SAWarning)


M
Mark Hymers 已提交
81 82
################################################################################

83 84 85
# Patch in support for the debversion field type so that it works during
# reflection

T
Torsten Werner 已提交
86 87 88 89 90 91 92 93
try:
    # that is for sqlalchemy 0.6
    UserDefinedType = sqltypes.UserDefinedType
except:
    # this one for sqlalchemy 0.5
    UserDefinedType = sqltypes.TypeEngine

class DebVersion(UserDefinedType):
94 95 96
    def get_col_spec(self):
        return "DEBVERSION"

97 98 99
    def bind_processor(self, dialect):
        return None

T
Torsten Werner 已提交
100 101
    # ' = None' is needed for sqlalchemy 0.5:
    def result_processor(self, dialect, coltype = None):
102 103
        return None

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

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

113
__all__ = ['IntegrityError', 'SQLAlchemyError', 'DebVersion']
114 115 116

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

117
def session_wrapper(fn):
C
Chris Lamb 已提交
118 119 120 121
    """
    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.
122 123 124 125

    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 已提交
126 127
    """

128 129 130
    def wrapped(*args, **kwargs):
        private_transaction = False

131
        # Find the session object
C
Chris Lamb 已提交
132 133 134
        session = kwargs.get('session')

        if session is None:
135 136 137 138 139 140 141
            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]
142
                if session is None:
M
fixup  
Mark Hymers 已提交
143
                    args = list(args)
144 145
                    session = args[-1] = DBConn().session()
                    private_transaction = True
146 147 148 149 150

        if private_transaction:
            session.commit_or_flush = session.commit
        else:
            session.commit_or_flush = session.flush
151 152 153 154 155 156

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

159 160 161
    wrapped.__doc__ = fn.__doc__
    wrapped.func_name = fn.func_name

162 163
    return wrapped

F
Frank Lichtenheld 已提交
164 165
__all__.append('session_wrapper')

166 167
################################################################################

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

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

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

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

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

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

248 249 250 251 252 253 254 255 256 257
    def not_null_constraints(self):
        '''
        Returns a list of properties that must be not NULL. Derived classes
        should override this method if needed.
        '''
        return []

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

258 259
    def validate(self):
        '''
260 261 262
        This function validates the not NULL constraints as returned by
        not_null_constraints(). It raises the DBUpdateError exception if
        validation fails.
263
        '''
264
        for property in self.not_null_constraints():
265 266 267 268 269 270
            # TODO: It is a bit awkward that the mapper configuration allow
            # directly setting the numeric _id columns. We should get rid of it
            # in the long run.
            if hasattr(self, property + '_id') and \
                getattr(self, property + '_id') is not None:
                continue
271 272 273
            if not hasattr(self, property) or getattr(self, property) is None:
                raise DBUpdateError(self.validation_message % \
                    (property, str(self)))
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    @classmethod
    @session_wrapper
    def get(cls, primary_key,  session = None):
        '''
        This is a support function that allows getting an object by its primary
        key.

        Architecture.get(3[, session])

        instead of the more verbose

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

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    def session(self, replace = False):
        '''
        Returns the current session that is associated with the object. May
        return None is object is in detached state.
        '''

        return object_session(self)

    def clone(self, session = None):
        '''
        Clones the current object in a new session and returns the new clone. A
        fresh session is created if the optional session parameter is not
        provided.

        RATIONALE: SQLAlchemy's session is not thread safe. This method allows
        cloning of an existing object to allow several threads to work with
        their own instances of an ORMObject.

        WARNING: Only persistent (committed) objects can be cloned.
        '''

        if session is None:
            session = DBConn().session()
        if self.session() is None:
            raise RuntimeError('Method clone() failed for detached object:\n%s' %
                self)
        self.session().flush()
        mapper = object_mapper(self)
        primary_key = mapper.primary_key_from_instance(self)
        object_class = self.__class__
        new_object = session.query(object_class).get(primary_key)
        if new_object is None:
            raise RuntimeError( \
                'Method clone() failed for non-persistent object:\n%s' % self)
        return new_object

326 327 328 329
__all__.append('ORMObject')

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

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
class Validator(MapperExtension):
    '''
    This class calls the validate() method for each instance for the
    'before_update' and 'before_insert' events. A global object validator is
    used for configuring the individual mappers.
    '''

    def before_update(self, mapper, connection, instance):
        instance.validate()
        return EXT_CONTINUE

    def before_insert(self, mapper, connection, instance):
        instance.validate()
        return EXT_CONTINUE

validator = Validator()

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

349
class Architecture(ORMObject):
T
Torsten Werner 已提交
350 351 352
    def __init__(self, arch_string = None, description = None):
        self.arch_string = arch_string
        self.description = description
M
Mark Hymers 已提交
353

354 355 356 357 358 359 360 361 362 363 364 365
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.arch_string== val)
        # This signals to use the normal comparison operator
        return NotImplemented

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

366 367
    def properties(self):
        return ['arch_string', 'arch_id', 'suites_count']
M
Mark Hymers 已提交
368

369 370
    def not_null_constraints(self):
        return ['arch_string']
371

372 373
__all__.append('Architecture')

374
@session_wrapper
375 376 377 378 379 380 381 382 383 384 385 386 387 388
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)
    """
389

390
    q = session.query(Architecture).filter_by(arch_string=architecture)
391

392 393 394 395
    try:
        return q.one()
    except NoResultFound:
        return None
396

397 398
__all__.append('get_architecture')

399
# TODO: should be removed because the implementation is too trivial
400
@session_wrapper
M
Mark Hymers 已提交
401 402 403 404
def get_architecture_suites(architecture, session=None):
    """
    Returns list of Suite objects for given C{architecture} name

J
Joerg Jaspert 已提交
405 406
    @type architecture: str
    @param architecture: Architecture name to search for
M
Mark Hymers 已提交
407 408 409 410 411 412 413 414 415

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

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

416
    return get_architecture(architecture, session).suites
M
Mark Hymers 已提交
417

418 419
__all__.append('get_architecture_suites')

M
Mark Hymers 已提交
420 421
################################################################################

M
Mark Hymers 已提交
422
class Archive(object):
M
Mark Hymers 已提交
423 424
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
425 426

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

429 430
__all__.append('Archive')

431
@session_wrapper
432 433
def get_archive(archive, session=None):
    """
F
Frank Lichtenheld 已提交
434
    returns database id for given C{archive}.
435 436 437 438 439 440 441 442 443 444 445 446 447

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

449
    q = session.query(Archive).filter_by(archive_name=archive)
450

451 452 453 454
    try:
        return q.one()
    except NoResultFound:
        return None
455

456
__all__.append('get_archive')
457

M
Mark Hymers 已提交
458 459
################################################################################

M
Mike O'Connor 已提交
460 461 462 463 464 465 466 467 468 469 470
class BinContents(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<BinContents (%s, %s)>' % (self.binary, self.filename)

__all__.append('BinContents')

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

471 472 473 474 475 476 477 478 479 480 481
class DBBinary(ORMObject):
    def __init__(self, package = None, source = None, version = None, \
        maintainer = None, architecture = None, poolfile = None, \
        binarytype = 'deb'):
        self.package = package
        self.source = source
        self.version = version
        self.maintainer = maintainer
        self.architecture = architecture
        self.poolfile = poolfile
        self.binarytype = binarytype
M
Mark Hymers 已提交
482

483 484 485
    def properties(self):
        return ['package', 'version', 'maintainer', 'source', 'architecture', \
            'poolfile', 'binarytype', 'fingerprint', 'install_date', \
486
            'suites_count', 'binary_id']
487 488

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

492 493 494
    def get_component_name(self):
        return self.poolfile.location.component.component_name

495
__all__.append('DBBinary')
496

497
@session_wrapper
498 499 500 501
def get_suites_binary_in(package, session=None):
    """
    Returns list of Suite objects which given C{package} name is in

J
Joerg Jaspert 已提交
502 503
    @type package: str
    @param package: DBBinary package name to search for
504 505 506 507 508

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

509
    return session.query(Suite).filter(Suite.binaries.any(DBBinary.package == package)).all()
510 511 512

__all__.append('get_suites_binary_in')

513
@session_wrapper
514
def get_component_by_package_suite(package, suite_list, arch_list=[], session=None):
515 516
    '''
    Returns the component name of the newest binary package in suite_list or
517 518
    None if no package is found. The result can be optionally filtered by a list
    of architecture names.
519 520 521

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

523 524 525
    @type suite_list: list of str
    @param suite_list: list of suite_name items

526 527 528
    @type arch_list: list of str
    @param arch_list: optional list of arch_string items that defaults to []

529 530 531 532
    @rtype: str or NoneType
    @return: name of component or None
    '''

533 534 535 536 537 538
    q = session.query(DBBinary).filter_by(package = package). \
        join(DBBinary.suites).filter(Suite.suite_name.in_(suite_list))
    if len(arch_list) > 0:
        q = q.join(DBBinary.architecture). \
            filter(Architecture.arch_string.in_(arch_list))
    binary = q.order_by(desc(DBBinary.version)).first()
539 540 541 542
    if binary is None:
        return None
    else:
        return binary.get_component_name()
543 544

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

M
Mark Hymers 已提交
546 547
################################################################################

548 549 550 551
class BinaryACL(object):
    def __init__(self, *args, **kwargs):
        pass

552 553 554
    def __repr__(self):
        return '<BinaryACL %s>' % self.binary_acl_id

555 556 557 558 559 560 561 562
__all__.append('BinaryACL')

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

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

563 564 565
    def __repr__(self):
        return '<BinaryACLMap %s>' % self.binary_acl_map_id

566 567 568 569
__all__.append('BinaryACLMap')

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

M
Mark Hymers 已提交
570 571 572 573
MINIMAL_APT_CONF="""
Dir
{
   ArchiveDir "%(archivepath)s";
J
Joerg Jaspert 已提交
574 575
   OverrideDir "%(overridedir)s";
   CacheDir "%(cachedir)s";
M
Mark Hymers 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
};

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

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

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

   FileList "%(filelist)s";

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

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

609 610 611 612 613
class BuildQueue(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
614
        return '<BuildQueue %s>' % self.queue_name
615

M
Mark Hymers 已提交
616
    def write_metadata(self, starttime, force=False):
M
Mark Hymers 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629
        # Do we write out metafiles?
        if not (force or self.generate_metadata):
            return

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

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

        try:
            # Grab files we want to include
M
Mark Hymers 已提交
630
            newer = session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id).filter(BuildQueueFile.lastused + timedelta(seconds=self.stay_of_execution) > starttime).all()
M
Mark Hymers 已提交
631 632 633 634 635 636
            # Write file list with newer files
            (fl_fd, fl_name) = mkstemp()
            for n in newer:
                os.write(fl_fd, '%s\n' % n.fullpath)
            os.close(fl_fd)

J
Joerg Jaspert 已提交
637 638
            cnf = Config()

M
Mark Hymers 已提交
639 640 641 642
            # Write minimal apt.conf
            # TODO: Remove hardcoding from template
            (ac_fd, ac_name) = mkstemp()
            os.write(ac_fd, MINIMAL_APT_CONF % {'archivepath': self.path,
J
Joerg Jaspert 已提交
643 644 645 646
                                                'filelist': fl_name,
                                                'cachedir': cnf["Dir::Cache"],
                                                'overridedir': cnf["Dir::Override"],
                                                })
M
Mark Hymers 已提交
647
            os.close(ac_fd)
M
Mark Hymers 已提交
648 649

            # Run apt-ftparchive generate
M
Mark Hymers 已提交
650 651
            os.chdir(os.path.dirname(ac_name))
            os.system('apt-ftparchive -qq -o APT::FTPArchive::Contents=off generate %s' % os.path.basename(ac_name))
M
Mark Hymers 已提交
652 653 654 655 656 657

            # Run apt-ftparchive release
            # TODO: Eww - fix this
            bname = os.path.basename(self.path)
            os.chdir(self.path)
            os.chdir('..')
658 659 660 661 662 663 664 665

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

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

J
Joerg Jaspert 已提交
668 669 670 671 672 673
            # Crude hack with open and append, but this whole section is and should be redone.
            if self.notautomatic:
                release=open("Release", "a")
                release.write("NotAutomatic: yes")
                release.close()

M
Mark Hymers 已提交
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
            # Sign if necessary
            if self.signingkey:
                keyring = "--secret-keyring \"%s\"" % cnf["Dinstall::SigningKeyring"]
                if cnf.has_key("Dinstall::SigningPubKeyring"):
                    keyring += " --keyring \"%s\"" % cnf["Dinstall::SigningPubKeyring"]

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

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

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

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

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

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

M
Mark Hymers 已提交
714
    def clean_and_update(self, starttime, Logger, dryrun=False):
M
Mark Hymers 已提交
715 716 717
        """WARNING: This routine commits for you"""
        session = DBConn().session().object_session(self)

M
Mark Hymers 已提交
718
        if self.generate_metadata and not dryrun:
M
Mark Hymers 已提交
719
            self.write_metadata(starttime)
M
Mark Hymers 已提交
720 721

        # Grab files older than our execution time
M
Mark Hymers 已提交
722
        older = session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id).filter(BuildQueueFile.lastused + timedelta(seconds=self.stay_of_execution) <= starttime).all()
M
Mark Hymers 已提交
723 724 725 726 727

        for o in older:
            killdb = False
            try:
                if dryrun:
M
Mark Hymers 已提交
728
                    Logger.log(["I: Would have removed %s from the queue" % o.fullpath])
M
Mark Hymers 已提交
729
                else:
M
Mark Hymers 已提交
730
                    Logger.log(["I: Removing %s from the queue" % o.fullpath])
M
Mark Hymers 已提交
731 732 733 734 735 736 737 738
                    os.unlink(o.fullpath)
                    killdb = True
            except OSError, e:
                # If it wasn't there, don't worry
                if e.errno == ENOENT:
                    killdb = True
                else:
                    # TODO: Replace with proper logging call
M
Mark Hymers 已提交
739
                    Logger.log(["E: Could not remove %s" % o.fullpath])
M
Mark Hymers 已提交
740 741 742 743 744 745

            if killdb:
                session.delete(o)

        session.commit()

M
Mark Hymers 已提交
746
        for f in os.listdir(self.path):
J
Joerg Jaspert 已提交
747
            if f.startswith('Packages') or f.startswith('Source') or f.startswith('Release') or f.startswith('advisory'):
M
Mark Hymers 已提交
748 749 750 751 752 753 754
                continue

            try:
                r = session.query(BuildQueueFile).filter_by(build_queue_id = self.queue_id).filter_by(filename = f).one()
            except NoResultFound:
                fp = os.path.join(self.path, f)
                if dryrun:
M
Mark Hymers 已提交
755
                    Logger.log(["I: Would remove unused link %s" % fp])
M
Mark Hymers 已提交
756
                else:
M
Mark Hymers 已提交
757
                    Logger.log(["I: Removing unused link %s" % fp])
M
Mark Hymers 已提交
758 759 760
                    try:
                        os.unlink(fp)
                    except OSError:
M
Mark Hymers 已提交
761
                        Logger.log(["E: Failed to unlink unreferenced file %s" % r.fullpath])
M
Mark Hymers 已提交
762

763 764 765 766 767 768 769 770 771 772 773
    def add_file_from_pool(self, poolfile):
        """Copies a file into the pool.  Assumes that the PoolFile object is
        attached to the same SQLAlchemy session as the Queue object is.

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

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

M
Mark Hymers 已提交
780 781
        # Prepare BuildQueueFile object
        qf = BuildQueueFile()
M
hmm...  
Mark Hymers 已提交
782
        qf.build_queue_id = self.queue_id
783
        qf.lastused = datetime.now()
784
        qf.filename = poolfile_basename
785

M
Mark Hymers 已提交
786
        targetpath = poolfile.fullpath
787 788 789
        queuepath = os.path.join(self.path, poolfile_basename)

        try:
M
Mark Hymers 已提交
790
            if self.copy_files:
791 792
                # We need to copy instead of symlink
                import utils
M
Mark Hymers 已提交
793
                utils.copy(targetpath, queuepath)
794 795 796
                # NULL in the fileid field implies a copy
                qf.fileid = None
            else:
M
Mark Hymers 已提交
797
                os.symlink(targetpath, queuepath)
798 799 800 801 802 803 804 805 806 807 808 809 810
                qf.fileid = poolfile.file_id
        except OSError:
            return None

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

        return qf


__all__.append('BuildQueue')

@session_wrapper
811
def get_build_queue(queuename, session=None):
812
    """
813
    Returns BuildQueue object for given C{queue name}, creating it if it does not
814 815 816 817 818 819 820 821 822
    exist.

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

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

823 824
    @rtype: BuildQueue
    @return: BuildQueue object for the given queue
825 826
    """

827
    q = session.query(BuildQueue).filter_by(queue_name=queuename)
828 829 830 831 832 833

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

834
__all__.append('get_build_queue')
835 836 837 838 839 840 841 842

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

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

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

M
Mark Hymers 已提交
845 846 847 848
    @property
    def fullpath(self):
        return os.path.join(self.buildqueue.path, self.filename)

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

__all__.append('BuildQueueFile')

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

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

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

__all__.append('ChangePendingBinary')

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

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

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

__all__.append('ChangePendingFile')

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

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

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

__all__.append('ChangePendingSource')

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

887 888 889
class Component(ORMObject):
    def __init__(self, component_name = None):
        self.component_name = component_name
M
Mark Hymers 已提交
890

891 892 893 894 895 896 897 898 899 900 901 902
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.component_name == val)
        # This signals to use the normal comparison operator
        return NotImplemented

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

903 904 905 906 907 908
    def properties(self):
        return ['component_name', 'component_id', 'description', 'location', \
            'meets_dfsg']

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

910 911 912

__all__.append('Component')

913
@session_wrapper
914 915 916 917 918 919 920 921 922 923 924 925
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()
926

927
    q = session.query(Component).filter_by(component_name=component)
928

929 930 931 932
    try:
        return q.one()
    except NoResultFound:
        return None
933

934 935
__all__.append('get_component')

M
Mark Hymers 已提交
936 937
################################################################################

M
Mark Hymers 已提交
938
class DBConfig(object):
M
Mark Hymers 已提交
939 940
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
941 942 943 944

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

945 946
__all__.append('DBConfig')

M
Mark Hymers 已提交
947 948
################################################################################

949
@session_wrapper
950 951 952 953 954 955 956 957 958 959
def get_or_set_contents_file_id(filename, session=None):
    """
    Returns database id for given filename.

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

    @type filename: string
    @param filename: The filename
    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
M
Mark Hymers 已提交
960 961
    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.
962 963 964 965 966

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

967
    q = session.query(ContentFilename).filter_by(filename=filename)
968 969 970 971

    try:
        ret = q.one().cafilename_id
    except NoResultFound:
972 973 974
        cf = ContentFilename()
        cf.filename = filename
        session.add(cf)
975
        session.commit_or_flush()
976
        ret = cf.cafilename_id
977

978
    return ret
979 980 981

__all__.append('get_or_set_contents_file_id')

982
@session_wrapper
M
Mark Hymers 已提交
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
def get_contents(suite, overridetype, section=None, session=None):
    """
    Returns contents for a suite / overridetype combination, limiting
    to a section if not None.

    @type suite: Suite
    @param suite: Suite object

    @type overridetype: OverrideType
    @param overridetype: OverrideType object

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

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

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

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

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

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

    contents_q += " ORDER BY fn"

1029
    return session.execute(contents_q, vals)
M
Mark Hymers 已提交
1030 1031 1032

__all__.append('get_contents')

M
Mark Hymers 已提交
1033 1034
################################################################################

M
Mark Hymers 已提交
1035
class ContentFilepath(object):
M
Mark Hymers 已提交
1036 1037
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1038 1039 1040 1041

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

1042 1043
__all__.append('ContentFilepath')

1044
@session_wrapper
M
Mark Hymers 已提交
1045
def get_or_set_contents_path_id(filepath, session=None):
1046 1047 1048 1049 1050
    """
    Returns database id for given path.

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

J
Joerg Jaspert 已提交
1051 1052 1053
    @type filepath: string
    @param filepath: The filepath

1054 1055
    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
M
Mark Hymers 已提交
1056 1057
    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.
1058 1059 1060 1061 1062

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

1063
    q = session.query(ContentFilepath).filter_by(filepath=filepath)
1064 1065 1066 1067

    try:
        ret = q.one().cafilepath_id
    except NoResultFound:
1068 1069 1070
        cf = ContentFilepath()
        cf.filepath = filepath
        session.add(cf)
1071
        session.commit_or_flush()
1072
        ret = cf.cafilepath_id
1073

1074
    return ret
1075 1076 1077

__all__.append('get_or_set_contents_path_id')

M
Mark Hymers 已提交
1078 1079
################################################################################

1080
class ContentAssociation(object):
M
Mark Hymers 已提交
1081 1082
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1083 1084 1085 1086

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

1087 1088
__all__.append('ContentAssociation')

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
def insert_content_paths(binary_id, fullpaths, session=None):
    """
    Make sure given path is associated with given binary id

    @type binary_id: int
    @param binary_id: the id of the binary
    @type fullpaths: list
    @param fullpaths: the list of paths of the file being associated with the binary
    @type session: SQLAlchemy session
    @param session: Optional SQLAlchemy session.  If this is passed, the caller
    is responsible for ensuring a transaction has begun and committing the
    results or rolling back based on the result code.  If not passed, a commit
M
Mark Hymers 已提交
1101 1102
    will be performed at the end of the function, otherwise the caller is
    responsible for commiting.
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

    @return: True upon success
    """

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

    try:
M
Mark Hymers 已提交
1113
        # Insert paths
1114 1115 1116 1117 1118
        def generate_path_dicts():
            for fullpath in fullpaths:
                if fullpath.startswith( './' ):
                    fullpath = fullpath[2:]

1119
                yield {'filename':fullpath, 'id': binary_id }
1120

1121 1122 1123
        for d in generate_path_dicts():
            session.execute( "INSERT INTO bin_contents ( file, binary_id ) VALUES ( :filename, :id )",
                         d )
1124

M
Mike O'Connor 已提交
1125
        session.commit()
1126
        if privatetrans:
M
Mark Hymers 已提交
1127
            session.close()
1128
        return True
M
Mark Hymers 已提交
1129

1130 1131 1132 1133 1134 1135
    except:
        traceback.print_exc()

        # Only rollback if we set up the session ourself
        if privatetrans:
            session.rollback()
M
Mark Hymers 已提交
1136
            session.close()
1137 1138 1139 1140 1141

        return False

__all__.append('insert_content_paths')

M
Mark Hymers 已提交
1142 1143
################################################################################

M
Mark Hymers 已提交
1144
class DSCFile(object):
M
Mark Hymers 已提交
1145 1146
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1147 1148 1149 1150

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

1151 1152
__all__.append('DSCFile')

1153
@session_wrapper
M
Mark Hymers 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
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)

1182
    return q.all()
M
Mark Hymers 已提交
1183 1184 1185

__all__.append('get_dscfiles')

M
Mark Hymers 已提交
1186 1187
################################################################################

1188
class PoolFile(ORMObject):
1189 1190 1191 1192 1193 1194
    def __init__(self, filename = None, location = None, filesize = -1, \
        md5sum = None):
        self.filename = filename
        self.location = location
        self.filesize = filesize
        self.md5sum = md5sum
M
Mark Hymers 已提交
1195

M
Mark Hymers 已提交
1196 1197 1198 1199
    @property
    def fullpath(self):
        return os.path.join(self.location.path, self.filename)

1200
    def is_valid(self, filesize = -1, md5sum = None):
1201
        return self.filesize == long(filesize) and self.md5sum == md5sum
T
Torsten Werner 已提交
1202

1203 1204
    def properties(self):
        return ['filename', 'file_id', 'filesize', 'md5sum', 'sha1sum', \
1205
            'sha256sum', 'location', 'source', 'binary', 'last_used']
1206

1207 1208
    def not_null_constraints(self):
        return ['filename', 'md5sum', 'location']
T
Torsten Werner 已提交
1209

1210 1211
__all__.append('PoolFile')

1212
@session_wrapper
1213 1214 1215
def check_poolfile(filename, filesize, md5sum, location_id, session=None):
    """
    Returns a tuple:
T
Torsten Werner 已提交
1216
    (ValidFileFound [boolean], PoolFile object or None)
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231

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

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

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

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

    @rtype: tuple
    @return: Tuple of length 2.
J
Joerg Jaspert 已提交
1232 1233 1234 1235
                 - If valid pool file found: (C{True}, C{PoolFile object})
                 - If valid pool file not found:
                     - (C{False}, C{None}) if no file found
                     - (C{False}, C{PoolFile object}) if file found with size/md5sum mismatch
1236 1237
    """

T
Torsten Werner 已提交
1238 1239 1240 1241 1242
    poolfile = session.query(Location).get(location_id). \
        files.filter_by(filename=filename).first()
    valid = False
    if poolfile and poolfile.is_valid(filesize = filesize, md5sum = md5sum):
        valid = True
1243

T
Torsten Werner 已提交
1244
    return (valid, poolfile)
1245 1246 1247

__all__.append('check_poolfile')

T
Torsten Werner 已提交
1248 1249
# TODO: the implementation can trivially be inlined at the place where the
# function is called
1250
@session_wrapper
M
Mark Hymers 已提交
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
def get_poolfile_by_id(file_id, session=None):
    """
    Returns a PoolFile objects or None for the given id

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

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

T
Torsten Werner 已提交
1262
    return session.query(PoolFile).get(file_id)
M
Mark Hymers 已提交
1263 1264 1265

__all__.append('get_poolfile_by_id')

1266
@session_wrapper
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
def get_poolfile_like_name(filename, session=None):
    """
    Returns an array of PoolFile objects which are like the given name

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

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

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

1281
    return q.all()
1282 1283 1284

__all__.append('get_poolfile_like_name')

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
@session_wrapper
def add_poolfile(filename, datadict, location_id, session=None):
    """
    Add a new file to the pool

    @type filename: string
    @param filename: filename

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

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

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

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

    return poolfile

__all__.append('add_poolfile')

M
Mark Hymers 已提交
1318 1319
################################################################################

1320
class Fingerprint(ORMObject):
T
Torsten Werner 已提交
1321 1322
    def __init__(self, fingerprint = None):
        self.fingerprint = fingerprint
M
Mark Hymers 已提交
1323

1324 1325 1326 1327 1328 1329
    def properties(self):
        return ['fingerprint', 'fingerprint_id', 'keyring', 'uid', \
            'binary_reject']

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

1331 1332
__all__.append('Fingerprint')

M
Mark Hymers 已提交
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
@session_wrapper
def get_fingerprint(fpr, session=None):
    """
    Returns Fingerprint object for given fpr.

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

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

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

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

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

    return ret

__all__.append('get_fingerprint')

1360
@session_wrapper
M
Mark Hymers 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
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
    """

1380
    q = session.query(Fingerprint).filter_by(fingerprint=fpr)
1381 1382 1383 1384

    try:
        ret = q.one()
    except NoResultFound:
1385 1386 1387
        fingerprint = Fingerprint()
        fingerprint.fingerprint = fpr
        session.add(fingerprint)
1388
        session.commit_or_flush()
1389
        ret = fingerprint
M
Mark Hymers 已提交
1390

1391
    return ret
M
Mark Hymers 已提交
1392 1393 1394

__all__.append('get_or_set_fingerprint')

M
Mark Hymers 已提交
1395 1396
################################################################################

M
Mark Hymers 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
# Helper routine for Keyring class
def get_ldap_name(entry):
    name = []
    for k in ["cn", "mn", "sn"]:
        ret = entry.get(k)
        if ret and ret[0] != "" and ret[0] != "-":
            name.append(ret[0])
    return " ".join(name)

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

M
Mark Hymers 已提交
1408
class Keyring(object):
M
Mark Hymers 已提交
1409 1410 1411 1412 1413 1414
    gpg_invocation = "gpg --no-default-keyring --keyring %s" +\
                     " --with-colons --fingerprint --fingerprint"

    keys = {}
    fpr_lookup = {}

M
Mark Hymers 已提交
1415 1416
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1417 1418 1419 1420

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

1421 1422
    def de_escape_gpg_str(self, txt):
        esclist = re.split(r'(\\x..)', txt)
M
Mark Hymers 已提交
1423 1424 1425 1426
        for x in range(1,len(esclist),2):
            esclist[x] = "%c" % (int(esclist[x][2:],16))
        return "".join(esclist)

T
Torsten Werner 已提交
1427 1428
    def parse_address(self, uid):
        """parses uid and returns a tuple of real name and email address"""
M
Mark Hymers 已提交
1429
        import email.Utils
T
Torsten Werner 已提交
1430 1431 1432 1433 1434 1435
        (name, address) = email.Utils.parseaddr(uid)
        name = re.sub(r"\s*[(].*[)]", "", name)
        name = self.de_escape_gpg_str(name)
        if name == "":
            name = uid
        return (name, address)
M
Mark Hymers 已提交
1436

T
Torsten Werner 已提交
1437
    def load_keys(self, keyring):
M
Mark Hymers 已提交
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
        if not self.keyring_id:
            raise Exception('Must be initialized with database information')

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

        for line in k.xreadlines():
            field = line.split(":")
            if field[0] == "pub":
                key = field[4]
T
Torsten Werner 已提交
1449 1450 1451 1452
                self.keys[key] = {}
                (name, addr) = self.parse_address(field[9])
                if "@" in addr:
                    self.keys[key]["email"] = addr
M
Mark Hymers 已提交
1453 1454 1455 1456 1457 1458
                    self.keys[key]["name"] = name
                self.keys[key]["fingerprints"] = []
                signingkey = True
            elif key and field[0] == "sub" and len(field) >= 12:
                signingkey = ("s" in field[11])
            elif key and field[0] == "uid":
T
Torsten Werner 已提交
1459 1460 1461 1462
                (name, addr) = self.parse_address(field[9])
                if "email" not in self.keys[key] and "@" in addr:
                    self.keys[key]["email"] = addr
                    self.keys[key]["name"] = name
M
Mark Hymers 已提交
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
            elif signingkey and field[0] == "fpr":
                self.keys[key]["fingerprints"].append(field[9])
                self.fpr_lookup[field[9]] = key

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

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

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

        ldap_fin_uid_id = {}

        byuid = {}
        byname = {}

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

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

        return (byname, byuid)

    def generate_users_from_keyring(self, format, session):
        byuid = {}
        byname = {}
        any_invalid = False
        for x in self.keys.keys():
T
Torsten Werner 已提交
1510
            if "email" not in self.keys[x]:
M
Mark Hymers 已提交
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
                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)

1528 1529
__all__.append('Keyring')

1530
@session_wrapper
M
Mark Hymers 已提交
1531
def get_keyring(keyring, session=None):
1532
    """
M
Mark Hymers 已提交
1533
    If C{keyring} does not have an entry in the C{keyrings} table yet, return None
1534 1535 1536 1537 1538 1539 1540 1541 1542
    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
    """

1543
    q = session.query(Keyring).filter_by(keyring_name=keyring)
1544

1545 1546 1547
    try:
        return q.one()
    except NoResultFound:
M
Mark Hymers 已提交
1548
        return None
1549

M
Mark Hymers 已提交
1550
__all__.append('get_keyring')
1551

M
Mark Hymers 已提交
1552
################################################################################
1553

M
Mark Hymers 已提交
1554 1555 1556 1557 1558 1559 1560 1561
class KeyringACLMap(object):
    def __init__(self, *args, **kwargs):
        pass

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

__all__.append('KeyringACLMap')
1562

M
Mark Hymers 已提交
1563 1564
################################################################################

M
Mark Hymers 已提交
1565
class DBChange(object):
J
Joerg Jaspert 已提交
1566 1567 1568 1569
    def __init__(self, *args, **kwargs):
        pass

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

1572 1573 1574 1575
    def clean_from_queue(self):
        session = DBConn().session().object_session(self)

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

M
Mark Hymers 已提交
1578 1579
        # Remove changes_pending_files references
        self.files = []
1580 1581 1582 1583 1584

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

M
Mark Hymers 已提交
1585
__all__.append('DBChange')
J
Joerg Jaspert 已提交
1586 1587

@session_wrapper
M
Mark Hymers 已提交
1588
def get_dbchange(filename, session=None):
J
Joerg Jaspert 已提交
1589
    """
M
Mark Hymers 已提交
1590
    returns DBChange object for given C{filename}.
J
Joerg Jaspert 已提交
1591

J
Joerg Jaspert 已提交
1592 1593
    @type filename: string
    @param filename: the name of the file
J
Joerg Jaspert 已提交
1594 1595 1596 1597 1598

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

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

J
Joerg Jaspert 已提交
1602
    """
M
Mark Hymers 已提交
1603
    q = session.query(DBChange).filter_by(changesname=filename)
J
Joerg Jaspert 已提交
1604 1605 1606 1607 1608 1609

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

M
Mark Hymers 已提交
1610
__all__.append('get_dbchange')
1611

M
Mark Hymers 已提交
1612 1613
################################################################################

1614
class Location(ORMObject):
1615
    def __init__(self, path = None, component = None):
1616
        self.path = path
1617
        self.component = component
1618 1619
        # the column 'type' should go away, see comment at mapper
        self.archive_type = 'pool'
M
Mark Hymers 已提交
1620

1621
    def properties(self):
1622 1623
        return ['path', 'location_id', 'archive_type', 'component', \
            'files_count']
1624 1625 1626

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

1628 1629
__all__.append('Location')

1630
@session_wrapper
1631 1632 1633 1634 1635 1636
def get_location(location, component=None, archive=None, session=None):
    """
    Returns Location object for the given combination of location, component
    and archive

    @type location: string
J
Joerg Jaspert 已提交
1637
    @param location: the path of the location, e.g. I{/srv/ftp-master.debian.org/ftp/pool/}
1638 1639 1640 1641 1642

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

    @type archive: string
J
Joerg Jaspert 已提交
1643
    @param archive: the archive name (if None, no restriction applied)
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656

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

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

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

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

1657 1658 1659 1660
    try:
        return q.one()
    except NoResultFound:
        return None
1661 1662 1663

__all__.append('get_location')

M
Mark Hymers 已提交
1664 1665
################################################################################

1666
class Maintainer(ORMObject):
1667 1668
    def __init__(self, name = None):
        self.name = name
M
Mark Hymers 已提交
1669

1670 1671 1672 1673 1674
    def properties(self):
        return ['name', 'maintainer_id']

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

M
Mark Hymers 已提交
1676 1677 1678 1679 1680 1681
    def get_split_maintainer(self):
        if not hasattr(self, 'name') or self.name is None:
            return ('', '', '', '')

        return fix_maintainer(self.name.strip())

1682 1683
__all__.append('Maintainer')

1684
@session_wrapper
M
Mark Hymers 已提交
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
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
    """

1704
    q = session.query(Maintainer).filter_by(name=name)
1705 1706 1707
    try:
        ret = q.one()
    except NoResultFound:
1708 1709 1710
        maintainer = Maintainer()
        maintainer.name = name
        session.add(maintainer)
1711
        session.commit_or_flush()
1712
        ret = maintainer
M
Mark Hymers 已提交
1713

1714
    return ret
M
Mark Hymers 已提交
1715 1716 1717

__all__.append('get_or_set_maintainer')

1718
@session_wrapper
C
Chris Lamb 已提交
1719
def get_maintainer(maintainer_id, session=None):
C
Chris Lamb 已提交
1720
    """
1721 1722
    Return the name of the maintainer behind C{maintainer_id} or None if that
    maintainer_id is invalid.
C
Chris Lamb 已提交
1723 1724 1725 1726

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

1727 1728
    @rtype: Maintainer
    @return: the Maintainer with this C{maintainer_id}
C
Chris Lamb 已提交
1729 1730
    """

1731
    return session.query(Maintainer).get(maintainer_id)
C
Chris Lamb 已提交
1732 1733 1734

__all__.append('get_maintainer')

M
Mark Hymers 已提交
1735 1736
################################################################################

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

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

__all__.append('NewComment')

1746
@session_wrapper
M
Mark Hymers 已提交
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
def has_new_comment(package, version, session=None):
    """
    Returns true if the given combination of C{package}, C{version} has a comment.

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

    @type version: string
    @param version: package version

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

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

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

1769
    return bool(q.count() > 0)
M
Mark Hymers 已提交
1770 1771 1772

__all__.append('has_new_comment')

1773
@session_wrapper
M
Mark Hymers 已提交
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
def get_new_comments(package=None, version=None, comment_id=None, session=None):
    """
    Returns (possibly empty) list of NewComment objects for the given
    parameters

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

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

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

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

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

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

1801
    return q.all()
M
Mark Hymers 已提交
1802 1803 1804 1805 1806

__all__.append('get_new_comments')

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

M
Mark Hymers 已提交
1807
class Override(object):
M
Mark Hymers 已提交
1808 1809
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1810 1811 1812 1813

    def __repr__(self):
        return '<Override %s (%s)>' % (self.package, self.suite_id)

1814 1815
__all__.append('Override')

1816
@session_wrapper
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
def get_override(package, suite=None, component=None, overridetype=None, session=None):
    """
    Returns Override object for the given parameters

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

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

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

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

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

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

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

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

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

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

1859
    return q.all()
1860 1861 1862 1863

__all__.append('get_override')


M
Mark Hymers 已提交
1864 1865
################################################################################

M
Mark Hymers 已提交
1866
class OverrideType(object):
M
Mark Hymers 已提交
1867 1868
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1869 1870 1871 1872

    def __repr__(self):
        return '<OverrideType %s>' % self.overridetype

1873 1874
__all__.append('OverrideType')

1875
@session_wrapper
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
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
    """
1890

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

1893 1894 1895 1896
    try:
        return q.one()
    except NoResultFound:
        return None
1897

1898 1899
__all__.append('get_override_type')

M
Mark Hymers 已提交
1900 1901
################################################################################

M
Mike O'Connor 已提交
1902
class DebContents(object):
M
Mark Hymers 已提交
1903 1904
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1905 1906

    def __repr__(self):
M
Mike O'Connor 已提交
1907 1908 1909 1910 1911 1912 1913 1914
        return '<DebConetnts %s: %s>' % (self.package.package,self.file)

__all__.append('DebContents')


class UdebContents(object):
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1915

M
Mike O'Connor 已提交
1916 1917 1918 1919 1920 1921 1922 1923
    def __repr__(self):
        return '<UdebConetnts %s: %s>' % (self.package.package,self.file)

__all__.append('UdebContents')

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

M
Mike O'Connor 已提交
1925 1926 1927 1928 1929 1930 1931 1932 1933
    def __repr__(self):
        return '<PendingBinContents %s>' % self.contents_id

__all__.append('PendingBinContents')

def insert_pending_content_paths(package,
                                 is_udeb,
                                 fullpaths,
                                 session=None):
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
    """
    Make sure given paths are temporarily associated with given
    package

    @type package: dict
    @param package: the package to associate with should have been read in from the binary control file
    @type fullpaths: list
    @param fullpaths: the list of paths of the file being associated with the binary
    @type session: SQLAlchemy session
    @param session: Optional SQLAlchemy session.  If this is passed, the caller
    is responsible for ensuring a transaction has begun and committing the
    results or rolling back based on the result code.  If not passed, a commit
    will be performed at the end of the function

    @return: True upon success, False if there is a problem
    """

    privatetrans = False

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

    try:
        arch = get_architecture(package['Architecture'], session)
        arch_id = arch.arch_id

        # Remove any already existing recorded files for this package
M
Mike O'Connor 已提交
1962
        q = session.query(PendingBinContents)
1963 1964 1965 1966 1967 1968 1969
        q = q.filter_by(package=package['Package'])
        q = q.filter_by(version=package['Version'])
        q = q.filter_by(architecture=arch_id)
        q.delete()

        for fullpath in fullpaths:

M
Mike O'Connor 已提交
1970 1971
            if fullpath.startswith( "./" ):
                fullpath = fullpath[2:]
M
Mark Hymers 已提交
1972

M
Mike O'Connor 已提交
1973
            pca = PendingBinContents()
1974 1975
            pca.package = package['Package']
            pca.version = package['Version']
M
Mike O'Connor 已提交
1976
            pca.file = fullpath
1977
            pca.architecture = arch_id
M
Mike O'Connor 已提交
1978

1979
            if isudeb:
M
Mike O'Connor 已提交
1980 1981 1982
                pca.type = 8 # gross
            else:
                pca.type = 7 # also gross
1983 1984 1985 1986 1987
            session.add(pca)

        # Only commit if we set up the session ourself
        if privatetrans:
            session.commit()
1988
            session.close()
M
Mark Hymers 已提交
1989 1990
        else:
            session.flush()
1991 1992

        return True
1993
    except Exception, e:
1994 1995 1996 1997 1998
        traceback.print_exc()

        # Only rollback if we set up the session ourself
        if privatetrans:
            session.rollback()
1999
            session.close()
2000 2001 2002 2003 2004

        return False

__all__.append('insert_pending_content_paths')

M
Mark Hymers 已提交
2005 2006
################################################################################

2007 2008 2009 2010 2011 2012 2013 2014 2015
class PolicyQueue(object):
    def __init__(self, *args, **kwargs):
        pass

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

__all__.append('PolicyQueue')

2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
@session_wrapper
def get_policy_queue(queuename, session=None):
    """
    Returns PolicyQueue object for given C{queue name}

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

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

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

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

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

__all__.append('get_policy_queue')

M
Mark Hymers 已提交
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
@session_wrapper
def get_policy_queue_from_path(pathname, session=None):
    """
    Returns PolicyQueue object for given C{path name}

    @type queuename: string
    @param queuename: The path

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

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

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

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

__all__.append('get_policy_queue_from_path')

2066 2067
################################################################################

M
Mark Hymers 已提交
2068
class Priority(object):
M
Mark Hymers 已提交
2069 2070
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2071

2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.priority == val)
        # This signals to use the normal comparison operator
        return NotImplemented

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

M
Mark Hymers 已提交
2084 2085 2086
    def __repr__(self):
        return '<Priority %s (%s)>' % (self.priority, self.priority_id)

2087 2088
__all__.append('Priority')

2089
@session_wrapper
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
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
    """
2104

2105
    q = session.query(Priority).filter_by(priority=priority)
2106

2107 2108 2109 2110
    try:
        return q.one()
    except NoResultFound:
        return None
2111

2112 2113
__all__.append('get_priority')

2114
@session_wrapper
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
def get_priorities(session=None):
    """
    Returns dictionary of priority names -> id mappings

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

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

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

    return ret

__all__.append('get_priorities')

M
Mark Hymers 已提交
2136 2137
################################################################################

M
Mark Hymers 已提交
2138
class Section(object):
M
Mark Hymers 已提交
2139 2140
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2141

2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.section == val)
        # This signals to use the normal comparison operator
        return NotImplemented

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

M
Mark Hymers 已提交
2154 2155 2156
    def __repr__(self):
        return '<Section %s>' % self.section

2157 2158
__all__.append('Section')

2159
@session_wrapper
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
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
    """
2174

2175
    q = session.query(Section).filter_by(section=section)
2176

2177 2178 2179 2180
    try:
        return q.one()
    except NoResultFound:
        return None
2181

2182 2183
__all__.append('get_section')

2184
@session_wrapper
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
def get_sections(session=None):
    """
    Returns dictionary of section names -> id mappings

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

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

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

    return ret

__all__.append('get_sections')

M
Mark Hymers 已提交
2206 2207
################################################################################

2208
class DBSource(ORMObject):
T
Torsten Werner 已提交
2209 2210 2211 2212
    def __init__(self, source = None, version = None, maintainer = None, \
        changedby = None, poolfile = None, install_date = None):
        self.source = source
        self.version = version
2213 2214
        self.maintainer = maintainer
        self.changedby = changedby
T
Torsten Werner 已提交
2215 2216
        self.poolfile = poolfile
        self.install_date = install_date
M
Mark Hymers 已提交
2217

2218 2219 2220
    def properties(self):
        return ['source', 'source_id', 'maintainer', 'changedby', \
            'fingerprint', 'poolfile', 'version', 'suites_count', \
2221
            'install_date', 'binaries_count']
2222 2223

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

2227
__all__.append('DBSource')
2228

2229
@session_wrapper
2230 2231 2232 2233 2234 2235 2236
def source_exists(source, source_version, suites = ["any"], session=None):
    """
    Ensure that source exists somewhere in the archive for the binary
    upload being processed.
      1. exact match     => 1.0-3
      2. bin-only NMU    => 1.0-3+b1 , 1.0-3.1+b1

J
Joerg Jaspert 已提交
2237 2238
    @type source: string
    @param source: source name
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255

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

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

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

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

    """

    cnf = Config()
2256 2257 2258 2259
    ret = True

    from daklib.regexes import re_bin_only_nmu
    orig_source_version = re_bin_only_nmu.sub('', source_version)
2260 2261

    for suite in suites:
2262 2263
        q = session.query(DBSource).filter_by(source=source). \
            filter(DBSource.version.in_([source_version, orig_source_version]))
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
        if suite != "any":
            # source must exist in suite X, or in some other suite that's
            # mapped to X, recursively... silent-maps are counted too,
            # unreleased-maps aren't.
            maps = cnf.ValueList("SuiteMappings")[:]
            maps.reverse()
            maps = [ m.split() for m in maps ]
            maps = [ (x[1], x[2]) for x in maps
                            if x[0] == "map" or x[0] == "silent-map" ]
            s = [suite]
            for x in maps:
                if x[1] in s and x[0] not in s:
                    s.append(x[0])

2278
            q = q.filter(DBSource.suites.any(Suite.suite_name.in_(s)))
2279

2280
        if q.count() > 0:
2281 2282 2283
            continue

        # No source found so return not ok
2284
        ret = False
2285 2286

    return ret
2287 2288 2289

__all__.append('source_exists')

2290
@session_wrapper
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
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
    """

2302
    return session.query(Suite).filter(Suite.sources.any(source=source)).all()
2303 2304 2305

__all__.append('get_suites_source_in')

2306
@session_wrapper
2307
def get_sources_from_name(source, version=None, dm_upload_allowed=None, session=None):
M
Mark Hymers 已提交
2308
    """
2309
    Returns list of DBSource objects for given C{source} name and other parameters
M
Mark Hymers 已提交
2310 2311

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

J
Joerg Jaspert 已提交
2314 2315
    @type version: str or None
    @param version: DBSource version name to search for or None if not applicable
2316

2317 2318 2319 2320
    @type dm_upload_allowed: bool
    @param dm_upload_allowed: If None, no effect.  If True or False, only
    return packages with that dm_upload_allowed setting

M
Mark Hymers 已提交
2321 2322 2323 2324 2325
    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
2326
    @return: list of DBSource objects for the given name (may be empty)
M
Mark Hymers 已提交
2327
    """
2328 2329

    q = session.query(DBSource).filter_by(source=source)
2330 2331 2332 2333

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

2334 2335 2336
    if dm_upload_allowed is not None:
        q = q.filter_by(dm_upload_allowed=dm_upload_allowed)

2337
    return q.all()
M
Mark Hymers 已提交
2338

2339 2340
__all__.append('get_sources_from_name')

T
Torsten Werner 已提交
2341 2342
# FIXME: This function fails badly if it finds more than 1 source package and
# its implementation is trivial enough to be inlined.
2343
@session_wrapper
2344 2345
def get_source_in_suite(source, suite, session=None):
    """
2346
    Returns a DBSource object for a combination of C{source} and C{suite}.
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360

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

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

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

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

    """
2361

T
Torsten Werner 已提交
2362
    q = get_suite(suite, session).get_sources(source)
2363
    try:
2364
        return q.one()
2365 2366
    except NoResultFound:
        return None
2367

2368 2369
__all__.append('get_source_in_suite')

M
Mark Hymers 已提交
2370 2371
################################################################################

2372 2373 2374 2375
@session_wrapper
def add_dsc_to_db(u, filename, session=None):
    entry = u.pkg.files[filename]
    source = DBSource()
2376
    pfs = []
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393

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

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

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

    # Set up a new poolfile if necessary
    if not entry.has_key("files id") or not entry["files id"]:
        filename = entry["pool name"] + filename
        poolfile = add_poolfile(filename, entry, dsc_location_id, session)
F
Frank Lichtenheld 已提交
2394
        session.flush()
2395
        pfs.append(poolfile)
2396 2397 2398 2399 2400
        entry["files id"] = poolfile.file_id

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

T
Torsten Werner 已提交
2401 2402 2403
    suite_names = u.pkg.changes["distribution"].keys()
    source.suites = session.query(Suite). \
        filter(Suite.suite_name.in_(suite_names)).all()
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433

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

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

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

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

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

            (found, obj) = check_poolfile(filename, dentry["size"], dentry["md5sum"], dsc_location_id)
            # FIXME: needs to check for -1/-2 and or handle exception
            if found and obj is not None:
                files_id = obj.file_id
2434
                pfs.append(obj)
2435 2436 2437 2438 2439 2440 2441

            # If still not found, add it
            if files_id is None:
                # HACK: Force sha1sum etc into dentry
                dentry["sha1sum"] = dfentry["sha1sum"]
                dentry["sha256sum"] = dfentry["sha256sum"]
                poolfile = add_poolfile(filename, dentry, dsc_location_id, session)
2442
                pfs.append(poolfile)
2443
                files_id = poolfile.file_id
2444 2445 2446 2447 2448
        else:
            poolfile = get_poolfile_by_id(files_id, session)
            if poolfile is None:
                utils.fubar("INTERNAL ERROR. Found no poolfile with id %d" % files_id)
            pfs.append(poolfile)
2449 2450 2451 2452 2453 2454 2455

        df.poolfile_id = files_id
        session.add(df)

    # Add the src_uploaders to the DB
    uploader_ids = [source.maintainer_id]
    if u.pkg.dsc.has_key("uploaders"):
2456
        for up in u.pkg.dsc["uploaders"].replace(">, ", ">\t").split("\t"):
2457 2458 2459 2460
            up = up.strip()
            uploader_ids.append(get_or_set_maintainer(up, session).maintainer_id)

    added_ids = {}
T
Torsten Werner 已提交
2461 2462 2463 2464
    for up_id in uploader_ids:
        if added_ids.has_key(up_id):
            import utils
            utils.warn("Already saw uploader %s for source %s" % (up_id, source.source))
2465 2466
            continue

T
Torsten Werner 已提交
2467
        added_ids[up_id]=1
2468 2469

        su = SrcUploader()
T
Torsten Werner 已提交
2470
        su.maintainer_id = up_id
2471 2472 2473 2474 2475
        su.source_id = source.source_id
        session.add(su)

    session.flush()

M
Mark Hymers 已提交
2476
    return source, dsc_component, dsc_location_id, pfs
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501

__all__.append('add_dsc_to_db')

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

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

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

2504 2505 2506 2507
    if entry.get("files id", None):
        poolfile = get_poolfile_by_id(bin.poolfile_id)
        bin.poolfile_id = entry["files id"]
    else:
2508
        poolfile = add_poolfile(filename, entry, entry["location id"], session)
2509
        bin.poolfile_id = entry["files id"] = poolfile.file_id
2510 2511 2512 2513 2514

    # Find source id
    bin_sources = get_sources_from_name(entry["source package"], entry["source version"], session=session)
    if len(bin_sources) != 1:
        raise NoSourceFieldError, "Unable to find a unique source id for %s (%s), %s, file %s, type %s, signed by %s" % \
2515
                                  (bin.package, bin.version, entry["architecture"],
2516 2517 2518 2519 2520 2521 2522
                                   filename, bin.binarytype, u.pkg.changes["fingerprint"])

    bin.source_id = bin_sources[0].source_id

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

2523 2524 2525
    suite_names = u.pkg.changes["distribution"].keys()
    bin.suites = session.query(Suite). \
        filter(Suite.suite_name.in_(suite_names)).all()
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535

    session.flush()

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

2536 2537
    return poolfile

2538 2539 2540 2541
__all__.append('add_deb_to_db')

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

2542 2543 2544 2545
class SourceACL(object):
    def __init__(self, *args, **kwargs):
        pass

2546 2547 2548
    def __repr__(self):
        return '<SourceACL %s>' % self.source_acl_id

2549 2550 2551 2552
__all__.append('SourceACL')

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

2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
class SrcFormat(object):
    def __init__(self, *args, **kwargs):
        pass

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

__all__.append('SrcFormat')

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

M
Mark Hymers 已提交
2564
class SrcUploader(object):
M
Mark Hymers 已提交
2565 2566
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2567 2568 2569 2570

    def __repr__(self):
        return '<SrcUploader %s>' % self.uploader_id

2571 2572
__all__.append('SrcUploader')

M
Mark Hymers 已提交
2573 2574
################################################################################

M
Mark Hymers 已提交
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
SUITE_FIELDS = [ ('SuiteName', 'suite_name'),
                 ('SuiteID', 'suite_id'),
                 ('Version', 'version'),
                 ('Origin', 'origin'),
                 ('Label', 'label'),
                 ('Description', 'description'),
                 ('Untouchable', 'untouchable'),
                 ('Announce', 'announce'),
                 ('Codename', 'codename'),
                 ('OverrideCodename', 'overridecodename'),
                 ('ValidTime', 'validtime'),
                 ('Priority', 'priority'),
                 ('NotAutomatic', 'notautomatic'),
                 ('CopyChanges', 'copychanges'),
J
Joerg Jaspert 已提交
2589
                 ('OverrideSuite', 'overridesuite')]
M
Mark Hymers 已提交
2590

T
Torsten Werner 已提交
2591 2592
# Why the heck don't we have any UNIQUE constraints in table suite?
# TODO: Add UNIQUE constraints for appropriate columns.
2593
class Suite(ORMObject):
2594 2595 2596
    def __init__(self, suite_name = None, version = None):
        self.suite_name = suite_name
        self.version = version
M
Mark Hymers 已提交
2597

2598
    def properties(self):
2599
        return ['suite_name', 'version', 'sources_count', 'binaries_count']
2600 2601 2602

    def not_null_constraints(self):
        return ['suite_name', 'version']
M
Mark Hymers 已提交
2603

2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.suite_name == val)
        # This signals to use the normal comparison operator
        return NotImplemented

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

M
Mark Hymers 已提交
2616 2617 2618 2619 2620 2621 2622 2623 2624
    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)

2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
    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)
        """

2641
        q = object_session(self).query(Architecture).with_parent(self)
2642 2643 2644 2645 2646 2647
        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 已提交
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
    def get_sources(self, source):
        """
        Returns a query object representing DBSource that is part of C{suite}.

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

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

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

        """

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

2666 2667
__all__.append('Suite')

2668
@session_wrapper
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
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 已提交
2681
    @return: Suite object for the requested suite name (None if not present)
2682
    """
2683

2684
    q = session.query(Suite).filter_by(suite_name=suite)
2685

2686 2687 2688 2689
    try:
        return q.one()
    except NoResultFound:
        return None
2690

2691 2692
__all__.append('get_suite')

M
Mark Hymers 已提交
2693 2694
################################################################################

2695
# TODO: should be removed because the implementation is too trivial
2696
@session_wrapper
2697
def get_suite_architectures(suite, skipsrc=False, skipall=False, session=None):
M
Mark Hymers 已提交
2698 2699 2700
    """
    Returns list of Architecture objects for given C{suite} name

J
Joerg Jaspert 已提交
2701 2702
    @type suite: str
    @param suite: Suite name to search for
M
Mark Hymers 已提交
2703

2704 2705 2706 2707 2708 2709 2710 2711
    @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 已提交
2712 2713 2714 2715 2716 2717 2718 2719
    @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)
    """

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

2722
__all__.append('get_suite_architectures')
M
Mark Hymers 已提交
2723

M
Mark Hymers 已提交
2724 2725
################################################################################

2726 2727 2728 2729 2730 2731 2732 2733 2734
class SuiteSrcFormat(object):
    def __init__(self, *args, **kwargs):
        pass

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

__all__.append('SuiteSrcFormat')

2735
@session_wrapper
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
def get_suite_src_formats(suite, session=None):
    """
    Returns list of allowed SrcFormat for C{suite}.

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

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

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

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

2756
    return q.all()
2757 2758 2759 2760 2761

__all__.append('get_suite_src_formats')

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

2762
class Uid(ORMObject):
T
Torsten Werner 已提交
2763 2764 2765
    def __init__(self, uid = None, name = None):
        self.uid = uid
        self.name = name
M
Mark Hymers 已提交
2766

2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
    def __eq__(self, val):
        if isinstance(val, str):
            return (self.uid == val)
        # This signals to use the normal comparison operator
        return NotImplemented

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

2779 2780 2781 2782 2783
    def properties(self):
        return ['uid', 'name', 'fingerprint']

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

2785 2786
__all__.append('Uid')

2787
@session_wrapper
M
Mark Hymers 已提交
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
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
    """
2805 2806 2807

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

2808 2809 2810
    try:
        ret = q.one()
    except NoResultFound:
2811 2812 2813
        uid = Uid()
        uid.uid = uidname
        session.add(uid)
2814
        session.commit_or_flush()
2815
        ret = uid
M
Mark Hymers 已提交
2816

2817
    return ret
M
Mark Hymers 已提交
2818 2819 2820

__all__.append('get_or_set_uid')

2821
@session_wrapper
2822 2823 2824 2825
def get_uid_from_fingerprint(fpr, session=None):
    q = session.query(Uid)
    q = q.join(Fingerprint).filter_by(fingerprint=fpr)

2826 2827 2828 2829
    try:
        return q.one()
    except NoResultFound:
        return None
2830 2831 2832

__all__.append('get_uid_from_fingerprint')

M
Mark Hymers 已提交
2833 2834
################################################################################

2835 2836 2837 2838
class UploadBlock(object):
    def __init__(self, *args, **kwargs):
        pass

2839 2840 2841
    def __repr__(self):
        return '<UploadBlock %s (%s)>' % (self.source, self.upload_block_id)

2842 2843 2844 2845
__all__.append('UploadBlock')

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

2846
class DBConn(object):
M
Mark Hymers 已提交
2847
    """
2848
    database module init.
M
Mark Hymers 已提交
2849
    """
2850 2851
    __shared_state = {}

M
Mark Hymers 已提交
2852
    def __init__(self, *args, **kwargs):
2853
        self.__dict__ = self.__shared_state
M
Mark Hymers 已提交
2854

2855 2856 2857 2858
        if not getattr(self, 'initialised', False):
            self.initialised = True
            self.debug = kwargs.has_key('debug')
            self.__createconn()
M
Mark Hymers 已提交
2859

M
Mark Hymers 已提交
2860
    def __setuptables(self):
2861
        tables_with_primary = (
C
Chris Lamb 已提交
2862 2863 2864 2865 2866 2867 2868
            'architecture',
            'archive',
            'bin_associations',
            'binaries',
            'binary_acl',
            'binary_acl_map',
            'build_queue',
2869
            'changelogs_text',
C
Chris Lamb 已提交
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
            'component',
            'config',
            'changes_pending_binaries',
            'changes_pending_files',
            'changes_pending_source',
            'dsc_files',
            'files',
            'fingerprint',
            'keyrings',
            'keyring_acl_map',
            'location',
            'maintainer',
            'new_comments',
            'override_type',
M
Mike O'Connor 已提交
2884
            'pending_bin_contents',
C
Chris Lamb 已提交
2885 2886 2887 2888 2889 2890 2891 2892 2893
            'policy_queue',
            'priority',
            'section',
            'source',
            'source_acl',
            'src_associations',
            'src_format',
            'src_uploaders',
            'suite',
2894 2895
            'uid',
            'upload_blocks',
2896 2897 2898 2899 2900
            # The following tables have primary keys but sqlalchemy
            # version 0.5 fails to reflect them correctly with database
            # versions before upgrade #41.
            #'changes',
            #'build_queue_files',
2901 2902 2903 2904 2905 2906 2907 2908 2909
        )

        tables_no_primary = (
            'bin_contents',
            'changes_pending_files_map',
            'changes_pending_source_files',
            'changes_pool_files',
            'deb_contents',
            'override',
C
Chris Lamb 已提交
2910 2911 2912
            'suite_architectures',
            'suite_src_formats',
            'suite_build_queue_copy',
M
Mike O'Connor 已提交
2913
            'udeb_contents',
2914 2915 2916
            # see the comment above
            'changes',
            'build_queue_files',
C
Chris Lamb 已提交
2917 2918
        )

2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
        views = (
            'almost_obsolete_all_associations',
            'almost_obsolete_src_associations',
            'any_associations_source',
            'bin_assoc_by_arch',
            'bin_associations_binaries',
            'binaries_suite_arch',
            'binfiles_suite_component_arch',
            'changelogs',
            'file_arch_suite',
            'newest_all_associations',
            'newest_any_associations',
            'newest_source',
            'newest_src_association',
            'obsolete_all_associations',
            'obsolete_any_associations',
            'obsolete_any_by_all_associations',
            'obsolete_src_associations',
            'source_suite',
            'src_associations_bin',
            'src_associations_src',
            'suite_arch_by_name',
        )

2943 2944 2945
        # Sqlalchemy version 0.5 fails to reflect the SERIAL type
        # correctly and that is why we have to use a workaround. It can
        # be removed as soon as we switch to version 0.6.
2946 2947 2948 2949 2950 2951 2952
        for table_name in tables_with_primary:
            table = Table(table_name, self.db_meta, \
                Column('id', Integer, primary_key = True), \
                autoload=True, useexisting=True)
            setattr(self, 'tbl_%s' % table_name, table)

        for table_name in tables_no_primary:
M
Mark Hymers 已提交
2953 2954
            table = Table(table_name, self.db_meta, autoload=True)
            setattr(self, 'tbl_%s' % table_name, table)
M
Mark Hymers 已提交
2955

2956 2957 2958 2959
        for view_name in views:
            view = Table(view_name, self.db_meta, autoload=True)
            setattr(self, 'view_%s' % view_name, view)

M
Mark Hymers 已提交
2960
    def __setupmappers(self):
M
Mark Hymers 已提交
2961
        mapper(Architecture, self.tbl_architecture,
2962
            properties = dict(arch_id = self.tbl_architecture.c.id,
2963 2964
               suites = relation(Suite, secondary=self.tbl_suite_architectures,
                   order_by='suite_name',
2965 2966
                   backref=backref('architectures', order_by='arch_string'))),
            extension = validator)
M
Mark Hymers 已提交
2967 2968 2969 2970 2971

        mapper(Archive, self.tbl_archive,
               properties = dict(archive_id = self.tbl_archive.c.id,
                                 archive_name = self.tbl_archive.c.name))

M
Mike O'Connor 已提交
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
        mapper(PendingBinContents, self.tbl_pending_bin_contents,
               properties = dict(contents_id =self.tbl_pending_bin_contents.c.id,
                                 filename = self.tbl_pending_bin_contents.c.filename,
                                 package = self.tbl_pending_bin_contents.c.package,
                                 version = self.tbl_pending_bin_contents.c.version,
                                 arch = self.tbl_pending_bin_contents.c.arch,
                                 otype = self.tbl_pending_bin_contents.c.type))

        mapper(DebContents, self.tbl_deb_contents,
               properties = dict(binary_id=self.tbl_deb_contents.c.binary_id,
                                 package=self.tbl_deb_contents.c.package,
2983
                                 suite=self.tbl_deb_contents.c.suite,
M
Mike O'Connor 已提交
2984 2985 2986 2987 2988 2989 2990
                                 arch=self.tbl_deb_contents.c.arch,
                                 section=self.tbl_deb_contents.c.section,
                                 filename=self.tbl_deb_contents.c.filename))

        mapper(UdebContents, self.tbl_udeb_contents,
               properties = dict(binary_id=self.tbl_udeb_contents.c.binary_id,
                                 package=self.tbl_udeb_contents.c.package,
2991
                                 suite=self.tbl_udeb_contents.c.suite,
M
Mike O'Connor 已提交
2992 2993 2994
                                 arch=self.tbl_udeb_contents.c.arch,
                                 section=self.tbl_udeb_contents.c.section,
                                 filename=self.tbl_udeb_contents.c.filename))
M
Mike O'Connor 已提交
2995

2996 2997 2998 2999 3000 3001 3002
        mapper(BuildQueue, self.tbl_build_queue,
               properties = dict(queue_id = self.tbl_build_queue.c.id))

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

3003
        mapper(DBBinary, self.tbl_binaries,
M
Mark Hymers 已提交
3004
               properties = dict(binary_id = self.tbl_binaries.c.id,
M
Mark Hymers 已提交
3005 3006
                                 package = self.tbl_binaries.c.package,
                                 version = self.tbl_binaries.c.version,
M
Mark Hymers 已提交
3007
                                 maintainer_id = self.tbl_binaries.c.maintainer,
M
Mark Hymers 已提交
3008
                                 maintainer = relation(Maintainer),
M
Mark Hymers 已提交
3009
                                 source_id = self.tbl_binaries.c.source,
3010
                                 source = relation(DBSource, backref='binaries'),
M
Mark Hymers 已提交
3011
                                 arch_id = self.tbl_binaries.c.architecture,
M
Mark Hymers 已提交
3012 3013
                                 architecture = relation(Architecture),
                                 poolfile_id = self.tbl_binaries.c.file,
3014
                                 poolfile = relation(PoolFile, backref=backref('binary', uselist = False)),
M
Mark Hymers 已提交
3015 3016 3017 3018
                                 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,
3019
                                 suites = relation(Suite, secondary=self.tbl_bin_associations,
T
Torsten Werner 已提交
3020
                                     backref=backref('binaries', lazy='dynamic'))),
3021
                extension = validator)
M
Mark Hymers 已提交
3022

3023 3024 3025 3026
        mapper(BinaryACL, self.tbl_binary_acl,
               properties = dict(binary_acl_id = self.tbl_binary_acl.c.id))

        mapper(BinaryACLMap, self.tbl_binary_acl_map,
3027 3028 3029
               properties = dict(binary_acl_map_id = self.tbl_binary_acl_map.c.id,
                                 fingerprint = relation(Fingerprint, backref="binary_acl_map"),
                                 architecture = relation(Architecture)))
3030

M
Mark Hymers 已提交
3031 3032
        mapper(Component, self.tbl_component,
               properties = dict(component_id = self.tbl_component.c.id,
3033 3034
                                 component_name = self.tbl_component.c.name),
               extension = validator)
M
Mark Hymers 已提交
3035 3036 3037 3038 3039 3040 3041

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

        mapper(DSCFile, self.tbl_dsc_files,
               properties = dict(dscfile_id = self.tbl_dsc_files.c.id,
                                 source_id = self.tbl_dsc_files.c.source,
3042
                                 source = relation(DBSource),
M
Mark Hymers 已提交
3043 3044
                                 poolfile_id = self.tbl_dsc_files.c.file,
                                 poolfile = relation(PoolFile)))
M
Mark Hymers 已提交
3045 3046 3047 3048

        mapper(PoolFile, self.tbl_files,
               properties = dict(file_id = self.tbl_files.c.id,
                                 filesize = self.tbl_files.c.size,
M
Mark Hymers 已提交
3049
                                 location_id = self.tbl_files.c.location,
3050 3051 3052 3053
                                 location = relation(Location,
                                     # using lazy='dynamic' in the back
                                     # reference because we have A LOT of
                                     # files in one location
3054 3055
                                     backref=backref('files', lazy='dynamic'))),
                extension = validator)
M
Mark Hymers 已提交
3056 3057 3058 3059

        mapper(Fingerprint, self.tbl_fingerprint,
               properties = dict(fingerprint_id = self.tbl_fingerprint.c.id,
                                 uid_id = self.tbl_fingerprint.c.uid,
M
Mark Hymers 已提交
3060 3061
                                 uid = relation(Uid),
                                 keyring_id = self.tbl_fingerprint.c.keyring,
3062 3063
                                 keyring = relation(Keyring),
                                 source_acl = relation(SourceACL),
3064 3065
                                 binary_acl = relation(BinaryACL)),
               extension = validator)
M
Mark Hymers 已提交
3066 3067 3068 3069 3070

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

M
Mark Hymers 已提交
3071 3072
        mapper(DBChange, self.tbl_changes,
               properties = dict(change_id = self.tbl_changes.c.id,
M
Mark Hymers 已提交
3073 3074 3075
                                 poolfiles = relation(PoolFile,
                                                      secondary=self.tbl_changes_pool_files,
                                                      backref="changeslinks"),
3076
                                 seen = self.tbl_changes.c.seen,
3077 3078 3079 3080 3081 3082 3083 3084
                                 source = self.tbl_changes.c.source,
                                 binaries = self.tbl_changes.c.binaries,
                                 architecture = self.tbl_changes.c.architecture,
                                 distribution = self.tbl_changes.c.distribution,
                                 urgency = self.tbl_changes.c.urgency,
                                 maintainer = self.tbl_changes.c.maintainer,
                                 changedby = self.tbl_changes.c.changedby,
                                 date = self.tbl_changes.c.date,
M
Mike O'Connor 已提交
3085
                                 version = self.tbl_changes.c.version,
3086 3087 3088 3089 3090 3091 3092
                                 files = relation(ChangePendingFile,
                                                  secondary=self.tbl_changes_pending_files_map,
                                                  backref="changesfile"),
                                 in_queue_id = self.tbl_changes.c.in_queue,
                                 in_queue = relation(PolicyQueue,
                                                     primaryjoin=(self.tbl_changes.c.in_queue==self.tbl_policy_queue.c.id)),
                                 approved_for_id = self.tbl_changes.c.approved_for))
3093

M
Mark Hymers 已提交
3094 3095
        mapper(ChangePendingBinary, self.tbl_changes_pending_binaries,
               properties = dict(change_pending_binary_id = self.tbl_changes_pending_binaries.c.id))
M
Mark Hymers 已提交
3096

3097
        mapper(ChangePendingFile, self.tbl_changes_pending_files,
3098 3099 3100 3101 3102 3103
               properties = dict(change_pending_file_id = self.tbl_changes_pending_files.c.id,
                                 filename = self.tbl_changes_pending_files.c.filename,
                                 size = self.tbl_changes_pending_files.c.size,
                                 md5sum = self.tbl_changes_pending_files.c.md5sum,
                                 sha1sum = self.tbl_changes_pending_files.c.sha1sum,
                                 sha256sum = self.tbl_changes_pending_files.c.sha256sum))
3104 3105 3106

        mapper(ChangePendingSource, self.tbl_changes_pending_source,
               properties = dict(change_pending_source_id = self.tbl_changes_pending_source.c.id,
M
Mark Hymers 已提交
3107
                                 change = relation(DBChange),
3108 3109 3110 3111 3112 3113 3114
                                 maintainer = relation(Maintainer,
                                                       primaryjoin=(self.tbl_changes_pending_source.c.maintainer_id==self.tbl_maintainer.c.id)),
                                 changedby = relation(Maintainer,
                                                      primaryjoin=(self.tbl_changes_pending_source.c.changedby_id==self.tbl_maintainer.c.id)),
                                 fingerprint = relation(Fingerprint),
                                 source_files = relation(ChangePendingFile,
                                                         secondary=self.tbl_changes_pending_source_files,
3115
                                                         backref="pending_sources")))
M
Mark Hymers 已提交
3116

J
Joerg Jaspert 已提交
3117

M
Mark Hymers 已提交
3118 3119 3120 3121 3122
        mapper(KeyringACLMap, self.tbl_keyring_acl_map,
               properties = dict(keyring_acl_map_id = self.tbl_keyring_acl_map.c.id,
                                 keyring = relation(Keyring, backref="keyring_acl_map"),
                                 architecture = relation(Architecture)))

M
Mark Hymers 已提交
3123 3124 3125
        mapper(Location, self.tbl_location,
               properties = dict(location_id = self.tbl_location.c.id,
                                 component_id = self.tbl_location.c.component,
3126 3127
                                 component = relation(Component, \
                                     backref=backref('location', uselist = False)),
M
Mark Hymers 已提交
3128
                                 archive_id = self.tbl_location.c.archive,
M
Mark Hymers 已提交
3129
                                 archive = relation(Archive),
3130 3131
                                 # FIXME: the 'type' column is old cruft and
                                 # should be removed in the future.
3132 3133
                                 archive_type = self.tbl_location.c.type),
               extension = validator)
M
Mark Hymers 已提交
3134 3135

        mapper(Maintainer, self.tbl_maintainer,
3136 3137 3138 3139
               properties = dict(maintainer_id = self.tbl_maintainer.c.id,
                   maintains_sources = relation(DBSource, backref='maintainer',
                       primaryjoin=(self.tbl_maintainer.c.id==self.tbl_source.c.maintainer)),
                   changed_sources = relation(DBSource, backref='changedby',
3140 3141
                       primaryjoin=(self.tbl_maintainer.c.id==self.tbl_source.c.changedby))),
                extension = validator)
M
Mark Hymers 已提交
3142

M
Mark Hymers 已提交
3143 3144 3145
        mapper(NewComment, self.tbl_new_comments,
               properties = dict(comment_id = self.tbl_new_comments.c.id))

M
Mark Hymers 已提交
3146 3147
        mapper(Override, self.tbl_override,
               properties = dict(suite_id = self.tbl_override.c.suite,
M
Mark Hymers 已提交
3148
                                 suite = relation(Suite),
3149
                                 package = self.tbl_override.c.package,
M
Mark Hymers 已提交
3150
                                 component_id = self.tbl_override.c.component,
M
Mark Hymers 已提交
3151
                                 component = relation(Component),
M
Mark Hymers 已提交
3152
                                 priority_id = self.tbl_override.c.priority,
M
Mark Hymers 已提交
3153
                                 priority = relation(Priority),
M
Mark Hymers 已提交
3154
                                 section_id = self.tbl_override.c.section,
M
Mark Hymers 已提交
3155 3156 3157
                                 section = relation(Section),
                                 overridetype_id = self.tbl_override.c.type,
                                 overridetype = relation(OverrideType)))
M
Mark Hymers 已提交
3158 3159 3160 3161 3162

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

3163 3164 3165
        mapper(PolicyQueue, self.tbl_policy_queue,
               properties = dict(policy_queue_id = self.tbl_policy_queue.c.id))

M
Mark Hymers 已提交
3166 3167 3168 3169
        mapper(Priority, self.tbl_priority,
               properties = dict(priority_id = self.tbl_priority.c.id))

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

3173
        mapper(DBSource, self.tbl_source,
M
Mark Hymers 已提交
3174
               properties = dict(source_id = self.tbl_source.c.id,
M
Mark Hymers 已提交
3175
                                 version = self.tbl_source.c.version,
M
Mark Hymers 已提交
3176
                                 maintainer_id = self.tbl_source.c.maintainer,
M
Mark Hymers 已提交
3177
                                 poolfile_id = self.tbl_source.c.file,
3178
                                 poolfile = relation(PoolFile, backref=backref('source', uselist = False)),
M
Mark Hymers 已提交
3179
                                 fingerprint_id = self.tbl_source.c.sig_fpr,
M
Mark Hymers 已提交
3180 3181 3182 3183
                                 fingerprint = relation(Fingerprint),
                                 changedby_id = self.tbl_source.c.changedby,
                                 srcfiles = relation(DSCFile,
                                                     primaryjoin=(self.tbl_source.c.id==self.tbl_dsc_files.c.source)),
3184
                                 suites = relation(Suite, secondary=self.tbl_src_associations,
3185
                                     backref=backref('sources', lazy='dynamic')),
3186 3187
                                 srcuploaders = relation(SrcUploader)),
               extension = validator)
M
Mark Hymers 已提交
3188

3189 3190
        mapper(SourceACL, self.tbl_source_acl,
               properties = dict(source_acl_id = self.tbl_source_acl.c.id))
M
Mark Hymers 已提交
3191

3192 3193 3194 3195
        mapper(SrcFormat, self.tbl_src_format,
               properties = dict(src_format_id = self.tbl_src_format.c.id,
                                 format_name = self.tbl_src_format.c.format_name))

M
Mark Hymers 已提交
3196 3197 3198
        mapper(SrcUploader, self.tbl_src_uploaders,
               properties = dict(uploader_id = self.tbl_src_uploaders.c.id,
                                 source_id = self.tbl_src_uploaders.c.source,
3199
                                 source = relation(DBSource,
M
Mark Hymers 已提交
3200 3201 3202 3203
                                                   primaryjoin=(self.tbl_src_uploaders.c.source==self.tbl_source.c.id)),
                                 maintainer_id = self.tbl_src_uploaders.c.maintainer,
                                 maintainer = relation(Maintainer,
                                                       primaryjoin=(self.tbl_src_uploaders.c.maintainer==self.tbl_maintainer.c.id))))
M
Mark Hymers 已提交
3204 3205

        mapper(Suite, self.tbl_suite,
3206
               properties = dict(suite_id = self.tbl_suite.c.id,
3207
                                 policy_queue = relation(PolicyQueue),
3208 3209 3210
                                 copy_queues = relation(BuildQueue,
                                     secondary=self.tbl_suite_build_queue_copy)),
                extension = validator)
M
Mark Hymers 已提交
3211

3212 3213 3214 3215 3216 3217
        mapper(SuiteSrcFormat, self.tbl_suite_src_formats,
               properties = dict(suite_id = self.tbl_suite_src_formats.c.suite,
                                 suite = relation(Suite, backref='suitesrcformats'),
                                 src_format_id = self.tbl_suite_src_formats.c.src_format,
                                 src_format = relation(SrcFormat)))

M
Mark Hymers 已提交
3218
        mapper(Uid, self.tbl_uid,
3219
               properties = dict(uid_id = self.tbl_uid.c.id,
3220 3221
                                 fingerprint = relation(Fingerprint)),
               extension = validator)
M
Mark Hymers 已提交
3222

3223
        mapper(UploadBlock, self.tbl_upload_blocks,
3224 3225 3226
               properties = dict(upload_block_id = self.tbl_upload_blocks.c.id,
                                 fingerprint = relation(Fingerprint, backref="uploadblocks"),
                                 uid = relation(Uid, backref="uploadblocks")))
3227

M
Mark Hymers 已提交
3228 3229
    ## Connection functions
    def __createconn(self):
M
Mark Hymers 已提交
3230
        from config import Config
3231 3232
        cnf = Config()
        if cnf["DB::Host"]:
M
Mark Hymers 已提交
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
            # TCP/IP
            connstr = "postgres://%s" % cnf["DB::Host"]
            if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
                connstr += ":%s" % cnf["DB::Port"]
            connstr += "/%s" % cnf["DB::Name"]
        else:
            # Unix Socket
            connstr = "postgres:///%s" % cnf["DB::Name"]
            if cnf["DB::Port"] and cnf["DB::Port"] != "-1":
                connstr += "?port=%s" % cnf["DB::Port"]
3243

M
updates  
Mark Hymers 已提交
3244
        self.db_pg   = create_engine(connstr, echo=self.debug)
M
Mark Hymers 已提交
3245 3246 3247 3248
        self.db_meta = MetaData()
        self.db_meta.bind = self.db_pg
        self.db_smaker = sessionmaker(bind=self.db_pg,
                                      autoflush=True,
3249
                                      autocommit=False)
M
Mark Hymers 已提交
3250

M
Mark Hymers 已提交
3251
        self.__setuptables()
M
Mark Hymers 已提交
3252
        self.__setupmappers()
M
Mark Hymers 已提交
3253

M
Mark Hymers 已提交
3254 3255
    def session(self):
        return self.db_smaker()
M
Mark Hymers 已提交
3256

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

3259