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

3 4 5 6 7 8
""" 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>
@copyright: 2009  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
M
Mark Hymers 已提交
40

41 42
from inspect import getargspec

43
import sqlalchemy
C
Chris Lamb 已提交
44
from sqlalchemy import create_engine, Table, MetaData
M
Mark Hymers 已提交
45
from sqlalchemy.orm import sessionmaker, mapper, relation
46
from sqlalchemy import types as sqltypes
M
Mark Hymers 已提交
47

M
Mark Hymers 已提交
48 49
# Don't remove this, we re-export the exceptions to scripts which import us
from sqlalchemy.exc import *
50
from sqlalchemy.orm.exc import NoResultFound
M
Mark Hymers 已提交
51

52 53 54
# Only import Config until Queue stuff is changed to store its config
# in the database
from config import Config
55
from singleton import Singleton
M
Mark Hymers 已提交
56
from textutils import fix_maintainer
M
Mark Hymers 已提交
57 58 59

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

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
# Patch in support for the debversion field type so that it works during
# reflection

class DebVersion(sqltypes.Text):
    def get_col_spec(self):
        return "DEBVERSION"

sa_major_version = sqlalchemy.__version__[0:3]
if sa_major_version == "0.5":
        from sqlalchemy.databases import postgres
        postgres.ischema_names['debversion'] = DebVersion
else:
        raise Exception("dak isn't ported to SQLA versions != 0.5 yet.  See daklib/dbconn.py")

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

M
Mark Hymers 已提交
76
__all__ = ['IntegrityError', 'SQLAlchemyError']
77 78 79

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

80
def session_wrapper(fn):
C
Chris Lamb 已提交
81 82 83 84
    """
    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.
85 86 87 88

    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 已提交
89 90
    """

91 92 93
    def wrapped(*args, **kwargs):
        private_transaction = False

94
        # Find the session object
C
Chris Lamb 已提交
95 96 97
        session = kwargs.get('session')

        if session is None:
98 99 100 101 102 103 104
            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]
105
                if session is None:
M
fixup  
Mark Hymers 已提交
106
                    args = list(args)
107 108
                    session = args[-1] = DBConn().session()
                    private_transaction = True
109 110 111 112 113

        if private_transaction:
            session.commit_or_flush = session.commit
        else:
            session.commit_or_flush = session.flush
114 115 116 117 118 119

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

122 123 124
    wrapped.__doc__ = fn.__doc__
    wrapped.func_name = fn.func_name

125 126 127 128
    return wrapped

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

M
Mark Hymers 已提交
129
class Architecture(object):
M
Mark Hymers 已提交
130 131
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
132

133 134 135 136 137 138 139 140 141 142 143 144
    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

M
Mark Hymers 已提交
145 146 147
    def __repr__(self):
        return '<Architecture %s>' % self.arch_string

148 149
__all__.append('Architecture')

150
@session_wrapper
151 152 153 154 155 156 157 158 159 160 161 162 163 164
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)
    """
165

166
    q = session.query(Architecture).filter_by(arch_string=architecture)
167

168 169 170 171
    try:
        return q.one()
    except NoResultFound:
        return None
172

173 174
__all__.append('get_architecture')

175
@session_wrapper
M
Mark Hymers 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
def get_architecture_suites(architecture, session=None):
    """
    Returns list of Suite objects for given C{architecture} name

    @type source: str
    @param source: Architecture 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: list of Suite objects for the given name (may be empty)
    """

    q = session.query(Suite)
    q = q.join(SuiteArchitecture)
    q = q.join(Architecture).filter_by(arch_string=architecture).order_by('suite_name')
194 195 196 197

    ret = q.all()

    return ret
M
Mark Hymers 已提交
198

199 200
__all__.append('get_architecture_suites')

M
Mark Hymers 已提交
201 202
################################################################################

M
Mark Hymers 已提交
203
class Archive(object):
M
Mark Hymers 已提交
204 205
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
206 207

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

210 211
__all__.append('Archive')

212
@session_wrapper
213 214
def get_archive(archive, session=None):
    """
F
Frank Lichtenheld 已提交
215
    returns database id for given C{archive}.
216 217 218 219 220 221 222 223 224 225 226 227 228

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

230
    q = session.query(Archive).filter_by(archive_name=archive)
231

232 233 234 235
    try:
        return q.one()
    except NoResultFound:
        return None
236

237
__all__.append('get_archive')
238

M
Mark Hymers 已提交
239 240
################################################################################

M
Mark Hymers 已提交
241
class BinAssociation(object):
M
Mark Hymers 已提交
242 243
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
244 245

    def __repr__(self):
M
Mark Hymers 已提交
246
        return '<BinAssociation %s (%s, %s)>' % (self.ba_id, self.binary, self.suite)
M
Mark Hymers 已提交
247

248 249
__all__.append('BinAssociation')

M
Mark Hymers 已提交
250 251
################################################################################

M
Mike O'Connor 已提交
252 253 254 255 256 257 258 259 260 261 262
class BinContents(object):
    def __init__(self, *args, **kwargs):
        pass

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

__all__.append('BinContents')

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

263
class DBBinary(object):
M
Mark Hymers 已提交
264 265
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
266 267

    def __repr__(self):
268
        return '<DBBinary %s (%s, %s)>' % (self.package, self.version, self.architecture)
M
Mark Hymers 已提交
269

270
__all__.append('DBBinary')
271

272
@session_wrapper
273 274 275 276 277 278 279 280 281 282 283
def get_suites_binary_in(package, session=None):
    """
    Returns list of Suite objects which given C{package} name is in

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

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

284
    return session.query(Suite).join(BinAssociation).join(DBBinary).filter_by(package=package).all()
285 286 287

__all__.append('get_suites_binary_in')

288
@session_wrapper
289 290
def get_binary_from_id(id, session=None):
    """
291
    Returns DBBinary object for given C{id}
292 293 294 295 296 297 298 299

    @type id: int
    @param id: Id of the required binary

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

300 301
    @rtype: DBBinary
    @return: DBBinary object for the given binary (None if not present)
302
    """
303

304
    q = session.query(DBBinary).filter_by(binary_id=id)
305

306 307 308 309
    try:
        return q.one()
    except NoResultFound:
        return None
M
Mark Hymers 已提交
310

311 312
__all__.append('get_binary_from_id')

313
@session_wrapper
314
def get_binaries_from_name(package, version=None, architecture=None, session=None):
M
Mark Hymers 已提交
315
    """
316
    Returns list of DBBinary objects for given C{package} name
M
Mark Hymers 已提交
317 318

    @type package: str
319
    @param package: DBBinary package name to search for
M
Mark Hymers 已提交
320

321 322 323 324 325 326
    @type version: str or None
    @param version: Version to search for (or None)

    @type package: str, list or None
    @param package: Architectures to limit to (or None if no limit)

M
Mark Hymers 已提交
327 328 329 330 331
    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
332
    @return: list of DBBinary objects for the given name (may be empty)
M
Mark Hymers 已提交
333
    """
334 335 336 337 338 339 340 341 342 343 344

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

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

    if architecture is not None:
        if not isinstance(architecture, list):
            architecture = [architecture]
        q = q.join(Architecture).filter(Architecture.arch_string.in_(architecture))

345 346 347
    ret = q.all()

    return ret
M
Mark Hymers 已提交
348

349 350
__all__.append('get_binaries_from_name')

351
@session_wrapper
352 353 354 355 356 357 358 359 360 361 362 363 364 365
def get_binaries_from_source_id(source_id, session=None):
    """
    Returns list of DBBinary objects for given C{source_id}

    @type source_id: int
    @param source_id: source_id to search for

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

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

367
    return session.query(DBBinary).filter_by(source_id=source_id).all()
368 369 370

__all__.append('get_binaries_from_source_id')

371
@session_wrapper
M
Mark Hymers 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
def get_binary_from_name_suite(package, suitename, session=None):
    ### For dak examine-package
    ### XXX: Doesn't use object API yet

    sql = """SELECT DISTINCT(b.package), b.version, c.name, su.suite_name
             FROM binaries b, files fi, location l, component c, bin_associations ba, suite su
             WHERE b.package=:package
               AND b.file = fi.id
               AND fi.location = l.id
               AND l.component = c.id
               AND ba.bin=b.id
               AND ba.suite = su.id
               AND su.suite_name=:suitename
          ORDER BY b.version DESC"""

387
    return session.execute(sql, {'package': package, 'suitename': suitename})
M
Mark Hymers 已提交
388 389 390

__all__.append('get_binary_from_name_suite')

391
@session_wrapper
392
def get_binary_components(package, suitename, arch, session=None):
393
    # Check for packages that have moved from one component to another
394 395 396 397 398 399 400 401 402 403
    query = """SELECT c.name FROM binaries b, bin_associations ba, suite s, location l, component c, architecture a, files f
    WHERE b.package=:package AND s.suite_name=:suitename
      AND (a.arch_string = :arch OR a.arch_string = 'all')
      AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
      AND f.location = l.id
      AND l.component = c.id
      AND b.file = f.id"""

    vals = {'package': package, 'suitename': suitename, 'arch': arch}

404
    return session.execute(query, vals)
405 406

__all__.append('get_binary_components')
407

M
Mark Hymers 已提交
408 409
################################################################################

410 411 412 413
class BinaryACL(object):
    def __init__(self, *args, **kwargs):
        pass

414 415 416
    def __repr__(self):
        return '<BinaryACL %s>' % self.binary_acl_id

417 418 419 420 421 422 423 424
__all__.append('BinaryACL')

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

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

425 426 427
    def __repr__(self):
        return '<BinaryACLMap %s>' % self.binary_acl_map_id

428 429 430 431
__all__.append('BinaryACLMap')

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

M
Mark Hymers 已提交
432
class Component(object):
M
Mark Hymers 已提交
433 434
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
435

436 437 438 439 440 441 442 443 444 445 446 447
    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

M
Mark Hymers 已提交
448 449 450
    def __repr__(self):
        return '<Component %s>' % self.component_name

451 452 453

__all__.append('Component')

454
@session_wrapper
455 456 457 458 459 460 461 462 463 464 465 466
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()
467

468
    q = session.query(Component).filter_by(component_name=component)
469

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

475 476
__all__.append('get_component')

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

M
Mark Hymers 已提交
479
class DBConfig(object):
M
Mark Hymers 已提交
480 481
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
482 483 484 485

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

486 487
__all__.append('DBConfig')

M
Mark Hymers 已提交
488 489
################################################################################

490
@session_wrapper
491 492 493 494 495 496 497 498 499 500
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 已提交
501 502
    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.
503 504 505 506 507

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

508
    q = session.query(ContentFilename).filter_by(filename=filename)
509 510 511 512

    try:
        ret = q.one().cafilename_id
    except NoResultFound:
513 514 515
        cf = ContentFilename()
        cf.filename = filename
        session.add(cf)
516
        session.commit_or_flush()
517
        ret = cf.cafilename_id
518

519
    return ret
520 521 522

__all__.append('get_or_set_contents_file_id')

523
@session_wrapper
M
Mark Hymers 已提交
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
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"

570
    return session.execute(contents_q, vals)
M
Mark Hymers 已提交
571 572 573

__all__.append('get_contents')

M
Mark Hymers 已提交
574 575
################################################################################

M
Mark Hymers 已提交
576
class ContentFilepath(object):
M
Mark Hymers 已提交
577 578
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
579 580 581 582

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

583 584
__all__.append('ContentFilepath')

585
@session_wrapper
M
Mark Hymers 已提交
586
def get_or_set_contents_path_id(filepath, session=None):
587 588 589 590 591 592 593 594 595
    """
    Returns database id for given path.

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

    @type filename: string
    @param filename: The filepath
    @type session: SQLAlchemy
    @param session: Optional SQL session object (a temporary one will be
M
Mark Hymers 已提交
596 597
    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.
598 599 600 601 602

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

603
    q = session.query(ContentFilepath).filter_by(filepath=filepath)
604 605 606 607

    try:
        ret = q.one().cafilepath_id
    except NoResultFound:
608 609 610
        cf = ContentFilepath()
        cf.filepath = filepath
        session.add(cf)
611
        session.commit_or_flush()
612
        ret = cf.cafilepath_id
613

614
    return ret
615 616 617

__all__.append('get_or_set_contents_path_id')

M
Mark Hymers 已提交
618 619
################################################################################

620
class ContentAssociation(object):
M
Mark Hymers 已提交
621 622
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
623 624 625 626

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

627 628
__all__.append('ContentAssociation')

629 630 631 632 633 634 635 636 637 638 639 640
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 已提交
641 642
    will be performed at the end of the function, otherwise the caller is
    responsible for commiting.
643 644 645 646 647 648 649 650 651 652

    @return: True upon success
    """

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

    try:
M
Mark Hymers 已提交
653 654
        # Insert paths
        pathcache = {}
655
        for fullpath in fullpaths:
M
Mike O'Connor 已提交
656 657
            if fullpath.startswith( './' ):
                fullpath = fullpath[2:]
M
Mark Hymers 已提交
658

M
Mike O'Connor 已提交
659
            session.execute( "INSERT INTO bin_contents ( file, binary_id ) VALUES ( :filename, :id )", { 'filename': fullpath, 'id': binary_id}  )
660

M
Mike O'Connor 已提交
661
        session.commit()
662
        if privatetrans:
M
Mark Hymers 已提交
663
            session.close()
664
        return True
M
Mark Hymers 已提交
665

666 667 668 669 670 671
    except:
        traceback.print_exc()

        # Only rollback if we set up the session ourself
        if privatetrans:
            session.rollback()
M
Mark Hymers 已提交
672
            session.close()
673 674 675 676 677

        return False

__all__.append('insert_content_paths')

M
Mark Hymers 已提交
678 679
################################################################################

M
Mark Hymers 已提交
680
class DSCFile(object):
M
Mark Hymers 已提交
681 682
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
683 684 685 686

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

687 688
__all__.append('DSCFile')

689
@session_wrapper
M
Mark Hymers 已提交
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
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)

718
    return q.all()
M
Mark Hymers 已提交
719 720 721

__all__.append('get_dscfiles')

M
Mark Hymers 已提交
722 723
################################################################################

M
Mark Hymers 已提交
724
class PoolFile(object):
M
Mark Hymers 已提交
725 726
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
727 728 729 730

    def __repr__(self):
        return '<PoolFile %s>' % self.filename

731 732
__all__.append('PoolFile')

733
@session_wrapper
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
def check_poolfile(filename, filesize, md5sum, location_id, session=None):
    """
    Returns a tuple:
     (ValidFileFound [boolean or None], PoolFile object or None)

    @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.
             If more than one file found with that name:
                    (None,  None)
             If valid pool file found: (True, PoolFile object)
             If valid pool file not found:
                    (False, None) if no file found
                    (False, PoolFile object) if file found with size/md5sum mismatch
    """

    q = session.query(PoolFile).filter_by(filename=filename)
    q = q.join(Location).filter_by(location_id=location_id)

764 765
    ret = None

766
    if q.count() > 1:
767 768 769 770 771
        ret = (None, None)
    elif q.count() < 1:
        ret = (False, None)
    else:
        obj = q.one()
M
Mark Hymers 已提交
772
        if obj.md5sum != md5sum or obj.filesize != int(filesize):
773
            ret = (False, obj)
774

775 776
    if ret is None:
        ret = (True, obj)
777

778
    return ret
779 780 781

__all__.append('check_poolfile')

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

    q = session.query(PoolFile).filter_by(file_id=file_id)

796 797 798 799
    try:
        return q.one()
    except NoResultFound:
        return None
M
Mark Hymers 已提交
800 801 802

__all__.append('get_poolfile_by_id')

803

804
@session_wrapper
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
def get_poolfile_by_name(filename, location_id=None, session=None):
    """
    Returns an array of PoolFile objects for the given filename and
    (optionally) location_id

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

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

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

    q = session.query(PoolFile).filter_by(filename=filename)

    if location_id is not None:
        q = q.join(Location).filter_by(location_id=location_id)

825
    return q.all()
826 827 828

__all__.append('get_poolfile_by_name')

829
@session_wrapper
830 831 832 833 834 835 836 837 838 839 840 841 842 843
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%
    q = session.query(PoolFile).filter(PoolFile.filename.like('%%%s%%' % filename))

844
    return q.all()
845 846 847

__all__.append('get_poolfile_like_name')

M
Mark Hymers 已提交
848 849
################################################################################

M
Mark Hymers 已提交
850
class Fingerprint(object):
M
Mark Hymers 已提交
851 852
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
853 854 855 856

    def __repr__(self):
        return '<Fingerprint %s>' % self.fingerprint

857 858
__all__.append('Fingerprint')

M
Mark Hymers 已提交
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
@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')

886
@session_wrapper
M
Mark Hymers 已提交
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
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
    """

906
    q = session.query(Fingerprint).filter_by(fingerprint=fpr)
907 908 909 910

    try:
        ret = q.one()
    except NoResultFound:
911 912 913
        fingerprint = Fingerprint()
        fingerprint.fingerprint = fpr
        session.add(fingerprint)
914
        session.commit_or_flush()
915
        ret = fingerprint
M
Mark Hymers 已提交
916

917
    return ret
M
Mark Hymers 已提交
918 919 920

__all__.append('get_or_set_fingerprint')

M
Mark Hymers 已提交
921 922
################################################################################

M
Mark Hymers 已提交
923 924 925 926 927 928 929 930 931 932 933
# 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 已提交
934
class Keyring(object):
M
Mark Hymers 已提交
935 936 937 938 939 940
    gpg_invocation = "gpg --no-default-keyring --keyring %s" +\
                     " --with-colons --fingerprint --fingerprint"

    keys = {}
    fpr_lookup = {}

M
Mark Hymers 已提交
941 942
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
943 944 945 946

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

M
Mark Hymers 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 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 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    def de_escape_gpg_str(self, str):
        esclist = re.split(r'(\\x..)', str)
        for x in range(1,len(esclist),2):
            esclist[x] = "%c" % (int(esclist[x][2:],16))
        return "".join(esclist)

    def load_keys(self, keyring):
        import email.Utils

        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]
                (name, addr) = email.Utils.parseaddr(field[9])
                name = re.sub(r"\s*[(].*[)]", "", name)
                if name == "" or addr == "" or "@" not in addr:
                    name = field[9]
                    addr = "invalid-uid"
                name = self.de_escape_gpg_str(name)
                self.keys[key] = {"email": addr}
                if name != "":
                    self.keys[key]["name"] = name
                self.keys[key]["aliases"] = [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":
                (name, addr) = email.Utils.parseaddr(field[9])
                if name and name not in self.keys[key]["aliases"]:
                    self.keys[key]["aliases"].append(name)
            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():
            if self.keys[x]["email"] == "invalid-uid":
                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)

1050 1051
__all__.append('Keyring')

1052
@session_wrapper
M
Mark Hymers 已提交
1053
def get_keyring(keyring, session=None):
1054
    """
M
Mark Hymers 已提交
1055
    If C{keyring} does not have an entry in the C{keyrings} table yet, return None
1056 1057 1058 1059 1060 1061 1062 1063 1064
    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
    """

1065
    q = session.query(Keyring).filter_by(keyring_name=keyring)
1066

1067 1068 1069
    try:
        return q.one()
    except NoResultFound:
M
Mark Hymers 已提交
1070
        return None
1071

M
Mark Hymers 已提交
1072
__all__.append('get_keyring')
1073

M
Mark Hymers 已提交
1074
################################################################################
1075

M
Mark Hymers 已提交
1076 1077 1078 1079 1080 1081 1082 1083
class KeyringACLMap(object):
    def __init__(self, *args, **kwargs):
        pass

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

__all__.append('KeyringACLMap')
1084

M
Mark Hymers 已提交
1085 1086
################################################################################

J
Joerg Jaspert 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
class KnownChange(object):
    def __init__(self, *args, **kwargs):
        pass

    def __repr__(self):
        return '<KnownChange %s>' % self.changesname

__all__.append('KnownChange')

@session_wrapper
def get_knownchange(filename, session=None):
    """
    returns knownchange object for given C{filename}.

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

    """
    q = session.query(KnownChange).filter_by(changesname=filename)

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

__all__.append('get_knownchange')

################################################################################
M
Mark Hymers 已提交
1122
class Location(object):
M
Mark Hymers 已提交
1123 1124
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1125 1126 1127 1128

    def __repr__(self):
        return '<Location %s (%s)>' % (self.path, self.location_id)

1129 1130
__all__.append('Location')

1131
@session_wrapper
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
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
    @param location: the path of the location, e.g. I{/srv/ftp.debian.org/ftp/pool/}

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

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

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

1158 1159 1160 1161
    try:
        return q.one()
    except NoResultFound:
        return None
1162 1163 1164

__all__.append('get_location')

M
Mark Hymers 已提交
1165 1166
################################################################################

M
Mark Hymers 已提交
1167
class Maintainer(object):
M
Mark Hymers 已提交
1168 1169
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1170 1171 1172 1173

    def __repr__(self):
        return '''<Maintainer '%s' (%s)>''' % (self.name, self.maintainer_id)

M
Mark Hymers 已提交
1174 1175 1176 1177 1178 1179
    def get_split_maintainer(self):
        if not hasattr(self, 'name') or self.name is None:
            return ('', '', '', '')

        return fix_maintainer(self.name.strip())

1180 1181
__all__.append('Maintainer')

1182
@session_wrapper
M
Mark Hymers 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
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
    """

1202
    q = session.query(Maintainer).filter_by(name=name)
1203 1204 1205
    try:
        ret = q.one()
    except NoResultFound:
1206 1207 1208
        maintainer = Maintainer()
        maintainer.name = name
        session.add(maintainer)
1209
        session.commit_or_flush()
1210
        ret = maintainer
M
Mark Hymers 已提交
1211

1212
    return ret
M
Mark Hymers 已提交
1213 1214 1215

__all__.append('get_or_set_maintainer')

1216
@session_wrapper
C
Chris Lamb 已提交
1217
def get_maintainer(maintainer_id, session=None):
C
Chris Lamb 已提交
1218
    """
1219 1220
    Return the name of the maintainer behind C{maintainer_id} or None if that
    maintainer_id is invalid.
C
Chris Lamb 已提交
1221 1222 1223 1224

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

1225 1226
    @rtype: Maintainer
    @return: the Maintainer with this C{maintainer_id}
C
Chris Lamb 已提交
1227 1228
    """

1229
    return session.query(Maintainer).get(maintainer_id)
C
Chris Lamb 已提交
1230 1231 1232

__all__.append('get_maintainer')

M
Mark Hymers 已提交
1233 1234
################################################################################

M
Mark Hymers 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243
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')

1244
@session_wrapper
M
Mark Hymers 已提交
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
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)
1266

1267
    return bool(q.count() > 0)
M
Mark Hymers 已提交
1268 1269 1270

__all__.append('has_new_comment')

1271
@session_wrapper
M
Mark Hymers 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
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)

1299
    return q.all()
M
Mark Hymers 已提交
1300 1301 1302 1303 1304

__all__.append('get_new_comments')

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

M
Mark Hymers 已提交
1305
class Override(object):
M
Mark Hymers 已提交
1306 1307
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1308 1309 1310 1311

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

1312 1313
__all__.append('Override')

1314
@session_wrapper
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
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))

1357
    return q.all()
1358 1359 1360 1361

__all__.append('get_override')


M
Mark Hymers 已提交
1362 1363
################################################################################

M
Mark Hymers 已提交
1364
class OverrideType(object):
M
Mark Hymers 已提交
1365 1366
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1367 1368 1369 1370

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

1371 1372
__all__.append('OverrideType')

1373
@session_wrapper
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
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
    """
1388

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

1391 1392 1393 1394
    try:
        return q.one()
    except NoResultFound:
        return None
1395

1396 1397
__all__.append('get_override_type')

M
Mark Hymers 已提交
1398 1399
################################################################################

M
Mark Hymers 已提交
1400
class PendingContentAssociation(object):
M
Mark Hymers 已提交
1401 1402
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1403 1404 1405 1406

    def __repr__(self):
        return '<PendingContentAssociation %s>' % self.pca_id

1407 1408
__all__.append('PendingContentAssociation')

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
def insert_pending_content_paths(package, fullpaths, session=None):
    """
    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
        q = session.query(PendingContentAssociation)
        q = q.filter_by(package=package['Package'])
        q = q.filter_by(version=package['Version'])
        q = q.filter_by(architecture=arch_id)
        q.delete()

        # Insert paths
M
Mark Hymers 已提交
1445
        pathcache = {}
1446 1447 1448 1449 1450 1451
        for fullpath in fullpaths:
            (path, file) = os.path.split(fullpath)

            if path.startswith( "./" ):
                path = path[2:]

M
Mark Hymers 已提交
1452 1453 1454 1455 1456 1457
            filepath_id = get_or_set_contents_path_id(path, session)
            filename_id = get_or_set_contents_file_id(file, session)

            pathcache[fullpath] = (filepath_id, filename_id)

        for fullpath, dat in pathcache.items():
1458 1459 1460
            pca = PendingContentAssociation()
            pca.package = package['Package']
            pca.version = package['Version']
M
Mark Hymers 已提交
1461 1462
            pca.filepath_id = dat[0]
            pca.filename_id = dat[1]
1463 1464 1465 1466 1467 1468
            pca.architecture = arch_id
            session.add(pca)

        # Only commit if we set up the session ourself
        if privatetrans:
            session.commit()
1469
            session.close()
M
Mark Hymers 已提交
1470 1471
        else:
            session.flush()
1472 1473

        return True
1474
    except Exception, e:
1475 1476 1477 1478 1479
        traceback.print_exc()

        # Only rollback if we set up the session ourself
        if privatetrans:
            session.rollback()
1480
            session.close()
1481 1482 1483 1484 1485

        return False

__all__.append('insert_pending_content_paths')

M
Mark Hymers 已提交
1486 1487
################################################################################

M
Mark Hymers 已提交
1488
class Priority(object):
M
Mark Hymers 已提交
1489 1490
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1491

1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
    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 已提交
1504 1505 1506
    def __repr__(self):
        return '<Priority %s (%s)>' % (self.priority, self.priority_id)

1507 1508
__all__.append('Priority')

1509
@session_wrapper
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
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
    """
1524

1525
    q = session.query(Priority).filter_by(priority=priority)
1526

1527 1528 1529 1530
    try:
        return q.one()
    except NoResultFound:
        return None
1531

1532 1533
__all__.append('get_priority')

1534
@session_wrapper
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
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 已提交
1556 1557
################################################################################

M
Mark Hymers 已提交
1558
class Queue(object):
M
Mark Hymers 已提交
1559 1560
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1561 1562 1563 1564

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

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    def autobuild_upload(self, changes, srcpath, session=None):
        """
        Update queue_build database table used for incoming autobuild support.

        @type changes: Changes
        @param changes: changes object for the upload to process

        @type srcpath: string
        @param srcpath: path for the queue file entries/link destinations

        @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,
        otherwise the caller is responsible for commiting.

        @rtype: NoneType or string
        @return: None if the operation failed, a string describing the error if not
        """

1586
        privatetrans = False
1587 1588
        if session is None:
            session = DBConn().session()
1589
            privatetrans = True
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618

        # TODO: Remove by moving queue config into the database
        conf = Config()

        for suitename in changes.changes["distribution"].keys():
            # TODO: Move into database as:
            #       buildqueuedir TEXT DEFAULT NULL (i.e. NULL is no build)
            #       buildqueuecopy BOOLEAN NOT NULL DEFAULT FALSE (i.e. default is symlink)
            #       This also gets rid of the SecurityQueueBuild hack below
            if suitename not in conf.ValueList("Dinstall::QueueBuildSuites"):
                continue

            # Find suite object
            s = get_suite(suitename, session)
            if s is None:
                return "INTERNAL ERROR: Could not find suite %s" % suitename

            # TODO: Get from database as above
            dest_dir = conf["Dir::QueueBuild"]

            # TODO: Move into database as above
            if conf.FindB("Dinstall::SecurityQueueBuild"):
                dest_dir = os.path.join(dest_dir, suitename)

            for file_entry in changes.files.keys():
                src = os.path.join(srcpath, file_entry)
                dest = os.path.join(dest_dir, file_entry)

                # TODO: Move into database as above
M
Mark Hymers 已提交
1619
                if conf.FindB("Dinstall::SecurityQueueBuild"):
1620
                    # Copy it since the original won't be readable by www-data
1621
                    import utils
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
                    utils.copy(src, dest)
                else:
                    # Create a symlink to it
                    os.symlink(src, dest)

                qb = QueueBuild()
                qb.suite_id = s.suite_id
                qb.queue_id = self.queue_id
                qb.filename = dest
                qb.in_queue = True

                session.add(qb)

1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
            # If the .orig tarballs are in the pool, create a symlink to
            # them (if one doesn't already exist)
            for dsc_file in changes.dsc_files.keys():
                # Skip all files except orig tarballs
                from daklib.regexes import re_is_orig_source
                if not re_is_orig_source.match(dsc_file):
                    continue
                # Skip orig files not identified in the pool
                if not (changes.orig_files.has_key(dsc_file) and
                        changes.orig_files[dsc_file].has_key("id")):
                    continue
                orig_file_id = changes.orig_files[dsc_file]["id"]
                dest = os.path.join(dest_dir, dsc_file)

                # If it doesn't exist, create a symlink
                if not os.path.exists(dest):
                    q = session.execute("SELECT l.path, f.filename FROM location l, files f WHERE f.id = :id and f.location = l.id",
                                        {'id': orig_file_id})
                    res = q.fetchone()
                    if not res:
                        return "[INTERNAL ERROR] Couldn't find id %s in files table." % (orig_file_id)

                    src = os.path.join(res[0], res[1])
                    os.symlink(src, dest)
1659

1660 1661 1662 1663 1664
                    # Add it to the list of packages for later processing by apt-ftparchive
                    qb = QueueBuild()
                    qb.suite_id = s.suite_id
                    qb.queue_id = self.queue_id
                    qb.filename = dest
1665 1666 1667
                    qb.in_queue = True
                    session.add(qb)

1668 1669 1670 1671 1672 1673 1674 1675
                # If it does, update things to ensure it's not removed prematurely
                else:
                    qb = get_queue_build(dest, s.suite_id, session)
                    if qb is None:
                        qb.in_queue = True
                        qb.last_used = None
                        session.add(qb)

1676
        if privatetrans:
1677
            session.commit()
1678
            session.close()
1679 1680 1681

        return None

1682 1683
__all__.append('Queue')

1684
@session_wrapper
C
Chris Lamb 已提交
1685
def get_or_set_queue(queuename, session=None):
1686
    """
C
Chris Lamb 已提交
1687 1688
    Returns Queue object for given C{queue name}, creating it if it does not
    exist.
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

    @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: Queue
    @return: Queue object for the given queue
    """
1700

1701
    q = session.query(Queue).filter_by(queue_name=queuename)
1702

1703
    try:
C
Chris Lamb 已提交
1704
        ret = q.one()
1705
    except NoResultFound:
C
Chris Lamb 已提交
1706 1707 1708 1709 1710 1711 1712
        queue = Queue()
        queue.queue_name = queuename
        session.add(queue)
        session.commit_or_flush()
        ret = queue

    return ret
1713

C
Chris Lamb 已提交
1714
__all__.append('get_or_set_queue')
1715

M
Mark Hymers 已提交
1716 1717
################################################################################

M
Mark Hymers 已提交
1718
class QueueBuild(object):
M
Mark Hymers 已提交
1719 1720
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1721 1722 1723 1724

    def __repr__(self):
        return '<QueueBuild %s (%s)>' % (self.filename, self.queue_id)

1725 1726
__all__.append('QueueBuild')

1727
@session_wrapper
1728
def get_queue_build(filename, suite, session=None):
1729
    """
1730
    Returns QueueBuild object for given C{filename} and C{suite}.
1731 1732 1733 1734

    @type filename: string
    @param filename: The name of the file

1735 1736
    @type suiteid: int or str
    @param suiteid: Suite name or ID
1737 1738 1739 1740 1741 1742 1743 1744

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

    @rtype: Queue
    @return: Queue object for the given queue
    """
1745

1746 1747 1748 1749 1750 1751
    if isinstance(suite, int):
        q = session.query(QueueBuild).filter_by(filename=filename).filter_by(suite_id=suite)
    else:
        q = session.query(QueueBuild).filter_by(filename=filename)
        q = q.join(Suite).filter_by(suite_name=suite)

1752 1753 1754 1755
    try:
        return q.one()
    except NoResultFound:
        return None
1756 1757 1758

__all__.append('get_queue_build')

M
Mark Hymers 已提交
1759 1760
################################################################################

M
Mark Hymers 已提交
1761
class Section(object):
M
Mark Hymers 已提交
1762 1763
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1764

1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
    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 已提交
1777 1778 1779
    def __repr__(self):
        return '<Section %s>' % self.section

1780 1781
__all__.append('Section')

1782
@session_wrapper
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
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
    """
1797

1798
    q = session.query(Section).filter_by(section=section)
1799

1800 1801 1802 1803
    try:
        return q.one()
    except NoResultFound:
        return None
1804

1805 1806
__all__.append('get_section')

1807
@session_wrapper
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
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 已提交
1829 1830
################################################################################

1831
class DBSource(object):
M
Mark Hymers 已提交
1832 1833
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
1834 1835

    def __repr__(self):
1836
        return '<DBSource %s (%s)>' % (self.source, self.version)
M
Mark Hymers 已提交
1837

1838
__all__.append('DBSource')
1839

1840
@session_wrapper
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
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

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

    @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()
1867
    ret = 1
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901

    for suite in suites:
        q = session.query(DBSource).filter_by(source=source)
        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])

            q = q.join(SrcAssociation).join(Suite)
            q = q.filter(Suite.suite_name.in_(s))

        # Reduce the query results to a list of version numbers
        ql = [ j.version for j in q.all() ]

        # Try (1)
        if source_version in ql:
            continue

        # Try (2)
        from daklib.regexes import re_bin_only_nmu
        orig_source_version = re_bin_only_nmu.sub('', source_version)
        if orig_source_version in ql:
            continue

        # No source found so return not ok
1902 1903 1904
        ret = 0

    return ret
1905 1906 1907

__all__.append('source_exists')

1908
@session_wrapper
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
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
    """

1920
    return session.query(Suite).join(SrcAssociation).join(DBSource).filter_by(source=source).all()
1921 1922 1923

__all__.append('get_suites_source_in')

1924
@session_wrapper
1925
def get_sources_from_name(source, version=None, dm_upload_allowed=None, session=None):
M
Mark Hymers 已提交
1926
    """
1927
    Returns list of DBSource objects for given C{source} name and other parameters
M
Mark Hymers 已提交
1928 1929

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

1932 1933 1934
    @type source: str or None
    @param source: DBSource version name to search for or None if not applicable

1935 1936 1937 1938
    @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 已提交
1939 1940 1941 1942 1943
    @type session: Session
    @param session: Optional SQL session object (a temporary one will be
    generated if not supplied)

    @rtype: list
1944
    @return: list of DBSource objects for the given name (may be empty)
M
Mark Hymers 已提交
1945
    """
1946 1947

    q = session.query(DBSource).filter_by(source=source)
1948 1949 1950 1951

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

1952 1953 1954
    if dm_upload_allowed is not None:
        q = q.filter_by(dm_upload_allowed=dm_upload_allowed)

1955
    return q.all()
M
Mark Hymers 已提交
1956

1957 1958
__all__.append('get_sources_from_name')

1959
@session_wrapper
1960 1961
def get_source_in_suite(source, suite, session=None):
    """
1962
    Returns list of DBSource objects for a combination of C{source} and C{suite}.
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976

      - 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}

    """
1977

M
updates  
Mark Hymers 已提交
1978 1979 1980
    q = session.query(SrcAssociation)
    q = q.join('source').filter_by(source=source)
    q = q.join('suite').filter_by(suite_name=suite)
1981

1982 1983 1984 1985
    try:
        return q.one().source
    except NoResultFound:
        return None
1986

1987 1988
__all__.append('get_source_in_suite')

M
Mark Hymers 已提交
1989 1990
################################################################################

1991 1992 1993 1994
class SourceACL(object):
    def __init__(self, *args, **kwargs):
        pass

1995 1996 1997
    def __repr__(self):
        return '<SourceACL %s>' % self.source_acl_id

1998 1999 2000 2001
__all__.append('SourceACL')

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

M
Mark Hymers 已提交
2002
class SrcAssociation(object):
M
Mark Hymers 已提交
2003 2004
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2005 2006

    def __repr__(self):
M
Mark Hymers 已提交
2007
        return '<SrcAssociation %s (%s, %s)>' % (self.sa_id, self.source, self.suite)
M
Mark Hymers 已提交
2008

2009 2010
__all__.append('SrcAssociation')

M
Mark Hymers 已提交
2011 2012
################################################################################

2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
class SrcFormat(object):
    def __init__(self, *args, **kwargs):
        pass

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

__all__.append('SrcFormat')

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

M
Mark Hymers 已提交
2024
class SrcUploader(object):
M
Mark Hymers 已提交
2025 2026
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2027 2028 2029 2030

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

2031 2032
__all__.append('SrcUploader')

M
Mark Hymers 已提交
2033 2034
################################################################################

M
Mark Hymers 已提交
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
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'),
                 ('CopyDotDak', 'copydotdak'),
                 ('CommentsDir', 'commentsdir'),
                 ('OverrideSuite', 'overridesuite'),
                 ('ChangelogBase', 'changelogbase')]


M
Mark Hymers 已提交
2055
class Suite(object):
M
Mark Hymers 已提交
2056 2057
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2058 2059 2060 2061

    def __repr__(self):
        return '<Suite %s>' % self.suite_name

2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
    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 已提交
2074 2075 2076 2077 2078 2079 2080 2081 2082
    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)

2083 2084
__all__.append('Suite')

2085
@session_wrapper
M
Mark Hymers 已提交
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
def get_suite_architecture(suite, architecture, session=None):
    """
    Returns a SuiteArchitecture object given C{suite} and ${arch} or None if it
    doesn't exist

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

    @type architecture: str
    @param architecture: Architecture name to search for

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

    @rtype: SuiteArchitecture
    @return: the SuiteArchitecture object or None
    """

    q = session.query(SuiteArchitecture)
    q = q.join(Architecture).filter_by(arch_string=architecture)
    q = q.join(Suite).filter_by(suite_name=suite)
2108

2109 2110 2111 2112
    try:
        return q.one()
    except NoResultFound:
        return None
M
Mark Hymers 已提交
2113

2114
__all__.append('get_suite_architecture')
M
Mark Hymers 已提交
2115

2116
@session_wrapper
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
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 已提交
2129
    @return: Suite object for the requested suite name (None if not present)
2130
    """
2131

2132
    q = session.query(Suite).filter_by(suite_name=suite)
2133

2134 2135 2136 2137
    try:
        return q.one()
    except NoResultFound:
        return None
2138

2139 2140
__all__.append('get_suite')

M
Mark Hymers 已提交
2141 2142
################################################################################

M
Mark Hymers 已提交
2143
class SuiteArchitecture(object):
M
Mark Hymers 已提交
2144 2145
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2146 2147 2148 2149

    def __repr__(self):
        return '<SuiteArchitecture (%s, %s)>' % (self.suite_id, self.arch_id)

2150 2151
__all__.append('SuiteArchitecture')

2152
@session_wrapper
2153
def get_suite_architectures(suite, skipsrc=False, skipall=False, session=None):
M
Mark Hymers 已提交
2154 2155 2156 2157 2158 2159
    """
    Returns list of Architecture objects for given C{suite} name

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

2160 2161 2162 2163 2164 2165 2166 2167
    @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 已提交
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
    @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)
    """

    q = session.query(Architecture)
    q = q.join(SuiteArchitecture)
2178
    q = q.join(Suite).filter_by(suite_name=suite)
2179

2180 2181
    if skipsrc:
        q = q.filter(Architecture.arch_string != 'source')
2182

2183 2184
    if skipall:
        q = q.filter(Architecture.arch_string != 'all')
2185

2186
    q = q.order_by('arch_string')
2187

2188
    return q.all()
M
Mark Hymers 已提交
2189

2190
__all__.append('get_suite_architectures')
M
Mark Hymers 已提交
2191

M
Mark Hymers 已提交
2192 2193
################################################################################

2194 2195 2196 2197 2198 2199 2200 2201 2202
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')

2203
@session_wrapper
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
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')

2224
    return q.all()
2225 2226 2227 2228 2229

__all__.append('get_suite_src_formats')

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

M
Mark Hymers 已提交
2230
class Uid(object):
M
Mark Hymers 已提交
2231 2232
    def __init__(self, *args, **kwargs):
        pass
M
Mark Hymers 已提交
2233

2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
    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

M
Mark Hymers 已提交
2246 2247 2248
    def __repr__(self):
        return '<Uid %s (%s)>' % (self.uid, self.name)

2249 2250
__all__.append('Uid')

2251
@session_wrapper
M
Mark Hymers 已提交
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
def add_database_user(uidname, session=None):
    """
    Adds a database user

    @type uidname: string
    @param uidname: The uid of the user 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
    """
2267 2268

    session.execute("CREATE USER :uid", {'uid': uidname})
2269
    session.commit_or_flush()
M
Mark Hymers 已提交
2270 2271 2272

__all__.append('add_database_user')

2273
@session_wrapper
M
Mark Hymers 已提交
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
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
    """
2291 2292 2293

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

2294 2295 2296
    try:
        ret = q.one()
    except NoResultFound:
2297 2298 2299
        uid = Uid()
        uid.uid = uidname
        session.add(uid)
2300
        session.commit_or_flush()
2301
        ret = uid
M
Mark Hymers 已提交
2302

2303
    return ret
M
Mark Hymers 已提交
2304 2305 2306

__all__.append('get_or_set_uid')

2307
@session_wrapper
2308 2309 2310 2311
def get_uid_from_fingerprint(fpr, session=None):
    q = session.query(Uid)
    q = q.join(Fingerprint).filter_by(fingerprint=fpr)

2312 2313 2314 2315
    try:
        return q.one()
    except NoResultFound:
        return None
2316 2317 2318

__all__.append('get_uid_from_fingerprint')

M
Mark Hymers 已提交
2319 2320
################################################################################

2321 2322 2323 2324
class UploadBlock(object):
    def __init__(self, *args, **kwargs):
        pass

2325 2326 2327
    def __repr__(self):
        return '<UploadBlock %s (%s)>' % (self.source, self.upload_block_id)

2328 2329 2330 2331
__all__.append('UploadBlock')

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

M
Mark Hymers 已提交
2332 2333
class DBConn(Singleton):
    """
2334
    database module init.
M
Mark Hymers 已提交
2335 2336 2337 2338 2339
    """
    def __init__(self, *args, **kwargs):
        super(DBConn, self).__init__(*args, **kwargs)

    def _startup(self, *args, **kwargs):
M
updates  
Mark Hymers 已提交
2340 2341 2342
        self.debug = False
        if kwargs.has_key('debug'):
            self.debug = True
M
Mark Hymers 已提交
2343 2344
        self.__createconn()

M
Mark Hymers 已提交
2345 2346
    def __setuptables(self):
        self.tbl_architecture = Table('architecture', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2347 2348 2349
        self.tbl_archive = Table('archive', self.db_meta, autoload=True)
        self.tbl_bin_associations = Table('bin_associations', self.db_meta, autoload=True)
        self.tbl_binaries = Table('binaries', self.db_meta, autoload=True)
2350 2351
        self.tbl_binary_acl = Table('binary_acl', self.db_meta, autoload=True)
        self.tbl_binary_acl_map = Table('binary_acl_map', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2352 2353 2354 2355 2356 2357 2358 2359 2360
        self.tbl_component = Table('component', self.db_meta, autoload=True)
        self.tbl_config = Table('config', self.db_meta, autoload=True)
        self.tbl_content_associations = Table('content_associations', self.db_meta, autoload=True)
        self.tbl_content_file_names = Table('content_file_names', self.db_meta, autoload=True)
        self.tbl_content_file_paths = Table('content_file_paths', self.db_meta, autoload=True)
        self.tbl_dsc_files = Table('dsc_files', self.db_meta, autoload=True)
        self.tbl_files = Table('files', self.db_meta, autoload=True)
        self.tbl_fingerprint = Table('fingerprint', self.db_meta, autoload=True)
        self.tbl_keyrings = Table('keyrings', self.db_meta, autoload=True)
J
Joerg Jaspert 已提交
2361
        self.tbl_known_changes = Table('known_changes', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2362
        self.tbl_keyring_acl_map = Table('keyring_acl_map', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2363 2364
        self.tbl_location = Table('location', self.db_meta, autoload=True)
        self.tbl_maintainer = Table('maintainer', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2365
        self.tbl_new_comments = Table('new_comments', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2366 2367 2368 2369 2370 2371 2372 2373
        self.tbl_override = Table('override', self.db_meta, autoload=True)
        self.tbl_override_type = Table('override_type', self.db_meta, autoload=True)
        self.tbl_pending_content_associations = Table('pending_content_associations', self.db_meta, autoload=True)
        self.tbl_priority = Table('priority', self.db_meta, autoload=True)
        self.tbl_queue = Table('queue', self.db_meta, autoload=True)
        self.tbl_queue_build = Table('queue_build', self.db_meta, autoload=True)
        self.tbl_section = Table('section', self.db_meta, autoload=True)
        self.tbl_source = Table('source', self.db_meta, autoload=True)
2374
        self.tbl_source_acl = Table('source_acl', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2375
        self.tbl_src_associations = Table('src_associations', self.db_meta, autoload=True)
2376
        self.tbl_src_format = Table('src_format', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2377 2378 2379
        self.tbl_src_uploaders = Table('src_uploaders', self.db_meta, autoload=True)
        self.tbl_suite = Table('suite', self.db_meta, autoload=True)
        self.tbl_suite_architectures = Table('suite_architectures', self.db_meta, autoload=True)
2380
        self.tbl_suite_src_formats = Table('suite_src_formats', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2381
        self.tbl_uid = Table('uid', self.db_meta, autoload=True)
2382
        self.tbl_upload_blocks = Table('upload_blocks', self.db_meta, autoload=True)
M
Mark Hymers 已提交
2383 2384

    def __setupmappers(self):
M
Mark Hymers 已提交
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
        mapper(Architecture, self.tbl_architecture,
               properties = dict(arch_id = self.tbl_architecture.c.id))

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

        mapper(BinAssociation, self.tbl_bin_associations,
               properties = dict(ba_id = self.tbl_bin_associations.c.id,
                                 suite_id = self.tbl_bin_associations.c.suite,
M
Mark Hymers 已提交
2395 2396
                                 suite = relation(Suite),
                                 binary_id = self.tbl_bin_associations.c.bin,
2397
                                 binary = relation(DBBinary)))
M
Mark Hymers 已提交
2398

M
Mike O'Connor 已提交
2399

2400
        mapper(DBBinary, self.tbl_binaries,
M
Mark Hymers 已提交
2401
               properties = dict(binary_id = self.tbl_binaries.c.id,
M
Mark Hymers 已提交
2402 2403
                                 package = self.tbl_binaries.c.package,
                                 version = self.tbl_binaries.c.version,
M
Mark Hymers 已提交
2404
                                 maintainer_id = self.tbl_binaries.c.maintainer,
M
Mark Hymers 已提交
2405
                                 maintainer = relation(Maintainer),
M
Mark Hymers 已提交
2406
                                 source_id = self.tbl_binaries.c.source,
2407
                                 source = relation(DBSource),
M
Mark Hymers 已提交
2408
                                 arch_id = self.tbl_binaries.c.architecture,
M
Mark Hymers 已提交
2409 2410 2411 2412 2413 2414 2415 2416 2417
                                 architecture = relation(Architecture),
                                 poolfile_id = self.tbl_binaries.c.file,
                                 poolfile = relation(PoolFile),
                                 binarytype = self.tbl_binaries.c.type,
                                 fingerprint_id = self.tbl_binaries.c.sig_fpr,
                                 fingerprint = relation(Fingerprint),
                                 install_date = self.tbl_binaries.c.install_date,
                                 binassociations = relation(BinAssociation,
                                                            primaryjoin=(self.tbl_binaries.c.id==self.tbl_bin_associations.c.bin))))
M
Mark Hymers 已提交
2418

2419 2420 2421 2422
        mapper(BinaryACL, self.tbl_binary_acl,
               properties = dict(binary_acl_id = self.tbl_binary_acl.c.id))

        mapper(BinaryACLMap, self.tbl_binary_acl_map,
2423 2424 2425
               properties = dict(binary_acl_map_id = self.tbl_binary_acl_map.c.id,
                                 fingerprint = relation(Fingerprint, backref="binary_acl_map"),
                                 architecture = relation(Architecture)))
2426

M
Mark Hymers 已提交
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
        mapper(Component, self.tbl_component,
               properties = dict(component_id = self.tbl_component.c.id,
                                 component_name = self.tbl_component.c.name))

        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,
2437
                                 source = relation(DBSource),
M
Mark Hymers 已提交
2438 2439
                                 poolfile_id = self.tbl_dsc_files.c.file,
                                 poolfile = relation(PoolFile)))
M
Mark Hymers 已提交
2440 2441 2442 2443

        mapper(PoolFile, self.tbl_files,
               properties = dict(file_id = self.tbl_files.c.id,
                                 filesize = self.tbl_files.c.size,
M
Mark Hymers 已提交
2444 2445
                                 location_id = self.tbl_files.c.location,
                                 location = relation(Location)))
M
Mark Hymers 已提交
2446 2447 2448 2449

        mapper(Fingerprint, self.tbl_fingerprint,
               properties = dict(fingerprint_id = self.tbl_fingerprint.c.id,
                                 uid_id = self.tbl_fingerprint.c.uid,
M
Mark Hymers 已提交
2450 2451
                                 uid = relation(Uid),
                                 keyring_id = self.tbl_fingerprint.c.keyring,
2452 2453 2454
                                 keyring = relation(Keyring),
                                 source_acl = relation(SourceACL),
                                 binary_acl = relation(BinaryACL)))
M
Mark Hymers 已提交
2455 2456 2457 2458 2459

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

J
Joerg Jaspert 已提交
2460 2461 2462
        mapper(KnownChange, self.tbl_known_changes,
               properties = dict(known_change_id = self.tbl_known_changes.c.id))

M
Mark Hymers 已提交
2463 2464 2465 2466 2467
        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 已提交
2468 2469 2470
        mapper(Location, self.tbl_location,
               properties = dict(location_id = self.tbl_location.c.id,
                                 component_id = self.tbl_location.c.component,
M
Mark Hymers 已提交
2471
                                 component = relation(Component),
M
Mark Hymers 已提交
2472
                                 archive_id = self.tbl_location.c.archive,
M
Mark Hymers 已提交
2473
                                 archive = relation(Archive),
M
Mark Hymers 已提交
2474 2475 2476 2477 2478
                                 archive_type = self.tbl_location.c.type))

        mapper(Maintainer, self.tbl_maintainer,
               properties = dict(maintainer_id = self.tbl_maintainer.c.id))

M
Mark Hymers 已提交
2479 2480 2481
        mapper(NewComment, self.tbl_new_comments,
               properties = dict(comment_id = self.tbl_new_comments.c.id))

M
Mark Hymers 已提交
2482 2483
        mapper(Override, self.tbl_override,
               properties = dict(suite_id = self.tbl_override.c.suite,
M
Mark Hymers 已提交
2484
                                 suite = relation(Suite),
M
Mark Hymers 已提交
2485
                                 component_id = self.tbl_override.c.component,
M
Mark Hymers 已提交
2486
                                 component = relation(Component),
M
Mark Hymers 已提交
2487
                                 priority_id = self.tbl_override.c.priority,
M
Mark Hymers 已提交
2488
                                 priority = relation(Priority),
M
Mark Hymers 已提交
2489
                                 section_id = self.tbl_override.c.section,
M
Mark Hymers 已提交
2490 2491 2492
                                 section = relation(Section),
                                 overridetype_id = self.tbl_override.c.type,
                                 overridetype = relation(OverrideType)))
M
Mark Hymers 已提交
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505

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

        mapper(Priority, self.tbl_priority,
               properties = dict(priority_id = self.tbl_priority.c.id))

        mapper(Queue, self.tbl_queue,
               properties = dict(queue_id = self.tbl_queue.c.id))

        mapper(QueueBuild, self.tbl_queue_build,
               properties = dict(suite_id = self.tbl_queue_build.c.suite,
M
Mark Hymers 已提交
2506
                                 queue_id = self.tbl_queue_build.c.queue,
2507
                                 queue = relation(Queue, backref='queuebuild')))
M
Mark Hymers 已提交
2508 2509 2510 2511

        mapper(Section, self.tbl_section,
               properties = dict(section_id = self.tbl_section.c.id))

2512
        mapper(DBSource, self.tbl_source,
M
Mark Hymers 已提交
2513
               properties = dict(source_id = self.tbl_source.c.id,
M
Mark Hymers 已提交
2514
                                 version = self.tbl_source.c.version,
M
Mark Hymers 已提交
2515
                                 maintainer_id = self.tbl_source.c.maintainer,
M
Mark Hymers 已提交
2516 2517 2518 2519
                                 maintainer = relation(Maintainer,
                                                       primaryjoin=(self.tbl_source.c.maintainer==self.tbl_maintainer.c.id)),
                                 poolfile_id = self.tbl_source.c.file,
                                 poolfile = relation(PoolFile),
M
Mark Hymers 已提交
2520
                                 fingerprint_id = self.tbl_source.c.sig_fpr,
M
Mark Hymers 已提交
2521 2522 2523 2524 2525 2526 2527
                                 fingerprint = relation(Fingerprint),
                                 changedby_id = self.tbl_source.c.changedby,
                                 changedby = relation(Maintainer,
                                                      primaryjoin=(self.tbl_source.c.changedby==self.tbl_maintainer.c.id)),
                                 srcfiles = relation(DSCFile,
                                                     primaryjoin=(self.tbl_source.c.id==self.tbl_dsc_files.c.source)),
                                 srcassociations = relation(SrcAssociation,
M
Mark Hymers 已提交
2528 2529
                                                            primaryjoin=(self.tbl_source.c.id==self.tbl_src_associations.c.source)),
                                 srcuploaders = relation(SrcUploader)))
M
Mark Hymers 已提交
2530

2531 2532
        mapper(SourceACL, self.tbl_source_acl,
               properties = dict(source_acl_id = self.tbl_source_acl.c.id))
M
Mark Hymers 已提交
2533 2534

        mapper(SrcAssociation, self.tbl_src_associations,
M
Mark Hymers 已提交
2535 2536 2537 2538
               properties = dict(sa_id = self.tbl_src_associations.c.id,
                                 suite_id = self.tbl_src_associations.c.suite,
                                 suite = relation(Suite),
                                 source_id = self.tbl_src_associations.c.source,
2539
                                 source = relation(DBSource)))
M
Mark Hymers 已提交
2540

2541 2542 2543 2544
        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 已提交
2545 2546 2547
        mapper(SrcUploader, self.tbl_src_uploaders,
               properties = dict(uploader_id = self.tbl_src_uploaders.c.id,
                                 source_id = self.tbl_src_uploaders.c.source,
2548
                                 source = relation(DBSource,
M
Mark Hymers 已提交
2549 2550 2551 2552
                                                   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 已提交
2553 2554

        mapper(Suite, self.tbl_suite,
2555 2556
               properties = dict(suite_id = self.tbl_suite.c.id,
                                 policy_queue = relation(Queue)))
M
Mark Hymers 已提交
2557 2558 2559

        mapper(SuiteArchitecture, self.tbl_suite_architectures,
               properties = dict(suite_id = self.tbl_suite_architectures.c.suite,
2560
                                 suite = relation(Suite, backref='suitearchitectures'),
M
Mark Hymers 已提交
2561 2562
                                 arch_id = self.tbl_suite_architectures.c.architecture,
                                 architecture = relation(Architecture)))
M
Mark Hymers 已提交
2563

2564 2565 2566 2567 2568 2569
        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 已提交
2570
        mapper(Uid, self.tbl_uid,
2571 2572
               properties = dict(uid_id = self.tbl_uid.c.id,
                                 fingerprint = relation(Fingerprint)))
M
Mark Hymers 已提交
2573

2574
        mapper(UploadBlock, self.tbl_upload_blocks,
2575 2576 2577
               properties = dict(upload_block_id = self.tbl_upload_blocks.c.id,
                                 fingerprint = relation(Fingerprint, backref="uploadblocks"),
                                 uid = relation(Uid, backref="uploadblocks")))
2578

M
Mark Hymers 已提交
2579 2580
    ## Connection functions
    def __createconn(self):
M
Mark Hymers 已提交
2581
        from config import Config
2582 2583
        cnf = Config()
        if cnf["DB::Host"]:
M
Mark Hymers 已提交
2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
            # 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"]
2594

M
updates  
Mark Hymers 已提交
2595
        self.db_pg   = create_engine(connstr, echo=self.debug)
M
Mark Hymers 已提交
2596 2597 2598 2599
        self.db_meta = MetaData()
        self.db_meta.bind = self.db_pg
        self.db_smaker = sessionmaker(bind=self.db_pg,
                                      autoflush=True,
2600
                                      autocommit=False)
M
Mark Hymers 已提交
2601

M
Mark Hymers 已提交
2602
        self.__setuptables()
M
Mark Hymers 已提交
2603
        self.__setupmappers()
M
Mark Hymers 已提交
2604

M
Mark Hymers 已提交
2605 2606
    def session(self):
        return self.db_smaker()
M
Mark Hymers 已提交
2607

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

2610