Exemplo n.º 1
0
    def test_override_attributes(self):
        class SomeObject(object):
            pass

        class SomeOtherObject(object):
            pass

        ctx = SessionContext(create_session)
        assign_mapper(
            ctx,
            SomeObject,
            table,
            properties={
                # this is the current workaround for class attribute name/collection collision: specify collection_class
                # explicitly.   when we do away with class attributes specifying collection classes, this wont be
                # needed anymore.
                'options': relation(SomeOtherObject, collection_class=list)
            })
        assign_mapper(ctx, SomeOtherObject, table2)
        class_mapper(SomeObject)
        s = SomeObject()
        s.id = 1
        s.data = 'hello'
        sso = SomeOtherObject()
        s.options.append(sso)
        ctx.current.flush()
        ctx.current.clear()

        assert SomeObject.get_by(id=s.id).options[0].id == sso.id
Exemplo n.º 2
0
    def test_dont_clobber_methods(self):
        class MyClass(object):
            def expunge(self):
                return "an expunge !"

        assign_mapper(ctx, MyClass, table2)

        assert MyClass().expunge() == "an expunge !"
Exemplo n.º 3
0
 def assign_and_create(obj, table, **localkw):
     table.tometadata(meta)
     sendkw = dict([(k, v) for k, v in localkw.items()])
     sendkw.update(kw)
     assign_mapper(session_context, obj, table, **sendkw)
     checkfirst = False
     import sys
     table.create(meta.engine, checkfirst=checkfirst)
Exemplo n.º 4
0
 def __init__(self, timeout):
     global visit_class
     super(SqlAlchemyVisitManager,self).__init__(timeout)
     visit_class_path = config.get("visit.saprovider.model",
                            "turbogears.visit.savisit.TG_Visit")
     visit_class = load_class(visit_class_path)
     bind_meta_data()
     if visit_class is TG_Visit:
         assign_mapper(session.context, visit_class, visits_table)
Exemplo n.º 5
0
    def test_override_attributes(self):

        sso = SomeOtherObject.query().first()

        assert SomeObject.query.filter_by(id=1).one().options[0].id == sso.id

        s2 = SomeObject(someid=12)
        s3 = SomeOtherObject(someid=123, bogus=345)

        class ValidatedOtherObject(object):pass
        assign_mapper(ctx, ValidatedOtherObject, table2, validate=True)

        v1 = ValidatedOtherObject(someid=12)
        try:
            v2 = ValidatedOtherObject(someid=12, bogus=345)
            assert False
        except exceptions.ArgumentError:
            pass
Exemplo n.º 6
0
    def setUp(self):
        global SomeObject, SomeOtherObject, ctx
        class SomeObject(object):pass
        class SomeOtherObject(object):pass

        ctx = SessionContext(create_session)
        assign_mapper(ctx, SomeObject, table, properties={
            'options':relation(SomeOtherObject)
            })
        assign_mapper(ctx, SomeOtherObject, table2)

        s = SomeObject()
        s.id = 1
        s.data = 'hello'
        sso = SomeOtherObject()
        s.options.append(sso)
        ctx.current.flush()
        ctx.current.clear()
Exemplo n.º 7
0
 def test_override_attributes(self):
     class SomeObject(object):pass
     class SomeOtherObject(object):pass
     
     ctx = SessionContext(create_session)
     assign_mapper(ctx, SomeObject, table, properties={
         # this is the current workaround for class attribute name/collection collision: specify collection_class
         # explicitly.   when we do away with class attributes specifying collection classes, this wont be
         # needed anymore.
         'options':relation(SomeOtherObject, collection_class=list)
     })
     assign_mapper(ctx, SomeOtherObject, table2)
     class_mapper(SomeObject)
     s = SomeObject()
     s.id = 1
     s.data = 'hello'
     sso = SomeOtherObject()
     s.options.append(sso)
     ctx.current.flush()
     ctx.current.clear()
     
     assert SomeObject.get_by(id=s.id).options[0].id == sso.id
Exemplo n.º 8
0
def assign(*args, **kw):
    """Map tables to objects with knowledge about the session context."""
    return assign_mapper(session.context, *args, **kw)
Exemplo n.º 9
0
    Column( "dataset_id", Integer, ForeignKey( "dataset.id" ) ),
    Column( "name", String(255) ) )
    
Event.table = Table( "event", metadata, 
    Column( "id", Integer, primary_key=True ),
    Column( "create_time", DateTime, PassiveDefault( func.current_timestamp() ) ),
    Column( "update_time", DateTime, PassiveDefault( func.current_timestamp() ), onupdate=func.current_timestamp() ),
    Column( "history_id", Integer, nullable=True ),
    Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), nullable=True ),
    Column( "message", TrimmedString( 1024 ) ) )

# With the tables defined we can define the mappers and setup the 
# relationships between the model objects.

assign_mapper( context, Dataset, Dataset.table,
    properties=dict( children=relation( Dataset, cascade="delete", 
                                        backref=backref("parent", foreignkey=Dataset.table.c.id ) ) ) )

# assign_mapper( model.Query, model.Query.table,
#     properties=dict( datasets=relation( model.Dataset.mapper, backref="query") ) )

assign_mapper( context, History, History.table,
    properties=dict( datasets=relation( Dataset, backref="history", lazy=False, 
                                        order_by=asc(Dataset.table.c.hid) ) ) )

assign_mapper( context, User, User.table, 
    properties=dict( histories=relation( History, backref="user", 
                                         order_by=desc(History.table.c.update_time) ) ) )

assign_mapper( context, JobToInputDatasetAssociation, JobToInputDatasetAssociation.table,
    properties=dict( job=relation( Job ), dataset=relation( Dataset ) ) )
Exemplo n.º 10
0
def assign(*args, **kw):
    """Map tables to objects with knowledge about the session context."""
    return assign_mapper(session.context, *args, **kw)
Exemplo n.º 11
0
def assign_mapper(class_, *args, **kwargs):
    assignmapper.assign_mapper(objectstore.context, class_, *args, **kwargs)
Exemplo n.º 12
0
    def update_model(self, model):
        
        meta = model.meta
        ctx = model.ctx
        
        class User(object):
            def __init__(
                self,
                username,
                uid=None,
                password=None,
                group_uid=None,
            ):
                self.id         = id
                self.username   = username
                self.password   = password
                self.group_uid  = group_uid
            def __repr__(self):
                return "User(%(username)s)" % self.__dict__

        class Group(object):
            def __init__(self, name=None):
                self.name = name
            def __repr__(self):
                return "Group(%(name)s)" % self.__dict__
                
        class Role(object):
            def __init__(self, name=None):
                self.name = name
            def __repr__(self):
                return "Role(%(name)s)" % self.__dict__
                
        # Tables
        groups_table = Table(
            "groups",
            meta,
            Column("uid",        Integer,        primary_key=True),
            Column("name",      String(255),    unique=True,    nullable=False),
        )
        roles_table = Table(
            "roles",
            meta,
            Column("uid",        Integer,        primary_key=True),
            Column("name",      String(255),    unique=True,    nullable=False),
        )
        users_table = Table(
            "users",
            meta,
            Column("uid",        Integer,        primary_key=True),
            Column("username",  String(255),    unique=True,    nullable=False),
            Column("password",  String(255),     nullable=False),
            Column("group_uid",  Integer,        ForeignKey("groups.uid")),
        )
        users_roles_table = Table(                # many:many relation table
            "users_roles",
            meta,
            Column("user_uid",   Integer,        ForeignKey("users.uid")),
            Column("role_uid",   Integer,        ForeignKey("roles.uid")),
        )
           
        groups_mapper = assign_mapper(
            ctx,
            Group,
            groups_table,
            properties={
                "users": relation(User)
            }
        )
        users_mapper = assign_mapper(
            ctx,
            User,
            users_table,
            properties={
                "roles": relation(Role, lazy=True, secondary=users_roles_table),
                "group": relation(Group),
            }
        )
        roles_mapper = assign_mapper(
            ctx,
            Role,
            roles_table,
            properties={
                "users": relation(User, lazy=True, secondary=users_roles_table)
            }
        )

        model.User = User
        model.Group = Group
        model.Role = Role
        return model
Exemplo n.º 13
0
    def __init__(cls, clsname, bases, dict):
        table_name = clsname.lower()
        columns = []
        relations = {}
        autoload = False
        _metadata = getattr(sys.modules[cls.__module__], "__metadata__",
                            metadata)
        version_id_col = None
        version_id_col_object = None
        table_opts = {}

        if 'mapping' in dict:
            found_pk = False

            members = inspect.getmembers(dict.get('mapping'))
            for name, value in members:
                if name == '__table__':
                    table_name = value
                    continue

                if '__metadata__' == name:
                    _metadata = value
                    continue

                if '__autoload__' == name:
                    autoload = True
                    continue

                if '__version_id_col__' == name:
                    version_id_col = value

                if '__table_opts__' == name:
                    table_opts = value

                if name.startswith('__'): continue

                if isinstance(value, column):
                    if value.primary_key == True: found_pk = True

                    if value.foreign_key:
                        col = Column(value.colname or name,
                                     value.coltype,
                                     value.foreign_key,
                                     primary_key=value.primary_key,
                                     *value.args,
                                     **value.kwargs)
                    else:
                        col = Column(value.colname or name,
                                     value.coltype,
                                     primary_key=value.primary_key,
                                     *value.args,
                                     **value.kwargs)
                    columns.append(col)
                    continue

                if isinstance(value, relationship):
                    relations[name] = value

            if not found_pk and not autoload:
                col = Column('id', Integer, primary_key=True)
                cls.mapping.id = col
                columns.append(col)

            assert _metadata is not None, "No MetaData specified"

            ActiveMapperMeta.metadatas.add(_metadata)

            if not autoload:
                cls.table = Table(table_name, _metadata, *columns,
                                  **table_opts)
                cls.columns = columns
            else:
                cls.table = Table(table_name,
                                  _metadata,
                                  autoload=True,
                                  **table_opts)
                cls.columns = cls.table._columns

            # check for inheritence
            if version_id_col is not None:
                version_id_col_object = getattr(cls.table.c, version_id_col,
                                                None)
                assert (version_id_col_object is not None,
                        "version_id_col (%s) does not exist." % version_id_col)

            if hasattr(bases[0], "mapping"):
                cls._base_mapper = bases[0].mapper
                assign_mapper(objectstore.context,
                              cls,
                              cls.table,
                              inherits=cls._base_mapper,
                              version_id_col=version_id_col_object)
            else:
                assign_mapper(objectstore.context,
                              cls,
                              cls.table,
                              version_id_col=version_id_col_object)
            cls.relations = relations
            ActiveMapperMeta.classes[clsname] = cls

            process_relationships(cls)

        super(ActiveMapperMeta, cls).__init__(clsname, bases, dict)
Exemplo n.º 14
0

climateCodeToName = {
    'normal': 'Temperate',
    'desert': 'Desert',
    'hilly': 'Arctic',
    'candy': 'Toyland',
}

climateNamesToCode = dict([(v, k) for k, v in climateCodeToName.iteritems()])


class User(object):
    def canManage(self, user):
        return self is user


class Server(object):
    def touch(self):
        self.config_changed = datetime.utcnow()
        self.flush()


class Version(object):
    pass


assign_mapper(ctx, User, users_table)
assign_mapper(ctx, Server, servers_table)
assign_mapper(ctx, Version, openttd_versions_table)
Exemplo n.º 15
0
    def __init__(cls, clsname, bases, dict):
        table_name = clsname.lower()
        columns    = []
        relations  = {}
        autoload   = False
        _metadata  = getattr(sys.modules[cls.__module__], 
                             "__metadata__", metadata)
        version_id_col = None
        version_id_col_object = None
        table_opts = {}

        if 'mapping' in dict:
            found_pk = False
            
            members = inspect.getmembers(dict.get('mapping'))
            for name, value in members:
                if name == '__table__':
                    table_name = value
                    continue
                
                if '__metadata__' == name:
                    _metadata= value
                    continue
                
                if '__autoload__' == name:
                    autoload = True
                    continue
                
                if '__version_id_col__' == name:
                    version_id_col = value
                
                if '__table_opts__' == name:
                    table_opts = value

                if name.startswith('__'): continue
                
                if isinstance(value, column):
                    if value.primary_key == True: found_pk = True
                        
                    if value.foreign_key:
                        col = Column(value.colname or name, 
                                     value.coltype,
                                     value.foreign_key, 
                                     primary_key=value.primary_key,
                                     *value.args, **value.kwargs)
                    else:
                        col = Column(value.colname or name,
                                     value.coltype,
                                     primary_key=value.primary_key,
                                     *value.args, **value.kwargs)
                    columns.append(col)
                    continue
                
                if isinstance(value, relationship):
                    relations[name] = value
            
            if not found_pk and not autoload:
                col = Column('id', Integer, primary_key=True)
                cls.mapping.id = col
                columns.append(col)
            
            assert _metadata is not None, "No MetaData specified"
            
            ActiveMapperMeta.metadatas.add(_metadata)
            
            if not autoload:
                cls.table = Table(table_name, _metadata, *columns, **table_opts)
                cls.columns = columns
            else:
                cls.table = Table(table_name, _metadata, autoload=True, **table_opts)
                cls.columns = cls.table._columns
            
            if version_id_col is not None:
                version_id_col_object = getattr(cls.table.c, version_id_col, None)
                assert(version_id_col_object is not None, "version_id_col (%s) does not exist." % version_id_col)

            # check for inheritence
            if hasattr(bases[0], "mapping"):
                cls._base_mapper= bases[0].mapper
                assign_mapper(objectstore.context, cls, cls.table, 
                              inherits=cls._base_mapper, version_id_col=version_id_col_object)
            else:
                assign_mapper(objectstore.context, cls, cls.table, version_id_col=version_id_col_object)
            cls.relations = relations
            ActiveMapperMeta.classes[clsname] = cls
            
            process_relationships(cls)
        
        super(ActiveMapperMeta, cls).__init__(clsname, bases, dict)
Exemplo n.º 16
0
def assign_mapper(class_, *args, **kwargs):
    assignmapper.assign_mapper(objectstore.context, class_, *args, **kwargs)
Exemplo n.º 17
0
    def update_model(self, model):

        meta = model.meta
        ctx = model.ctx

        class User(object):
            def __init__(
                self,
                username,
                uid=None,
                password=None,
                group_uid=None,
            ):
                self.id = id
                self.username = username
                self.password = password
                self.group_uid = group_uid

            def __repr__(self):
                return "User(%(username)s)" % self.__dict__

        class Group(object):
            def __init__(self, name=None):
                self.name = name

            def __repr__(self):
                return "Group(%(name)s)" % self.__dict__

        class Role(object):
            def __init__(self, name=None):
                self.name = name

            def __repr__(self):
                return "Role(%(name)s)" % self.__dict__

        # Tables
        groups_table = Table(
            "groups",
            meta,
            Column("uid", Integer, primary_key=True),
            Column("name", String(255), unique=True, nullable=False),
        )
        roles_table = Table(
            "roles",
            meta,
            Column("uid", Integer, primary_key=True),
            Column("name", String(255), unique=True, nullable=False),
        )
        users_table = Table(
            "users",
            meta,
            Column("uid", Integer, primary_key=True),
            Column("username", String(255), unique=True, nullable=False),
            Column("password", String(255), nullable=False),
            Column("group_uid", Integer, ForeignKey("groups.uid")),
        )
        users_roles_table = Table(  # many:many relation table
            "users_roles",
            meta,
            Column("user_uid", Integer, ForeignKey("users.uid")),
            Column("role_uid", Integer, ForeignKey("roles.uid")),
        )

        groups_mapper = assign_mapper(ctx,
                                      Group,
                                      groups_table,
                                      properties={"users": relation(User)})
        users_mapper = assign_mapper(ctx,
                                     User,
                                     users_table,
                                     properties={
                                         "roles":
                                         relation(Role,
                                                  lazy=True,
                                                  secondary=users_roles_table),
                                         "group":
                                         relation(Group),
                                     })
        roles_mapper = assign_mapper(ctx,
                                     Role,
                                     roles_table,
                                     properties={
                                         "users":
                                         relation(User,
                                                  lazy=True,
                                                  secondary=users_roles_table)
                                     })

        model.User = User
        model.Group = Group
        model.Role = Role
        return model
Exemplo n.º 18
0
    Column("create_time", DateTime, PassiveDefault(func.current_timestamp())),
    Column("update_time",
           DateTime,
           PassiveDefault(func.current_timestamp()),
           onupdate=func.current_timestamp()),
    Column("history_id", Integer, nullable=True),
    Column("user_id", Integer, ForeignKey("galaxy_user.id"), nullable=True),
    Column("message", TrimmedString(1024)))

# With the tables defined we can define the mappers and setup the
# relationships between the model objects.

assign_mapper(context,
              Dataset,
              Dataset.table,
              properties=dict(children=relation(
                  Dataset,
                  cascade="delete",
                  backref=backref("parent", foreignkey=Dataset.table.c.id))))

# assign_mapper( model.Query, model.Query.table,
#     properties=dict( datasets=relation( model.Dataset.mapper, backref="query") ) )

assign_mapper(
    context,
    History,
    History.table,
    properties=dict(datasets=relation(Dataset,
                                      backref="history",
                                      lazy=False,
                                      order_by=asc(Dataset.table.c.hid))))
Exemplo n.º 19
0
        session.flush()
        return pend
        
    @classmethod
    def get_by_email_address(cls, email_address):
        '''
            Returns a user identified by email_address
            
            @param cls: The user class
            @param email_address: Email identifying the user
            @return: User identified by email_address
        '''

        return session.query(cls).get_by(email_address=email_address)

assign_mapper(session.context, RegistrationPendingUser, registration_pending_user_table)

# def newRegistrationPendingUser(user_name,
#                                 email_address,
#                                 display_name,
#                                 password,
#                                 validation_key
#                                 ):
#     pend = RegistrationPendingUser(
#                         user_name = user_name,
#                         email_address = email_address,
#                         display_name = display_name,
#                         password = password,
#                         validation_key = validation_key
#     )
#     session.save(pend)
Exemplo n.º 20
0
            if not self.lang == "None":                
                lexer = get_lexer_by_name(self.lang, stripall=True)
                formatter = HtmlFormatter(linenos=True, cssclass="source")
                self._formatted_content = highlight(self.content, lexer, formatter)
                self.flush()
            else:
                self._formatted_content = cgi.escape(self.content)
                self.flush()
        return self._formatted_content

        
    def _set_formatted_content(self, content):
        self._formatted_content = content
    
    formatted_content = property(_get_formatted_content, _set_formatted_content)
    
    def _get_formatted_lines(self):
        return self.formatted_content
    formatted_lines = property(_get_formatted_lines)
        
    
class Setting(object):
    pass
    
assign_mapper(session.context, Paste, paste_table,
    properties={
        "_formatted_content": paste_table.c.formatted_content
    }
)
assign_mapper(session.context, Setting, setting_table)