Пример #1
0
    class GroupUser(orb.Table):
        id = orb.IdColumn()
        user = orb.ReferenceColumn(reference='User')
        group = orb.ReferenceColumn(reference='Group')

        byUserAndGroup = orb.Index(('user', 'group'), flags={'Unique'})
        byUser = orb.Index(('user', ))
Пример #2
0
class UserSchema(orb.ModelMixin):
    id = orb.IdColumn()
    username = orb.StringColumn(flags={'Required'})
    password = orb.StringColumn(flags={'Required'})
    first_name = orb.StringColumn()
    last_name = orb.StringColumn()

    addresses = orb.ReverseLookup(from_column='Address.user')
    preferences = orb.ReverseLookup(from_column='Preference.user',
                                    flags={'Unique'})
    groups = orb.Pipe(through_path='GroupUser.user.group')

    byUsername = orb.Index(columns=['username'], flags={'Unique'})
    byName = orb.Index(columns=['first_name', 'last_name'])
Пример #3
0
class Group(orb.Table):
    id = orb.IdColumn()
    name = orb.StringColumn()

    users = orb.Pipe(through_path='GroupUser.group.user')

    byName = orb.Index(columns=['name'], flags={'Unique'})
Пример #4
0
    class Group(orb.Table):
        __resource__ = True

        id = orb.IdColumn()
        name = orb.StringColumn(flags={'Required'})

        users = orb.Pipe(through_path='GroupUser.group.user')

        byName = orb.Index(columns=['name'], flags={'Unique'})
Пример #5
0
    class Group(orb.Table):
        __resource__ = True

        id = orb.IdColumn()
        name = orb.StringColumn(flags={'Unique'})
        owner = orb.ReferenceColumn(reference='User')

        users = orb.Pipe(through_path='GroupUser.group.user')
        groupUsers = orb.ReverseLookup(from_column='GroupUser.group')

        byName = orb.Index(columns=['name'], flags={'Unique'})
Пример #6
0
def test_my_statement_create_index(orb, GroupUser, my_sql):
    index = orb.Index(name='byGroupAndUser', columns=[orb.ReferenceColumn(name='group'), orb.ReferenceColumn('user')])
    index.setSchema(GroupUser.schema())
    st = my_sql.statement('CREATE INDEX')
    assert st is not None

    statement, data = st(index)
    assert 'CREATE INDEX' in statement

    statement, data = st(index, checkFirst=True)
    assert 'DO $$' in statement
Пример #7
0
    class User(orb.Table):
        __resource__ = True

        id = orb.IdColumn()
        username = orb.StringColumn(flags={'Required'})
        password = orb.StringColumn(flags={'Required', 'Private'})

        groups = orb.Pipe(through_path='GroupUser.user.group')
        addresses = orb.ReverseLookup(from_column='Address.user')

        byUsername = orb.Index(columns=['username'], flags={'Unique'})

        @classmethod
        @action(method='get')
        def run(cls, request):
            return 'user run model'

        @action(method='get', name='run')
        def run_record(self, request):
            return 'user run record'

        @classmethod
        @action(method='post', name='exec')
        def run_post_model(self, request):
            return 'user exec post model'

        @action(method='delete', name='run')
        def run_delete(self, request):
            return 'user run delete record'

        @action(method='patch', name='run')
        def run_patch(self, request):
            return 'user run patch record'

        @action(method='put', name='run')
        def run_put(self, request):
            return 'user run put record'
Пример #8
0
    class User(orb.Table):
        __resouce__ = True

        id = orb.IdColumn()
        username = orb.StringColumn(flags={'Unique'})
        password = orb.PasswordColumn()
        token = orb.TokenColumn()

        groups = orb.Pipe(through='GroupUser', from_='user', to='group')
        userGroups = orb.ReverseLookup(from_column='GroupUser.user')

        @orb.virtual(orb.BooleanColumn)
        def hasGroups(self, **context):
            return len(self.get('groups')) != 0

        @orb.virtual(orb.Collector, model='Group')
        def myGroups(self, **context):
            group_ids = GroupUser.select(
                where=orb.Query('user') == self).values('group')
            context['where'] = orb.Query('id').in_(group_ids) & context.get(
                'where')
            return Group.select(**context)

        byUsername = orb.Index(columns=['username'], flags={'Unique'})
Пример #9
0
    def createModel(mcs, name, bases, attrs, db_data):
        """
        Create a new table model.
        """
        # implement a new override class
        if db_data['__db_implements__']:
            new_base = orb.system.model(db_data['__db_implements__'],
                                        autoGenerate=True)
            bases = tuple([
                new_base if issubclass(base, orb.Table) else base
                for base in bases
            ])
            schema = new_base.schema()
        else:
            schema = db_data['__db_schema__']

        new_model = super(MetaTable, mcs).__new__(mcs, name, bases, attrs)

        if schema:
            db_data['__db_name__'] = schema.name()
            db_data['__db_dbname__'] = schema.dbname()

            try:
                schema.setAutoLocalize(db_data['__db_autolocalize__'])
            except KeyError:
                pass
            try:
                schema.setAutoPrimary(db_data['__db_autoprimary__'])
            except KeyError:
                pass

            if db_data['__db_columns__']:
                columns = schema.columns(
                    recurse=False) + db_data['__db_columns__']
                schema.setColumns(columns)
            if db_data['__db_indexes__']:
                indexes = schema.indexes() + db_data['__db_indexes__']
                schema.setIndexes(indexes)
            if db_data['__db_pipes__']:
                pipes = schema.pipes() + db_data['__db_pipes__']
                schema.setPipes(pipes)
            if db_data['__db_contexts__']:
                contexts = dict(schema.contexts())
                contexts.update(db_data['__db_contexts__'])
                schema.setContexts(contexts)
            if db_data['__db_views__']:
                for name, view in db_data['__db_views__'].items():
                    schema.setView(name, view)
        else:
            # create the table schema
            schema = orb.TableSchema()
            schema.setDatabase(db_data['__db__'])
            schema.setAutoPrimary(db_data.get('__db_autoprimary__', True))
            schema.setAutoLocalize(db_data.get('__db_autolocalize__', False))
            schema.setName(db_data['__db_name__'] or name)
            schema.setGroupName(db_data['__db_group__'])
            schema.setDbName(db_data['__db_dbname__'])
            schema.setAbstract(db_data['__db_abstract__'])
            schema.setColumns(db_data['__db_columns__'])
            schema.setIndexes(db_data['__db_indexes__'])
            schema.setPipes(db_data['__db_pipes__'])
            schema.setInherits(db_data['__db_inherits__'])
            schema.setArchived(db_data['__db_archived__'])
            schema.setContexts(db_data['__db_contexts__'])

            for name, view in db_data['__db_views__'].items():
                schema.setView(name, view)

            schema.setModel(new_model)

            orb.system.registerSchema(schema)

        db_data['__db_schema__'] = schema

        # add the db values to the class
        for key, value in db_data.items():
            setattr(new_model, key, value)

        # create class methods for the index instances
        for index in schema.indexes():
            iname = index.name()
            if not hasattr(new_model, iname):
                setattr(new_model, index.name(), classmethod(index))

        # create instance methods for the pipe instances
        for pipe in schema.pipes():
            pname = pipe.name()
            if not hasattr(new_model, pname):
                pipemethod = instancemethod(pipe, None, new_model)
                setattr(new_model, pname, pipemethod)

        # pylint: disable-msg=W0212
        columns = schema.columns(recurse=False)
        for column in columns:
            colname = column.name()

            # create getter method
            gname = column.getterName()
            if gname and not hasattr(new_model, gname):
                gmethod = gettermethod(columnName=colname,
                                       translatable=column.isTranslatable(),
                                       inflatable=column.isReference(),
                                       returns=column.returnType(),
                                       __name__=gname)

                getter = instancemethod(gmethod, None, new_model)
                setattr(new_model, gname, getter)

            # create setter method
            sname = column.setterName()
            if sname and not (column.isReadOnly()
                              or hasattr(new_model, sname)):
                smethod = settermethod(columnName=colname,
                                       translatable=column.isTranslatable(),
                                       inflatable=column.isReference(),
                                       returns=column.returnType(),
                                       __name__=sname)
                setter = instancemethod(smethod, None, new_model)
                setattr(new_model, sname, setter)

            # create an index if necessary
            iname = column.indexName()
            if column.indexed() and iname and not hasattr(new_model, iname):
                index = orb.Index(iname, [column.name()],
                                  unique=column.unique())
                index.setCached(column.indexCached())
                index.setCacheTimeout(column.indexCacheTimeout())
                index.__name__ = iname
                imethod = classmethod(index)
                setattr(new_model, iname, imethod)

            # create a reverse lookup
            if column.isReversed() and column.schema().name(
            ) == db_data['__db_name__']:
                rev_name = column.reversedName()
                rev_cached = column.reversedCached()
                ref_name = column.reference()

                try:
                    ref_model = column.referenceModel()
                except errors.TableNotFound:
                    ref_model = None

                rev_cacheTimeout = column.reversedCacheTimeout()

                # create the lookup method
                lookup = reverselookupmethod(columnName=column.name(),
                                             reference=db_data['__db_name__'],
                                             unique=column.unique(),
                                             cached=rev_cached,
                                             cacheTimeout=rev_cacheTimeout,
                                             __name__=rev_name)

                while ref_model and ref_model.__module__ != 'orb.schema.dynamic' and \
                        ref_model.__bases__ and ref_model.__bases__[0] == orb.Table:
                    ref_model = ref_model.__bases__[0]

                # assign to an existing model
                # ensure we're assigning it to the proper base module
                if ref_model:
                    ilookup = instancemethod(lookup, None, ref_model)
                    setattr(ref_model, rev_name, ilookup)
                else:
                    TEMP_REVERSE_LOOKUPS.setdefault(ref_name, [])
                    TEMP_REVERSE_LOOKUPS[ref_name].append((rev_name, lookup))

        # assign any cached reverse lookups to this model
        lookups = TEMP_REVERSE_LOOKUPS.pop(db_data['__db_name__'], [])
        for rev_name, lookup in lookups:
            ilookup = instancemethod(lookup, None, new_model)
            setattr(new_model, rev_name, ilookup)

        if db_data['__db_implements__']:
            orb.system.setModel(db_data['__db_implements__'], new_model)

        return new_model
Пример #10
0
    def createModel(mcs, name, bases, attrs, db_data):
        """
        Create a new view model.
        """
        new_model = super(MetaView, mcs).__new__(mcs, name, bases, attrs)
        schema = db_data['__db_schema__']

        if schema:
            db_data['__db_name__'] = schema.name()
            db_data['__db_viewname__'] = schema.viewName()

            if db_data['__db_columns__']:
                columns = schema.columns(
                    recurse=False) + db_data['__db_columns__']
                schema.setColumns(columns)
            if db_data['__db_indexes__']:
                indexes = schema.indexes() + db_data['__db_indexes__']
                schema.setIndexes(indexes)
            if db_data['__db_pipes__']:
                pipes = schema.pipes() + db_data['__db_pipes__']
                schema.setPipes(pipes)
            if db_data['__db_contexts__']:
                contexts = dict(schema.contexts())
                contexts.update(db_data['__db_contexts__'])
                schema.setContexts(contexts)
            if db_data['__db_views__']:
                for name, view in db_data['__db_views__'].items():
                    schema.setView(name, view)
        else:
            # create the view schema
            schema = orb.ViewSchema()
            schema.setDatabase(db_data['__db__'])
            schema.setAutoPrimary(False)
            schema.setName(db_data['__db_name__'] or name)
            schema.setGroupName(db_data['__db_group__'])
            schema.setDbName(db_data['__db_viewname__'])
            schema.setAbstract(db_data['__db_abstract__'])
            schema.setColumns(db_data['__db_columns__'])
            schema.setIndexes(db_data['__db_indexes__'])
            schema.setPipes(db_data['__db_pipes__'])
            schema.setInherits(db_data['__db_inherits__'])
            schema.setArchived(db_data['__db_archived__'])
            schema.setContexts(db_data['__db_contexts__'])
            schema.setStatic(db_data['__db_static__'])
            schema.setCacheEnabled(db_data['__db_cache__'].get(
                'enabled', db_data['__db_cache__'].get('preload')))
            schema.setPreloadCache(db_data['__db_cache__'].get('preload'))
            schema.setCacheTimeout(db_data['__db_cache__'].get('timeout', 0))

            for name, view in db_data['__db_views__'].items():
                schema.setView(name, view)

            schema.setModel(new_model)

            orb.system.registerSchema(schema)

        db_data['__db_schema__'] = schema

        # add the db values to the class
        for key, value in db_data.items():
            setattr(new_model, key, value)

        # create class methods for the index instances
        for index in schema.indexes():
            iname = index.name()
            if not hasattr(new_model, iname):
                setattr(new_model, index.name(), classmethod(index))

        # create instance methods for the pipe instances
        for pipe in schema.pipes():
            pname = pipe.name()
            if not hasattr(new_model, pname):
                pipemethod = instancemethod(pipe, None, new_model)
                setattr(new_model, pname, pipemethod)

        # pylint: disable-msg=W0212
        columns = schema.columns(recurse=False)
        for column in columns:
            colname = column.name()

            # create getter method
            gname = column.getterName()
            if gname and not hasattr(new_model, gname):
                gmethod = gettermethod(columnName=colname,
                                       translatable=column.isTranslatable(),
                                       inflatable=column.isReference(),
                                       returns=column.returnType(),
                                       __name__=gname)

                getter = instancemethod(gmethod, None, new_model)
                setattr(new_model, gname, getter)

            # create setter method
            sname = column.setterName()
            if sname and not (column.isReadOnly()
                              or hasattr(new_model, sname)):
                smethod = settermethod(columnName=colname,
                                       translatable=column.isTranslatable(),
                                       inflatable=column.isReference(),
                                       returns=column.returnType(),
                                       __name__=sname)
                setter = instancemethod(smethod, None, new_model)
                setattr(new_model, sname, setter)

            # create an index if necessary
            iname = column.indexName()
            if column.indexed() and iname and not hasattr(new_model, iname):
                index = orb.Index(iname, [column.name()],
                                  unique=column.unique())
                index.setCached(column.indexCached())
                index.setCacheTimeout(column.indexCacheTimeout())
                index.__name__ = iname
                imethod = classmethod(index)
                setattr(new_model, iname, imethod)

            # create a reverse lookup
            if column.isReversed() and column.schema().name(
            ) == db_data['__db_name__']:
                rev_name = column.reversedName()
                rev_cached = column.reversedCached()
                ref_name = column.reference()
                ref_model = column.referenceModel()
                rev_cacheTimeout = column.reversedCacheTimeout()

                # create the lookup method
                lookup = reverselookupmethod(columnName=column.name(),
                                             reference=db_data['__db_name__'],
                                             unique=column.unique(),
                                             cached=rev_cached,
                                             cacheTimeout=rev_cacheTimeout,
                                             __name__=rev_name)

                # ensure we're assigning it to the proper base module
                while ref_model and ref_model.__module__ != 'orb.schema.dynamic' and \
                        ref_model.__bases__ and ref_model.__bases__[0] == orb.View:
                    ref_model = ref_model.__bases__[0]

                # assign to an existing model
                if ref_model:
                    ilookup = instancemethod(lookup, None, ref_model)
                    setattr(ref_model, rev_name, ilookup)
                else:
                    TEMP_REVERSE_LOOKUPS.setdefault(ref_name, [])
                    TEMP_REVERSE_LOOKUPS[ref_name].append((rev_name, lookup))

        # assign any cached reverse lookups to this model
        lookups = TEMP_REVERSE_LOOKUPS.pop(db_data['__db_name__'], [])
        for rev_name, lookup in lookups:
            ilookup = instancemethod(lookup, None, new_model)
            setattr(new_model, rev_name, ilookup)

        return new_model