Esempio n. 1
0
    def __init__(self, timeout):
        global visit_class
        visit_class_path = config.get("visit.saprovider.model", "turbogears.visit.savisit.TG_Visit")
        visit_class = load_class(visit_class_path)
        if visit_class is None:
            msg = "No visit class found for %s" % visit_class_path
            msg += ", did you run setup.py develop?"
            log.error(msg)

        get_engine()
        if visit_class is TG_Visit:
            mapper(visit_class, visits_table)
        # base-class' __init__ triggers self.create_model, so mappers need to
        # be initialized before.
        super(SqlAlchemyVisitManager, self).__init__(timeout)
Esempio n. 2
0
    def __init__(self, timeout):
        global visit_class
        visit_class_path = config.get("visit.saprovider.model",
            "turbogears.visit.savisit.TG_Visit")
        visit_class = load_class(visit_class_path)
        if visit_class is None:
            msg = 'No visit class found for %s' % visit_class_path
            msg += ', did you run setup.py develop?'
            log.error(msg)

        get_engine()
        if visit_class is TG_Visit:
            mapper(visit_class, visits_table)
        # base-class' __init__ triggers self.create_model, so mappers need to
        # be initialized before.
        super(SqlAlchemyVisitManager, self).__init__(timeout)
Esempio n. 3
0
def create_tables():
    """Create tables filled with test data."""

    occupations_table = Table('occupations', metadata,
        Column('id', Integer, primary_key=True),
        Column('name', String(20)))
    users_table = Table('users', metadata,
        Column('id', Integer, primary_key=True),
        Column('name', String(20)),
        Column('occupation_id', Integer, ForeignKey("occupations.id")))
    addresses_table = Table('addresses', metadata,
        Column('id', Integer, primary_key=True),
        Column('user_id', Integer, ForeignKey("users.id")),
        Column('street', String(50)),
        Column('city', String(40)))

    mapper(Occupation, occupations_table)
    mapper(User, users_table, properties={
        'occupation' : relation(Occupation, lazy=False),
        'addresses': relation(Address, backref='user', lazy=False)})
    mapper(Address, addresses_table)

    try:
        metadata.create_all()
    except Exception, error:
        # workaround for a problem with PySqlite < 2.6 and SQLAlchemy < 0.5
        if 'Cannot operate on a closed cursor' in str(error):
            metadata.create_all(checkfirst=False)
        else:
            raise
Esempio n. 4
0
    def _get_cls(self):
        return self._cls

    pass
    cls = property(_get_cls, _set_cls)


class FileSystem(object):
    pass


mapper(
    Host,
    hosts,
    properties=dict(
        _devices=relation(HostLink, cascade="all,delete-orphan", backref=backref("host"), lazy=None),
        devices=relation(HostLink, cascade="all,delete-orphan"),
        fas_account=relation(FasLink, uselist=False),
        file_systems=relation(FileSystem, backref="host"),
    ),
)

mapper(
    ComputerLogicalDevice,
    computer_logical_devices,
    properties={
        "_host_links": relation(HostLink, cascade="all,delete-orphan", backref=backref("device"), lazy=None),
        "host_links": relation(HostLink, cascade="all,delete-orphan"),
    },
)

mapper(HostLink, host_links)
Esempio n. 5
0
                 ForeignKey('people.id'),
                 unique=True))


class Show(object):
    @classmethod
    def by_name(cls, name):
        return cls.query.filter_by(name=name).one()

    pass


mapper(Show, shows_table,
       properties= \
        dict(group=relation(Groups, uselist=False, backref='show'),
             owner=relation(People, backref='shows'),
             user_signups=relation(People,
                                   backref=backref('show', uselist=False),
                                   secondary=user_signups_table)))


class ShowPlugin(controllers.Controller):
    capabilities = ['show_plugin']

    def __init__(self):
        '''Create a Show Controller.'''
        self.path = ''

    help = Help()

    @expose(template="fas.templates.error")
Esempio n. 6
0
        self.hardware = hardware

class Ykval(object):
    def __init__(self, active, created, modified, yk_publicname, yk_counter, yk_use, yk_low, yk_high, nonce, notes):
        self.active = active
        self.created = created
        self.modified = modified
        self.yk_publicname = yk_publicname
        self.yk_counter = yk_counter
        self.yk_use = yk_use
        self.yk_low = yk_low
        self.yk_high = yk_high
        self.nonce = nonce
        self.notes = notes

mapper(Ykksm, ykksm_table)
mapper(Ykval, ykval_table)

import subprocess

admin_group = config.get('admingroup', 'accounts')
system_group = config.get('systemgroup', 'fas-system')
thirdparty_group = config.get('thirdpartygroup', 'thirdparty')
client_id = '1'

class YubikeySave(validators.Schema):
    targetname = KnownUser
    yubikey_enabled = validators.OneOf(['0', '1'], not_empty=True)
    yubikey_prefix = validators.String(min=12, max=12, not_empty=True)

def get_configs(configs_list):
Esempio n. 7
0
    This is used to make Branch keys for the dictionary mapping of pkg listings
    into packages.
    '''
    return pkg_listing.collection.simple_name


#
# Mappers
#

mapper(
    Package,
    PackageTable,
    properties={
        # listings is here for compatibility.  Will be removed in 0.4.x
        'listings':
        relation(PackageListing),
        'listings2':
        relation(PackageListing,
                 backref=backref('package'),
                 collection_class=mapped_collection(collection_alias))
    })

mapper(PackageListing,
       PackageListingTable,
       properties={
           'people':
           relation(PersonPackageListing),
           'people2':
           relation(PersonPackageListing,
                    backref=backref('packagelisting'),
                    collection_class=attribute_mapped_collection('username')),
Esempio n. 8
0
        return 'PackageListingStatus(%r)' % self.statuscodeid

class PackageAclStatus(BaseStatus):
    ''' Subset of status codes that apply to Person and Group Package Acls.

    Table -- PackageAclStatusCode
    '''
    # pylint: disable-msg=R0902, R0903
    def __repr__(self):
        return 'PackageAclStatus(%r)' % self.statuscodeid

#
# Mappers
#

mapper(StatusTranslation, StatusTranslationTable)
mapper(CollectionStatus, CollectionStatusTable, properties={
    'collections': relation(Collection, backref=backref('status')),
    'collectionPackages': relation(CollectionPackage,
        backref=backref('status')),
    'translations': relation(StatusTranslation,
        order_by=StatusTranslationTable.c.language,
        primaryjoin=StatusTranslationTable.c.statuscodeid \
                == CollectionStatusTable.c.statuscodeid,
        foreign_keys=[StatusTranslationTable.c.statuscodeid]),
    'locale': relation(StatusTranslation,
        primaryjoin=StatusTranslationTable.c.statuscodeid \
                == CollectionStatusTable.c.statuscodeid,
        foreign_keys=[StatusTranslationTable.c.statuscodeid],
        collection_class=attribute_mapped_collection('language'),
        backref=backref('cstatuscode',
Esempio n. 9
0
class Ykval(object):
    def __init__(self, active, created, modified, yk_publicname, yk_counter,
                 yk_use, yk_low, yk_high, nonce, notes):
        self.active = active
        self.created = created
        self.modified = modified
        self.yk_publicname = yk_publicname
        self.yk_counter = yk_counter
        self.yk_use = yk_use
        self.yk_low = yk_low
        self.yk_high = yk_high
        self.nonce = nonce
        self.notes = notes


mapper(Ykksm, ykksm_table)
mapper(Ykval, ykval_table)

import subprocess

admin_group = config.get('admingroup', 'accounts')
system_group = config.get('systemgroup', 'fas-system')
thirdparty_group = config.get('thirdpartygroup', 'thirdparty')
client_id = '1'


class YubikeySave(validators.Schema):
    targetname = KnownUser
    yubikey_enabled = validators.OneOf(['0', '1'], not_empty=True)
    yubikey_prefix = validators.String(min=12, max=12, not_empty=True)
Esempio n. 10
0
                              primary_key=True,
                              autoincrement=True),
                       Column('major', Integer),
                       Column('minor', Integer),
                       Column('point', Integer),
                       Column('branch', String(64),
                              default='main'),
                       Column('name', String(255)),
                       Column('date_applied', DateTime))

class SchemaChange(object):
    def __init__(self, **keys):
        if keys:
            self.major = keys['major']
            self.minor = keys['minor']
            self.point = keys['point']
            self.branch = keys['branch']
            self.name = keys['name']
        self.date_applied = datetime.today()

    def __str__(self):
        return str(self.__dict__)

    __repr__ = __str__
    pass

mapper(SchemaChange, schema_changes,
       order_by=[schema_changes.c.major
                ,schema_changes.c.minor
                ,schema_changes.c.point])
Esempio n. 11
0
        as used
        '''
        used = cls.query.filter_by(nonce=nonce).first()
        if used is not None:
            # This nonce was already used
            return False
        captcha = CaptchaNonce()
        captcha.nonce = nonce
        return True


#
# set up mappers between tables and classes
#

mapper(Session, SessionTable)
mapper(CaptchaNonce, CaptchaNonceTable)

#
# mappers for filtering roles
#
mapper(ApprovedRoles,
       ApprovedRolesSelect,
       properties={
           'group': relation(Groups, backref='approved_roles', lazy=False)
       })
mapper(UnApprovedRoles,
       UnApprovedRolesSelect,
       properties={
           'group': relation(Groups, backref='unapproved_roles', lazy=False)
       })
Esempio n. 12
0
    hopefully have localizations in pkgdb.

    Table -- Languages
    '''
    def __init__(self, name, shortname):
        super(Language, self).__init__()
        self.name = name
        self.shortname = shortname

    def __repr__(self):
        return 'Language(%r, %r)' % (self.name, self.shortname)

    @classmethod
    def find(cls, language):
        '''Returns a shortname after searching for both short and longname.

        :arg name: a short or long Language name
        '''
        #pylint:disable-msg=E1101
        return session.query(Language).filter(
            or_(Language.name == language,
                Language.shortname == language)).one()
        #pylint:enable-msg=E1101


#
# Mappers
#

mapper(Language, LanguagesTable)
Esempio n. 13
0
        self.statuscode = statuscode

    def __repr__(self):
        return 'GroupPackageListingAcl(%r, %r, grouppackagelistingid=%r)' % (
            self.acl, self.statuscode, self.grouppackagelistingid)


#
# Mappers
#

mapper(PersonPackageListing,
       PersonPackageListingTable,
       properties={
           'acls':
           relation(PersonPackageListingAcl),
           'acls2':
           relation(PersonPackageListingAcl,
                    backref=backref('personpackagelisting'),
                    collection_class=attribute_mapped_collection('acl'))
       })
mapper(GroupPackageListing,
       GroupPackageListingTable,
       properties={
           'acls':
           relation(GroupPackageListingAcl),
           'acls2':
           relation(GroupPackageListingAcl,
                    backref=backref('grouppackagelisting'),
                    collection_class=attribute_mapped_collection('acl'))
       })
mapper(PersonPackageListingAcl, PersonPackageListingAclTable)
Esempio n. 14
0
# IMPORTANT
# We *do* allow tracks to exist without an associated album or artist. Is that a good idea? I dunno...


# Here we set up a trigger to call Track.delete_related_files()
class DeleteFileMapperExtension(MapperExtension):
    def after_delete(self, mapper, connection, instance):
        instance._delete_related_files()


mapper(
    Track,
    track,
    extension=DeleteFileMapperExtension(),
    properties={
        'artists': relation(Artist, secondary=artist_track, lazy=True),
        'albums': relation(
            Album, secondary=album_track, lazy=True
        ),  #this causes all sorts of headaches, cascade='delete-orphan'), 
    })

mapper(
    Artist,
    artist,
    properties={
        'albums':
        relation(Album, secondary=album_artist),
        'tracks':
        relation(Track,
                 secondary=artist_track,
                 order_by=Track.title,
Esempio n. 15
0
class FileSystem(object):
    pass

class BatchJob(object):
    def __init__(self, data, hw_uuid, added):
        self.data = data
        self.hw_uuid = hw_uuid
        self.added = added
        self.arrival = text('NOW()')


mapper(Host, hosts,
       properties=dict(_devices=relation(HostLink,
                                         cascade="all,delete-orphan",
                                         backref=backref('host'),
                                         lazy=None),
                      devices=relation(HostLink, cascade='all,delete-orphan'),
                      fas_account=relation(FasLink, uselist=False),
                      file_systems=relation(FileSystem,
                                            backref='host')))

mapper(HostArchive, hosts_archive)

mapper(ComputerLogicalDevice,
       computer_logical_devices,
       properties = {"_host_links": relation(HostLink,
                                            cascade="all,delete-orphan",
                                            backref=backref('device'),
                                            lazy=None),
                     "host_links": relation(HostLink,
                                            cascade="all,delete-orphan")})
Esempio n. 16
0
        """
        return self._password

    password = property(_get_password, _set_password)


class Permission(object):
    """
    A relationship that determines what each Group can do
    """
    pass


# set up mappers between identity tables and classes

mapper(Visit, visits_table)

mapper(VisitIdentity, visit_identity_table,
        properties=dict(users=relation(User, backref='visit_identity')))

mapper(User, users_table,
        properties=dict(_password=users_table.c.password))

mapper(Group, groups_table,
        properties=dict(users=relation(User,
                secondary=user_group_table, backref='groups')))

mapper(Permission, permissions_table,
        properties=dict(groups=relation(Group,
                secondary=group_permission_table, backref='permissions')))
Esempio n. 17
0
    :arg pkg_listing: PackageListing to find the Collection for.
    :returns: Collection Alias.  This is either the branchname or a combination
        of the collection name and version.

    This is used to make Branch keys for the dictionary mapping of pkg listings
    into packages.
    '''
    return pkg_listing.collection.simple_name

#
# Mappers
#

mapper(Package, PackageTable, properties={
    # listings is here for compatibility.  Will be removed in 0.4.x
    'listings': relation(PackageListing),
    'listings2': relation(PackageListing,
        backref=backref('package'),
        collection_class=mapped_collection(collection_alias))
    })

mapper(PackageListing, PackageListingTable, properties={
    'people': relation(PersonPackageListing),
    'people2': relation(PersonPackageListing, backref=backref('packagelisting'),
        collection_class = attribute_mapped_collection('username')),
    'groups': relation(GroupPackageListing),
    'groups2': relation(GroupPackageListing, backref=backref('packagelisting'),
        collection_class = attribute_mapped_collection('groupname')),
    })

Esempio n. 18
0
#
# Mappers
#

mapper(
    Collection,
    CollectionJoin,
    polymorphic_on=CollectionJoin.c.kind,
    polymorphic_identity='c',
    with_polymorphic='*',
    properties={
        # listings is deprecated.  It will go away in 0.4.x
        'listings':
        relation(PackageListing),
        # listings2 is slower than listings.  It has a front-end cost to
        # load the data into the dict.  However, if we're using listings
        # to search for multiple packages, this will likely be faster.
        # Have to look at how it's being used in production and decide
        # what to do.
        'listings2':
        relation(PackageListing,
                 backref=backref('collection'),
                 collection_class=attribute_mapped_collection('packagename')),
        'repos':
        relation(Repo, backref=backref('collection'))
    })
mapper(Branch,
       BranchTable,
       inherits=Collection,
       inherit_condition=CollectionJoin.c.id == BranchTable.c.collectionid,
       polymorphic_identity='b')
Esempio n. 19
0
class Order(object):
    """
    A Facebook order.
    """


    def destroy(self):

        session.delete(self)


########################################################################
# Set up mappers between identity tables and classes.


mapper(Visit, visit_table)

mapper(VisitIdentity, visit_identity_table,
        properties={
            'users': relation(User, backref='visit_identity'),
        })

# TODO: user.cities property
mapper(User, user_table,
        properties={
            '_password': user_table.c.password,
            'cities': relation(City),
            'orders': relation(Order),
        })

mapper(City, city_table,
Esempio n. 20
0
    'schema_changes', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('major', Integer), Column('minor', Integer),
    Column('point', Integer), Column('branch', String(64), default='main'),
    Column('name', String(255)), Column('date_applied', DateTime))


class SchemaChange(object):
    def __init__(self, **keys):
        if keys:
            self.major = keys['major']
            self.minor = keys['minor']
            self.point = keys['point']
            self.branch = keys['branch']
            self.name = keys['name']
        self.date_applied = datetime.today()

    def __str__(self):
        return str(self.__dict__)

    __repr__ = __str__
    pass


mapper(SchemaChange,
       schema_changes,
       order_by=[
           schema_changes.c.major, schema_changes.c.minor,
           schema_changes.c.point
       ])
Esempio n. 21
0
    pass


class BatchJob(object):
    def __init__(self, data, hw_uuid, added):
        self.data = data
        self.hw_uuid = hw_uuid
        self.added = added
        self.arrival = text('NOW()')


mapper(Host,
       hosts,
       properties=dict(_devices=relation(HostLink,
                                         cascade="all,delete-orphan",
                                         backref=backref('host'),
                                         lazy=None),
                       devices=relation(HostLink, cascade='all,delete-orphan'),
                       fas_account=relation(FasLink, uselist=False),
                       file_systems=relation(FileSystem, backref='host')))

mapper(HostArchive, hosts_archive)

mapper(ComputerLogicalDevice,
       computer_logical_devices,
       properties={
           "_host_links":
           relation(HostLink,
                    cascade="all,delete-orphan",
                    backref=backref('device'),
                    lazy=None),
Esempio n. 22
0
# We cascade deletes from Album to AlbumSim and Artist to ArtistSim
# but we currently do not cascade deletes from Artist to Track nor Artist to Album...
# We do cascade from Album to Track but

# IMPORTANT
# We *do* allow tracks to exist without an associated album or artist. Is that a good idea? I dunno...

# Here we set up a trigger to call Track.delete_related_files() 
class DeleteFileMapperExtension(MapperExtension) :
    def after_delete(self,mapper,connection,instance) :
        instance._delete_related_files()

mapper(Track,track, extension=DeleteFileMapperExtension(),
       properties={
                   'artists':relation(Artist,secondary=artist_track,lazy=True), 
                   'albums':relation(Album,secondary=album_track,lazy=True), #this causes all sorts of headaches, cascade='delete-orphan'), 
                   }
       )

mapper(Artist,artist,
       properties={'albums':relation(Album,secondary=album_artist),   
                   'tracks':relation(Track,secondary=artist_track, order_by=Track.title, cascade='all,delete'),  #removed delete-orphan
                   }
       )
mapper(ArtistTrack,artist_track)

mapper(Album,album,
       properties={'artists':relation(Artist,secondary=album_artist),   
                   'tracks':relation(Track,secondary=album_track,order_by=Track.tracknum, cascade='all,delete'), #removed delete-orphan
                   'recommend':relation(Mbalbum_recommend, backref='album',cascade='all,delete,delete-orphan'),
                   'status':relation(AlbumStatus,backref='album',cascade='all,delete,delete-orphan')
Esempio n. 23
0
def setup_module():
    global fresh_metadata, users_table, test_table, Person, Address, Test

    config.update({"sqlalchemy.dburi": "sqlite:///:memory:"})

    if os.path.exists('freshtest.db'):
        os.unlink('freshtest.db')

    get_engine()
    fresh_metadata = MetaData()
    # :memory: can't be used in multiple threads
    fresh_metadata.bind = 'sqlite:///freshtest.db'
    metadata.bind.echo = True
    fresh_metadata.bind.echo = True

    users_table = Table("users", metadata,
                        Column("user_id", Integer, primary_key=True),
                        Column("user_name", String(40)),
                        Column("password", String(10)))

    mapper(User, users_table)

    if ActiveMapper:

        class Person(ActiveMapper):
            class mapping:
                id = column(Integer, primary_key=True)
                name = column(String(40))
                addresses = one_to_many("Address")

        class Address(ActiveMapper):
            class mapping:
                id = column(Integer, primary_key=True)
                address = column(String(40))
                city = column(String(40))
                person_id = column(Integer,
                                   foreign_key=ForeignKey("person.id"))

    else:

        persons_table = Table("persons", metadata,
                              Column("id", Integer, primary_key=True),
                              Column("name", String(40)))
        addresses_table = Table(
            "addresses", metadata, Column("id", Integer, primary_key=True),
            Column("address", String(40)), Column("city", String(40)),
            Column("person_id", Integer, ForeignKey(persons_table.c.id)))

        class Person(object):
            pass

        class Address(object):
            pass

        mapper(Person, persons_table)
        mapper(Address,
               addresses_table,
               properties=dict(person=relation(Person, backref='addresses')))

    test_table = Table("test", fresh_metadata,
                       Column("id", Integer, primary_key=True),
                       Column("val", String(40)))

    class Test(object):
        pass

    mapper(Test, test_table)

    try:
        metadata.create_all()
        fresh_metadata.create_all()
    except Exception, error:
        # workaround for a problem with PySqlite < 2.6 and SQLAlchemy < 0.5
        if 'Cannot operate on a closed cursor' in str(error):
            metadata.create_all(checkfirst=False)
            fresh_metadata.create_all(checkfirst=False)
        else:
            raise
Esempio n. 24
0
    # pylint: disable-msg=R0903
    def __init__(self, acl, statuscode=None, grouppackagelistingid=None):
        # pylint: disable-msg=R0913
        super(GroupPackageListingAcl, self).__init__()
        self.grouppackagelistingid = grouppackagelistingid
        self.acl = acl
        self.statuscode = statuscode

    def __repr__(self):
        return 'GroupPackageListingAcl(%r, %r, grouppackagelistingid=%r)' % (
                self.acl, self.statuscode, self.grouppackagelistingid)

#
# Mappers
#

mapper(PersonPackageListing, PersonPackageListingTable, properties={
    'acls': relation(PersonPackageListingAcl),
    'acls2': relation(PersonPackageListingAcl,
        backref=backref('personpackagelisting'),
        collection_class=attribute_mapped_collection('acl'))
    })
mapper(GroupPackageListing, GroupPackageListingTable, properties={
    'acls': relation(GroupPackageListingAcl),
    'acls2': relation(GroupPackageListingAcl,
        backref=backref('grouppackagelisting'),
        collection_class=attribute_mapped_collection('acl'))
    })
mapper(PersonPackageListingAcl, PersonPackageListingAclTable)
mapper(GroupPackageListingAcl, GroupPackageListingAclTable)
Esempio n. 25
0
File: samadhi.py Progetto: Affix/fas
                                   Column('assoc_type', String(64), nullable = False),
                                   PrimaryKeyConstraint('server_url', 'handle'))

class SamadhiAssociation(object):
    @classmethod
    def get(cls, server_url, handle = None):
        if handle is None:
            return cls.query.filter_by(server_url = server_url).order_by(samadhi_associations_table.c.issued.desc())
        return cls.query.filter_by(server_url = server_url, handle = handle).order_by(samadhi_associations_table.c.issued.desc())

    @classmethod
    def remove(cls, server_url, handle):
        for a in cls.query.filter_by(server_url = server_url, handle = handle):
            session.delete(a)

mapper(SamadhiAssociation, samadhi_associations_table)

samadhi_nonces_table = Table('samadhi_nonces', metadata,
                             Column('server_url', String(2048), nullable = False),
                             Column('timestamp', Integer, nullable = False),
                             Column('salt', String(40), nullable = False),
                             PrimaryKeyConstraint('server_url', 'timestamp', 'salt'))

class SamadhiNonce(object):
    pass

mapper(SamadhiNonce, samadhi_nonces_table)

# Implement an OpenID "store", which is how the OpenID library stores
# persisent data.  Here's the docs that describe it:
#
Esempio n. 26
0
def setup_module():
    global fresh_metadata, users_table, test_table, Person, Address, Test

    config.update({
        "sqlalchemy.dburi" : "sqlite:///:memory:"})

    if os.path.exists('freshtest.db'):
        os.unlink('freshtest.db')

    get_engine()
    fresh_metadata = MetaData()
    # :memory: can't be used in multiple threads
    fresh_metadata.bind = 'sqlite:///freshtest.db'
    metadata.bind.echo = True
    fresh_metadata.bind.echo = True

    users_table = Table("users", metadata,
        Column("user_id", Integer, primary_key=True),
        Column("user_name", String(40)),
        Column("password", String(10)))

    mapper(User, users_table)

    if ActiveMapper:

        class Person(ActiveMapper):
            class mapping:
                id = column(Integer, primary_key=True)
                name = column(String(40))
                addresses = one_to_many("Address")

        class Address(ActiveMapper):
            class mapping:
                id = column(Integer, primary_key=True)
                address = column(String(40))
                city = column(String(40))
                person_id = column(Integer,
                    foreign_key=ForeignKey("person.id"))

    else:

        persons_table = Table("persons", metadata,
                Column("id", Integer, primary_key=True),
                Column("name", String(40)))
        addresses_table = Table("addresses", metadata,
                Column("id", Integer, primary_key=True),
                Column("address", String(40)),
                Column("city", String(40)),
                Column("person_id", Integer,
                    ForeignKey(persons_table.c.id)))

        class Person(object):
            pass

        class Address(object):
            pass

        mapper(Person, persons_table)
        mapper(Address, addresses_table, properties=dict(
            person=relation(Person, backref='addresses')))

    test_table = Table("test", fresh_metadata,
        Column("id", Integer, primary_key=True),
        Column("val", String(40)))

    class Test(object):
        pass

    mapper(Test, test_table)

    try:
        metadata.create_all()
        fresh_metadata.create_all()
    except Exception, error:
        # workaround for a problem with PySqlite < 2.6 and SQLAlchemy < 0.5
        if 'Cannot operate on a closed cursor' in str(error):
            metadata.create_all(checkfirst=False)
            fresh_metadata.create_all(checkfirst=False)
        else:
            raise
Esempio n. 27
0
        as used
        """
        used = cls.query.filter_by(nonce=nonce).first()
        if used is not None:
            # This nonce was already used
            return False
        captcha = CaptchaNonce()
        captcha.nonce = nonce
        return True


#
# set up mappers between tables and classes
#

mapper(Session, SessionTable)
mapper(CaptchaNonce, CaptchaNonceTable)

#
# mappers for filtering roles
#
mapper(ApprovedRoles, ApprovedRolesSelect, properties={"group": relation(Groups, backref="approved_roles", lazy=False)})
mapper(
    UnApprovedRoles,
    UnApprovedRolesSelect,
    properties={"group": relation(Groups, backref="unapproved_roles", lazy=False)},
)


#
# General Mappers
Esempio n. 28
0
class VisitIdentity(SABase):
    '''Associate a user with a visit cookie.

    This allows users to log in to app.
    '''
    pass

class Session(SABase):
    '''Session'''
    pass

#
# set up mappers between tables and classes
#

mapper(Session, SessionTable)

#
# mappers for filtering roles
#
mapper(ApprovedRoles, ApprovedRolesSelect, properties = {
    'group': relation(Groups, backref='approved_roles', lazy = False)
    })
mapper(UnApprovedRoles, UnApprovedRolesSelect, properties = {
    'group': relation(Groups, backref='unapproved_roles', lazy = False)
    })


#
# General Mappers
#
Esempio n. 29
0
# your data tables

# your_table = Table('yourtable', metadata,
#     Column('my_id', Integer, primary_key=True)
# )
comics_table = Table('comic', metadata,
    Column('comic_id', Integer, primary_key=True),
    Column('comic_name', UnicodeText),
    Column('created', DateTime, default=datetime.datetime.now),
    Column('base_url', String(4092)),
    Column('first_comic', Integer),
    Column('start_on', DateTime, default=datetime.datetime.now),
)


# your model classes


# class YourDataClass(object):
#     pass
class Comic(object):
    pass


# set up mappers between your data tables and classes

# mapper(YourDataClass, your_table)
mapper(Comic, comics_table)

Esempio n. 30
0
    def __repr__(self):
        return "<Week('%s', '%s')>" % (self.week_num, self.comments)

class Game(object):
    def __init__(self, week, teams, scores):
        self.week = week
        self.teams = teams
        self.scores = scores
        
    def __repr__(self):
        return "<Game('%s', '%s', '%s')>" % (
            self.week, self.teams, self.scores
        )

# mappers between data tables and classes
mapper(Team, teams_table)
mapper(Score, scores_table,
       properties={
           'team' : relation(
               Team, backref='scores')
       }
)
mapper(Week, weeks_table)
mapper(Game, games_table,
       properties={
           'week' : relation(
               Week, backref='games'),
           'scores' : relation(
               Score, secondary=games_scores_table, backref='game'),
           'teams' : relation(
               Team, secondary=games_teams_table, backref='games'),
Esempio n. 31
0
        return 'CollectionPackage(id=%r, name=%r, version=%r,' \
            ' statuscode=%r, numpkgs=%r,' % (
            self.id, self.name, self.version, self.statuscode, self.numpkgs)

#
# Mappers
#

mapper(Collection, CollectionJoin,
        polymorphic_on=CollectionJoin.c.kind,
        polymorphic_identity='c',
        with_polymorphic='*',
        properties={
            # listings is deprecated.  It will go away in 0.4.x
            'listings': relation(PackageListing),
            # listings2 is slower than listings.  It has a front-end cost to
            # load the data into the dict.  However, if we're using listings
            # to search for multiple packages, this will likely be faster.
            # Have to look at how it's being used in production and decide
            # what to do.
            'listings2': relation(PackageListing,
                backref=backref('collection'),
                collection_class=attribute_mapped_collection('packagename')),
            'repos': relation(Repo, backref=backref('collection'))
        })
mapper(Branch, BranchTable, inherits=Collection,
        inherit_condition=CollectionJoin.c.id==BranchTable.c.collectionid,
        polymorphic_identity='b')
mapper(CollectionPackage, CollectionPackageTable)
mapper(Repo, ReposTable)
Esempio n. 32
0
    Column('old_id', Unicode(5)),
    Column('year', Integer),
    Column('have', Integer),
    Column('rating', Integer),
    Column('genre_id', Integer, ForeignKey("genres.genre_id")),
    Column('atype', Integer),
    Column('date', Date)
)

# set up mappers between your data tables and classes
# http://www.sqlalchemy.org/docs/05/mappers.html

# mapper(YourDataClass, your_table)

mapper(Artist, artists, properties={
    'genre': relationship(Genre, backref='artist')
})
mapper(Genre, genres_table)
mapper(Album, albums_table, properties={
    'artist': relationship(Artist, backref='album'),
    'genre': relationship(Genre, backref='album')
})

# functions for populating the database

def bootstrap_model(clean=False):
    """Create all database tables and fill them with default data.

    This function is run by the 'bootstrap' function from the command module.
    By default it creates all database tables for your model.
Esempio n. 33
0
File: samadhi.py Progetto: ccoss/fas
    @classmethod
    def get(cls, server_url, handle=None):
        if handle is None:
            return cls.query.filter_by(server_url=server_url).order_by(
                samadhi_associations_table.c.issued.desc())
        return cls.query.filter_by(
            server_url=server_url,
            handle=handle).order_by(samadhi_associations_table.c.issued.desc())

    @classmethod
    def remove(cls, server_url, handle):
        for a in cls.query.filter_by(server_url=server_url, handle=handle):
            session.delete(a)


mapper(SamadhiAssociation, samadhi_associations_table)

samadhi_nonces_table = Table(
    'samadhi_nonces', metadata,
    Column('server_url', String(2048), nullable=False),
    Column('timestamp', Integer, nullable=False),
    Column('salt', String(40), nullable=False),
    PrimaryKeyConstraint('server_url', 'timestamp', 'salt'))


class SamadhiNonce(object):
    pass


mapper(SamadhiNonce, samadhi_nonces_table)
Esempio n. 34
0
        """
        return self._password

    password = property(_get_password, _set_password)


class Permission(object):
    """
    A relationship that determines what each Group can do
    """
    pass


# set up mappers between identity tables and classes

mapper(Bid, bids_table)

mapper(SubBid,
       sub_bids_table,
       properties=dict(bids=relation(Bid, backref='sub_bids')))

mapper(Auction,
       auctions_table,
       properties=dict(members=relation(Member, backref='auctions')))

mapper(
    AuctionItem,
    auction_items_table,
    properties=dict(auction_items=relation(Auction, backref='auction_items')))

mapper(Item,
Esempio n. 35
0
    hopefully have localizations in pkgdb.

    Table -- Languages
    '''

    def __init__(self, name, shortname):
        super(Language, self).__init__()
        self.name = name
        self.shortname = shortname

    def __repr__(self):
        return 'Language(%r, %r)' % (self.name, self.shortname)

    @classmethod
    def find(cls, language):
        '''Returns a shortname after searching for both short and longname.

        :arg name: a short or long Language name
        '''
        #pylint:disable-msg=E1101
        return session.query(Language).filter(or_(Language.name==language,
                                         Language.shortname==language
                                         )).one()
        #pylint:enable-msg=E1101

#
# Mappers
#

mapper(Language, LanguagesTable)
Esempio n. 36
0
          Column('people_id', Integer,
                 ForeignKey('people.id'),
                 unique=True))


class Show(object):
    @classmethod
    def by_name(cls, name):
        return cls.query.filter_by(name=name).one()
    pass


mapper(Show, shows_table,
       properties= \
        dict(group=relation(Groups, uselist=False, backref='show'),
             owner=relation(People, backref='shows'),
             user_signups=relation(People, 
                                   backref=backref('show', uselist=False),
                                   secondary=user_signups_table)))

class ShowPlugin(controllers.Controller):
    capabilities = ['show_plugin']

    def __init__(self):
        '''Create a Show Controller.'''
        self.path = ''
        
    help = Help()
    @expose(template="fas.templates.error")
    def error(self, tg_errors=None):
        '''Show a friendly error message'''
Esempio n. 37
0
                literal_column("'grouppkglistacllog'").label('kind'))),
        'log':
        select((LogTable, literal_column("'log'").label('kind')),
               not_(
                   LogTable.c.id.in_(
                       select((LogTable.c.id, ), LogTable.c.id
                              == PackageListingLogTable.c.logid))))
    }, None)

#
# Mappers
#

logMapper = mapper(Log,
                   LogTable,
                   select_table=logJoin,
                   polymorphic_on=logJoin.c.kind,
                   polymorphic_identity='log')

mapper(PersonPackageListingAclLog, PersonPackageListingAclLogTable,
        inherits=logMapper, polymorphic_identity='personpkglistacllog',
        inherit_condition=LogTable.c.id == \
                PersonPackageListingAclLogTable.c.logid,
        properties={
            'acl': relation(PersonPackageListingAcl, backref='logs')
            })

mapper(GroupPackageListingAclLog, GroupPackageListingAclLogTable,
        inherits=logMapper, polymorphic_identity='grouppkglistacllog',
        inherit_condition=LogTable.c.id == \
                GroupPackageListingAclLogTable.c.logid,
Esempio n. 38
0
                literal_column("'grouppkglistacllog'").label("kind"),
            )
        ),
        "log": select(
            (LogTable, literal_column("'log'").label("kind")),
            not_(LogTable.c.id.in_(select((LogTable.c.id,), LogTable.c.id == PackageListingLogTable.c.logid))),
        ),
    },
    None,
)

#
# Mappers
#

logMapper = mapper(Log, LogTable, select_table=logJoin, polymorphic_on=logJoin.c.kind, polymorphic_identity="log")

mapper(
    PersonPackageListingAclLog,
    PersonPackageListingAclLogTable,
    inherits=logMapper,
    polymorphic_identity="personpkglistacllog",
    inherit_condition=LogTable.c.id == PersonPackageListingAclLogTable.c.logid,
    properties={"acl": relation(PersonPackageListingAcl, backref="logs")},
)

mapper(
    GroupPackageListingAclLog,
    GroupPackageListingAclLogTable,
    inherits=logMapper,
    polymorphic_identity="grouppkglistacllog",
Esempio n. 39
0
)

users_table = Table('tg_user', metadata,
    Column('user_id', Integer, primary_key=True),
    Column('user_name', Unicode(16), unique=True),
    Column('email_address', Unicode(255), unique=True),
    Column('display_name', Unicode(255)),
    Column('password', Unicode(40)),
    Column('created', DateTime, default=datetime.now)
)

user_group_table = Table('user_group', metadata,
    Column('user_id', Integer, ForeignKey('tg_user.user_id')),
    Column('group_id', Integer, ForeignKey('tg_group.group_id'))
)

class User(object):
    
    def __repr__(self):
        return "class User user_id=%s email_address=%s display_name=%s" % (
                self.user_id, self.email_address, self.display_name)
    
class Group(object):
    pass
    
gmapper = database.mapper(Group, groups_table)
umapper = database.mapper(User, users_table, properties=dict(
    groups = relation(Group, secondary=user_group_table, backref='users')
    )
)
Esempio n. 40
0
# your data tables

# your_table = Table('yourtable', metadata,
#     Column('my_id', Integer, primary_key=True)
# )

servers_table = Table('servers', metadata,
    Column('id', Integer, primary_key=True),
    Column('tag', Integer),
    Column('name', Unicode),
    Column('description', Unicode),
    Column('date_created', DateTime, default=datetime.now),
    Column('last_modified', DateTime, default=datetime.now),
    Column('physical_id', Integer, ForeignKey('servers.id'))
)

# your model classes

# class YourDataClass(object):
#     pass

class Server(object):
    pass

# set up mappers between your data tables and classes

# mapper(YourDataClass, your_table)

mapper(Server, servers_table,
       properties=dict(physicals=relation(Server, backref='servers')))
Esempio n. 41
0
        """
        return self._password

    password = property(_get_password, _set_password)


class Permission(object):
    """
    A relationship that determines what each Group can do
    """
    pass


# set up mappers between identity tables and classes

mapper(Bid, bids_table)

mapper(SubBid, sub_bids_table,
        properties=dict(bids=relation(Bid, backref='sub_bids')))

mapper(Auction, auctions_table,
       properties=dict(members=relation(Member, backref='auctions')))

mapper(AuctionItem, auction_items_table,
       properties=dict(auction_items=relation(Auction, backref='auction_items')))

mapper(Item, items_table,
       properties=dict(members=relation(Member, backref='items')))

mapper(ItemHistory, item_history_table,
       properties=dict(items=relation(Item, backref='item_history')))