예제 #1
0
 def __mapper_args__(cls):
     ret = {'polymorphic_identity': unicode(cls.__name__)}
     if not has_inherited_table(cls) and cls.__polymorphic__:
         ret['polymorphic_on'] = cls.row_type
     elif has_inherited_table(cls) and not cls.__polymorphic__:
         raise Exception('Please specify __polymorphic__=\'single\' or __polymorphic__=\'join\' on base class')
     return ret
예제 #2
0
 def __mapper_args__(cls):
     ret = {'polymorphic_identity': unicode(cls.__name__)}
     if not has_inherited_table(cls) and cls.__polymorphic__:
         ret['polymorphic_on'] = cls.row_type
     elif has_inherited_table(cls) and not cls.__polymorphic__:
         raise Exception('Please specify __polymorphic__=\'single\' or __polymorphic__=\'join\' on base class')
     return ret
예제 #3
0
    def test_has_inherited_table_doesnt_consider_base(self):
        class A(Base):
            __tablename__ = 'a'
            id = Column(Integer, primary_key=True)

        assert not has_inherited_table(A)

        class B(A):
            __tablename__ = 'b'
            id = Column(Integer, ForeignKey('a.id'), primary_key=True)

        assert has_inherited_table(B)
예제 #4
0
    def test_has_inherited_table_doesnt_consider_base(self):
        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

        assert not has_inherited_table(A)

        class B(A):
            __tablename__ = "b"
            id = Column(Integer, ForeignKey("a.id"), primary_key=True)

        assert has_inherited_table(B)
예제 #5
0
    def test_has_inherited_table(self, registry):
        @registry.mapped
        class Foo:
            __tablename__ = "foo"
            id = sa.Column(sa.Integer, primary_key=True)

        @registry.mapped
        class Bar(Foo):
            __tablename__ = "bar"
            id = sa.Column(sa.ForeignKey("foo.id"), primary_key=True)

        with self._expect_warning("has_inherited_table"):
            is_true(legacy_decl.has_inherited_table(Bar))

        with self._expect_warning("has_inherited_table"):
            is_false(legacy_decl.has_inherited_table(Foo))
예제 #6
0
    def __tablename__(cls):
        """Set the tablename to be the lowercase of the class name.

        Reference: http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative.html#controlling-table-inheritance-with-mixins  # noqa
        """
        if has_inherited_table(cls) and BasicBase not in cls.__bases__:
            return None
        return cls.__name__.lower()
예제 #7
0
파일: models.py 프로젝트: thonly/ofxtools
 def id(cls):
     if has_inherited_table(cls):
         return Column(
             Integer, ForeignKey('%s.id' % parent_table,
                                 onupdate='CASCADE', ondelete='CASCADE'),
             primary_key=True)
     else:
         return Column(Integer, primary_key=True)
예제 #8
0
파일: models.py 프로젝트: P-Laf/ofxtools
 def id(cls): 
     if has_inherited_table(cls):
         return Column(
             Integer, ForeignKey('%s.id' % parent_table, 
                                 onupdate='CASCADE', ondelete='CASCADE'),
             primary_key=True)
     else:
         return Column(Integer, primary_key=True)
예제 #9
0
파일: model.py 프로젝트: mor1s99/mor1s
    def __tablename__(cls):
        """
        """

        if has_inherited_table(cls):
            return None

        return cls.__name__.lower()
예제 #10
0
 def my_attr(cls):
     if decl.has_inherited_table(cls):
         id = Column(ForeignKey('a.my_attr'), primary_key=True)
         asserted['b'].add(id)
     else:
         id = Column(Integer, primary_key=True)
         asserted['a'].add(id)
     return id
예제 #11
0
 def uuid(cls):
     parent_tablename = get_parent_tablename_by_bases(cls.__bases__)
     if has_inherited_table(cls) and parent_tablename != '':
         return Column(ForeignKey(parent_tablename + '.uuid'),
                       primary_key=True)
     else:
         return Column(UUID(as_uuid=True),
                       ColumnDefault(uuid.uuid4),
                       primary_key=True)
예제 #12
0
파일: orm.py 프로젝트: gocreating/lation
 def id(cls):
     if has_inherited_table(cls):
         if JoinedTableInheritanceMixin in cls.mro():
             for base in cls.__bases__:
                 if hasattr(base, 'id'):
                     return Column(Integer, ForeignKey(base.id), primary_key=True, autoincrement=False)
         if SingleTableInheritanceMixin in cls.mro():
             return None
     return Column(Integer, primary_key=True)
예제 #13
0
    def __tablename__(cls):
        """Generate a __tablename__ attr for every model that does not have
        inherited tables.

        Ensures table names match the model name without needing to declare it.
        """
        if has_inherited_table(cls):
            return None
        return cls.__name__.lower()
예제 #14
0
 def __mapper_args__(cls):
     if not has_inherited_table(cls):
         ret = {
             'polymorphic_identity': 'default',
             'polymorphic_on': cls.type,
         }
     else:
         ret = {'polymorphic_identity': cls.__name__}
     return ret
예제 #15
0
 def __mapper_args__(cls):
     if not has_inherited_table(cls):
         ret = {
             'polymorphic_identity': 'default',
             'polymorphic_on': cls.type,
             }
     else:
         ret = {'polymorphic_identity': cls.__name__}
     return ret
예제 #16
0
 def __mapper_args__(cls):
     if not has_inherited_table(cls):
         ret = {
             "polymorphic_identity": "default",
             "polymorphic_on": cls.type,
         }
     else:
         ret = {"polymorphic_identity": cls.__name__}
     return ret
예제 #17
0
        def __table_args__(cls):
            if has_inherited_table(cls):
                return tuple()
            else:
                names = list(get_primary_keys(parent_cls).keys())

                return (sa.schema.ForeignKeyConstraint(names, [
                    '%s.%s' % (parent_cls.__tablename__, name)
                    for name in names
                ], **foreign_key_args), )
예제 #18
0
    def __tablename__(cls):
        """Set the tablename as the class name in snake_case.

        Pattern from:

        http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#controlling-table-inheritance-with-mixins
        """
        if has_inherited_table(cls):
            return None
        return inflection.underscore(cls.__name__)
예제 #19
0
def _get_parent_table_class(cls):
    if not has_inherited_table(cls):
        #  Safety against recursion
        return None

    base_classes = [b for b in cls.__bases__ if b.__tablename__]
    if len(base_classes) > 1:
        #  For simplicity at present, only allow join configurations IFF there's only one parent table class
        raise Exception('Can only inherit from one base class with defined table')

    return base_classes[0]
예제 #20
0
def _get_parent_table_class(cls):
    if not has_inherited_table(cls):
        #  Safety against recursion
        return None

    base_classes = [b for b in cls.__bases__ if b.__tablename__]
    if len(base_classes) > 1:
        #  For simplicity at present, only allow join configurations IFF there's only one parent table class
        raise Exception('Can only inherit from one base class with defined table')

    return base_classes[0]
예제 #21
0
파일: orm.py 프로젝트: gocreating/lation
 def __mapper_args__(cls):
     if has_inherited_table(cls):
         if SingleTableInheritanceMixin in cls.mro():
             top_class = cls.__bases__[0]
             if cls.__tablename__ != top_class.__tablename__:
                 raise Exception(f'Model `{cls.__name__}` should not define attribute `__tablename__` due to single heritance')
             polymorphic_identity = cls.__lation__.get('polymorphic_identity')
             if polymorphic_identity == top_class.__lation__.get('polymorphic_identity'):
                 raise Exception(f'Model `{cls.__name__}` should define attribute `__lation__.polymorphic_identity` with non-duplicate value. Duplicate value `{polymorphic_identity}` was detected.')
     return {
         'polymorphic_on': cls.discriminator,
         'polymorphic_identity': cls.__lation__['polymorphic_identity'],
     }
예제 #22
0
def create_permissions(app,
                       created_models,
                       verbosity,
                       db=DEFAULT_DB_ALIAS,
                       **kwargs):
    #print 'create perm for app:', app
    app_models = []
    for k, v in vars(app).items():
        if k not in Base._decl_class_registry:
            continue
        if v not in Base._decl_class_registry.values():
            continue
        if hasattr(
                app,
                '__package__') and app.__package__ + '.models' != v.__module__:
            continue
        app_models.append((k, v))
    if not app_models:
        return

    searched_perms = list()
    searched_codenames = set()
    for k, klass in sorted(app_models, key=lambda x: x[0]):
        if klass.__mapper__.polymorphic_on is not None:
            if has_inherited_table(klass):
                # ignore polymorphic subclasses
                continue
        elif klass.__subclasses__():
            # ignore base if subclass is present
            continue
        for perm in _get_all_permissions(klass._meta):
            if perm.codename in searched_codenames:
                continue
            searched_perms.append(perm)
            searched_codenames.add(perm.codename)

    session = orm.sessionmaker()
    all_perms = session.query(auth_app.Permission).all()
    all_codenames = set(p.codename for p in all_perms)

    perms = [
        perm for perm in searched_perms if perm.codename not in all_codenames
    ]
    session.add_all(perms)
    session.commit()

    if verbosity >= 2:
        for perm in perms:
            print("Adding permission '%s:%s'" % (perm.resource, perm.codename))
예제 #23
0
        def __table_args__(cls):
            if has_inherited_table(cls):
                return tuple()
            else:
                names = list(get_primary_keys(parent_cls).keys())

                return (
                    sa.schema.ForeignKeyConstraint(
                        names,
                        [
                            '%s.%s' % (parent_cls.__tablename__, name)
                            for name in names
                        ],
                        **foreign_key_args
                    ),
                )
예제 #24
0
def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS,
                       **kwargs):
    #print 'create perm for app:', app
    app_models = []
    for k, v in vars(app).items():
        if k not in Base._decl_class_registry:
            continue
        if v not in Base._decl_class_registry.values():
            continue
        if hasattr(app, '__package__') and app.__package__ + '.models' != v.__module__:
            continue
        app_models.append( (k,v) )
    if not app_models:
        return

    searched_perms = list()
    searched_codenames = set()
    for k, klass in sorted(app_models, key=lambda x: x[0]):
        if klass.__mapper__.polymorphic_on is not None:
            if has_inherited_table(klass):
                # ignore polymorphic subclasses
                continue
        elif klass.__subclasses__():
            # ignore base if subclass is present
            continue
        for perm in _get_all_permissions(klass._meta):
            if perm.codename in searched_codenames:
                continue
            searched_perms.append(perm)
            searched_codenames.add(perm.codename)

    session = orm.sessionmaker()    
    all_perms = session.query(auth_app.Permission).all()
    all_codenames = set(p.codename for p in all_perms)

    perms = [
        perm for perm in searched_perms
        if perm.codename not in all_codenames
        ]
    session.add_all(perms)
    session.commit()

    if verbosity >= 2:
        for perm in perms:
            print("Adding permission '%s:%s'" % (perm.resource, perm.codename))
예제 #25
0
    def __tablename__(cls):

        table_name = None

        if has_inherited_table(cls):
            if cls.__polymorphic__ == 'single':
                #  Single implies we are extending an existing table
                #  in which case SQLAlchemy should not be provided a new one
                return None
            elif cls.__polymorphic__ == 'join':
                parent = _get_parent_table_class(cls)
                table_name = "{}{}".format(parent.__name__, cls.__name__)
                # hack to make sure we can redefine id in a subclass
                cls.id = Column(tt.ObjectID(), ForeignKey("{}.id".format(parent.__tablename__)), primary_key=True)
        else:
            table_name = cls.__name__

        return convert_to_underscore(table_name)
예제 #26
0
    def __tablename__(cls):

        table_name = None

        if has_inherited_table(cls):
            if cls.__polymorphic__ == 'single':
                #  Single implies we are extending an existing table
                #  in which case SQLAlchemy should not be provided a new one
                return None
            elif cls.__polymorphic__ == 'join':
                parent = _get_parent_table_class(cls)
                table_name = "{}{}".format(parent.__name__, cls.__name__)
                # hack to make sure we can redefine id in a subclass
                cls.id = Column(tt.ObjectID(), ForeignKey("{}.id".format(parent.__tablename__)), primary_key=True)
        else:
            table_name = cls.__name__

        return convert_to_underscore(table_name)
예제 #27
0
def add_constraints_and_attributes(mapper, class_):
    if has_inherited_table(class_):
        return
    table = class_.__table__

    if class_.key_columns is not None:
        elements = []
        for col_name in class_.key_columns:
            elements.append((getattr(class_, col_name), '='))
        elements.append(('period', '&&'))
        table.append_constraint(ExcludeConstraint(*elements))

        if class_.value_columns is None:
            exclude = {'id', 'period'}
            exclude.update(class_.key_columns)
            class_.value_columns = [
                c.name for c in table.c if c.name not in exclude
            ]
    table.append_constraint(CheckConstraint("period != 'empty'::tsrange"))
예제 #28
0
파일: base.py 프로젝트: cjw296/ForJames
 def __tablename__(self):
     if (has_inherited_table(self) and Common not in self.__bases__):
         return None
     return self.__name__.lower()
예제 #29
0
파일: db.py 프로젝트: emorrp1/hike-tracker
	def __mapper_args__(cls):
		if has_inherited_table(cls):
			return {'polymorphic_identity': cls.__name__.lower()}
		return {'polymorphic_on': cls.row_type}
예제 #30
0
 def __table_args__(cls):
     if has_inherited_table(cls):
         return None
     else:
         return (UniqueConstraint(*cls.pks), )
예제 #31
0
 def __mapper_args__(cls):
     if has_inherited_table(cls):
         return {'polymorphic_identity': cls.__name__.lower()}
     else:
         return {'polymorphic_on': cls.subclass}
예제 #32
0
 def __tablename__(cls):
     if decl.has_inherited_table(cls) and TableNameMixin \
         not in cls.__bases__:
         return None
     return cls.__name__.lower()
예제 #33
0
 def __tablename__(cls):
     if decl.has_inherited_table(cls) and TableNameMixin \
             not in cls.__bases__:
         return None
     return cls.__name__.lower()
예제 #34
0
 def receive_before_flush(sess, _flush_context, _instances):
     for x in sess.dirty:
         if has_inherited_table(x.__class__) or is_parent_table(x.__class__):
             x.updated_at = datetime.datetime.now()
예제 #35
0
파일: __init__.py 프로젝트: gabrielx52/baph
def create_permissions(app,
                       created_models,
                       verbosity,
                       db=DEFAULT_DB_ALIAS,
                       **kwargs):
    app_models = []
    for k, v in vars(app).items():
        if k not in orm.Base._decl_class_registry:
            continue
        if v not in orm.Base._decl_class_registry.values():
            continue
        if hasattr(
                app,
                '__package__') and app.__package__ + '.models' != v.__module__:
            continue
        app_models.append((k, v))
    if not app_models:
        return

    try:
        Permission = getattr(auth_app, 'Permission')
    except:
        return

    searched_perms = list()
    ctypes = set()
    searched_codenames = set()
    for k, klass in sorted(app_models, key=lambda x: x[0]):
        if klass.__mapper__.polymorphic_on is not None:
            if has_inherited_table(klass):
                # ignore polymorphic subclasses
                continue
        elif klass.__subclasses__():
            # ignore base if subclass is present
            continue
        if not klass._meta.permission_resources:
            # no resource types
            continue

        ctypes.update(klass._meta.permission_resources)
        for perm in _get_all_permissions(klass._meta):
            if perm['codename'] in searched_codenames:
                continue
            searched_perms.append(perm)
            searched_codenames.add(perm['codename'])

    if not ctypes:
        return
    #connection = connections[db]
    session = orm.sessionmaker()

    all_perms = session.query(Permission.codename) \
                       .filter(Permission.resource.in_(ctypes)) \
                       .all()
    all_perms = set([perm[0] for perm in all_perms])

    perms = [
        perm for perm in searched_perms if perm['codename'] not in all_perms
    ]

    session.execute(Permission.__table__.insert(), perms)
    session.flush()

    if verbosity >= 2:
        for perm in perms:
            print("Adding permission '%s:%s'" %
                  (perm['resource'], perm['codename']))
예제 #36
0
 def __table_args__(cls):
     if has_inherited_table(cls):
         return (UniqueConstraint(*cls.pks), {'schema': 'ofx'})
     else:
         return {'schema': 'ofx'}
예제 #37
0
파일: base.py 프로젝트: cjw296/ForJames
 def __tablename__(self):
     if (has_inherited_table(self) and
         Common not in self.__bases__):
         return None
     return self.__name__.lower()
예제 #38
0
파일: models.py 프로젝트: P-Laf/ofxtools
 def __mapper_args__(cls):
     if has_inherited_table(cls):
         return {'polymorphic_identity': cls.__name__.lower()}
     else:
         return {'polymorphic_on': cls.subclass}
예제 #39
0
 def __tablename__(cls):
     if decl.has_inherited_table(cls):
         return None
     return cls.__name__.lower()
예제 #40
0
파일: models.py 프로젝트: P-Laf/ofxtools
 def __table_args__(cls):
     if has_inherited_table(cls):
         return (UniqueConstraint(*cls.pks),)
     else:
         return None
예제 #41
0
파일: __init__.py 프로젝트: devhub/baph
def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS,
                       **kwargs):
    app_models = []
    for k, v in vars(app).items():
        if k not in orm.Base._decl_class_registry:
            continue
        if v not in orm.Base._decl_class_registry.values():
            continue
        if hasattr(app, '__package__') and app.__package__ + '.models' != v.__module__:
            continue
        app_models.append( (k,v) )
    if not app_models:
        return

    try:
        Permission = getattr(auth_app, 'Permission')
    except:
        return

    searched_perms = list()
    ctypes = set()
    searched_codenames = set()
    for k, klass in sorted(app_models, key=lambda x: x[0]):
        if klass.__mapper__.polymorphic_on is not None:
            if has_inherited_table(klass):
                # ignore polymorphic subclasses
                continue
        elif klass.__subclasses__():
            # ignore base if subclass is present
            continue
        if not klass._meta.permission_resources:
            # no resource types
            continue

        ctypes.update(klass._meta.permission_resources)
        for perm in _get_all_permissions(klass._meta):
            if perm['codename'] in searched_codenames:
                continue
            searched_perms.append(perm)
            searched_codenames.add(perm['codename'])

    if not ctypes:
        return
    #connection = connections[db]
    session = orm.sessionmaker()

    all_perms = session.query(Permission.codename) \
                       .filter(Permission.resource.in_(ctypes)) \
                       .all()
    all_perms = set([perm[0] for perm in all_perms])

    perms = [
        perm for perm in searched_perms
        if perm['codename'] not in all_perms
        ]

    session.execute(Permission.__table__.insert(), perms)
    session.flush()

    if verbosity >= 2:
        for perm in perms:
            print("Adding permission '%s:%s'" % (perm['resource'],
                                                 perm['codename']))
예제 #42
0
 def __tablename__(cls):
     if decl.has_inherited_table(cls):
         return None
     return cls.__name__.lower()