Python sqlalchemy.orm.attributes.InstrumentedAttribute() Examples

The following are 12 code examples of sqlalchemy.orm.attributes.InstrumentedAttribute(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.orm.attributes , or try the search function .
Example #1
Source File: eagerload.py    From sqlalchemy-mixins with MIT License 6 votes vote down vote up
def with_joined(cls, *paths):
        """
        Eagerload for simple cases where we need to just
         joined load some relations
        In strings syntax, you can split relations with dot 
         due to this SQLAlchemy feature: https://goo.gl/yM2DLX
         
        :type paths: *List[str] | *List[InstrumentedAttribute]

        Example 1:
            Comment.with_joined('user', 'post', 'post.comments').first()

        Example 2:
            Comment.with_joined(Comment.user, Comment.post).first()
        """
        options = [joinedload(path) for path in paths]
        return cls.query.options(*options) 
Example #2
Source File: eagerload.py    From sqlalchemy-mixins with MIT License 6 votes vote down vote up
def with_subquery(cls, *paths):
        """
        Eagerload for simple cases where we need to just
         joined load some relations
        In strings syntax, you can split relations with dot 
         (it's SQLAlchemy feature)

        :type paths: *List[str] | *List[InstrumentedAttribute]

        Example 1:
            User.with_subquery('posts', 'posts.comments').all()

        Example 2:
            User.with_subquery(User.posts, User.comments).all()
        """
        options = [subqueryload(path) for path in paths]
        return cls.query.options(*options) 
Example #3
Source File: utils.py    From sqlalchemy-json-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_descriptor_columns(model, descriptor):
    if isinstance(descriptor, InstrumentedAttribute):
        return descriptor.property.columns
    elif isinstance(descriptor, sa.orm.ColumnProperty):
        return descriptor.columns
    elif isinstance(descriptor, sa.Column):
        return [descriptor]
    elif isinstance(descriptor, sa.sql.expression.ClauseElement):
        return []
    elif isinstance(descriptor, sa.ext.hybrid.hybrid_property):
        expr = descriptor.expr(model)
        try:
            return get_descriptor_columns(model, expr)
        except TypeError:
            return []
    elif (
        isinstance(descriptor, QueryableAttribute) and
        hasattr(descriptor, 'original_property')
    ):
        return get_descriptor_columns(model, descriptor.property)
    raise TypeError(
        'Given descriptor is not of type InstrumentedAttribute, '
        'ColumnProperty or Column.'
    ) 
Example #4
Source File: forms.py    From marvin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _loadParams(self, newclass):
        ''' Loads all parameters from wtforms into a dictionary with
            key, value = {'parameter_name': 'parent WTForm name'}.
            Ignores hidden attributes and the Meta class
        '''

        model = newclass.Meta.model
        schema = model.__table__.schema
        tablename = model.__table__.name

        mapper = sa_inspect(model)
        for key, item in mapper.all_orm_descriptors.items():
            if isinstance(item, (hybrid_property, hybrid_method)):
                key = key
            elif isinstance(item, InstrumentedAttribute):
                key = item.key
            else:
                continue

            lookupKeyName = schema + '.' + tablename + '.' + key
            self._param_form_lookup[lookupKeyName] = newclass
            self._paramtree[newclass.Meta.model.__name__][key] 
Example #5
Source File: eagerload.py    From sqlalchemy-mixins with MIT License 5 votes vote down vote up
def _flatten_schema(schema):
    """
    :type schema: dict
    """
    def _flatten(schema, parent_path, result):
        """
        :type schema: dict
        """
        for path, value in schema.items():
            # for supporting schemas like Product.user: {...},
            # we transform, say, Product.user to 'user' string
            if isinstance(path, InstrumentedAttribute):
                path = path.key

            if isinstance(value, tuple):
                join_method, inner_schema = value[0], value[1]
            elif isinstance(value, dict):
                join_method, inner_schema = JOINED, value
            else:
                join_method, inner_schema = value, None

            full_path = parent_path + '.' + path if parent_path else path
            result[full_path] = join_method

            if inner_schema:
                _flatten(inner_schema, full_path, result)

    result = {}
    _flatten(schema, '', result)
    return result 
Example #6
Source File: query_builder.py    From sqlalchemy-json-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_relationship_descriptor(self, descriptor):
        return (
            isinstance(descriptor, InstrumentedAttribute) and
            isinstance(descriptor.property, sa.orm.RelationshipProperty)
        ) 
Example #7
Source File: arg_checker.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def _are_valid_query_entities(self, func_name, entities):
        from sqlalchemy.orm.attributes import InstrumentedAttribute
        for e in entities:
            if not isinstance(e, InstrumentedAttribute):
                raise RQInvalidArgument(
                    _("function {}: invalid {} argument, should be entity like "
                      "Fundamentals.balance_sheet.total_equity, got {} (type: {})").format(
                        func_name, self.arg_name, e, type(e)
                    )) 
Example #8
Source File: arg_checker.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def _are_valid_query_entities(self, func_name, entities):
        from sqlalchemy.orm.attributes import InstrumentedAttribute
        for e in entities:
            if not isinstance(e, InstrumentedAttribute):
                raise RQInvalidArgument(
                    _(u"function {}: invalid {} argument, should be entity like "
                      u"Fundamentals.balance_sheet.total_equity, got {} (type: {})").format(
                        func_name, self.arg_name, e, type(e)
                    )) 
Example #9
Source File: hour_slice.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def filter_timestamp_column_by_day_of_week(
        self, ts_col: InstrumentedAttribute
    ) -> ColumnElement:
        """
        Returns an expression equivalent to TRUE (because no additional
        filtering is needed to limit the day of the week).

        Parameters
        ----------
        ts_col : sqlalchemy.orm.attributes.InstrumentedAttribute
            The timestamp column to filter. Note that this input argument
            is ignored for the DayPeriod class because it requires no
            additional filtering to limit the day of the week.
        """
        return true() 
Example #10
Source File: hour_slice.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def filter_timestamp_column_by_day_of_week(self, ts_col: InstrumentedAttribute):
        """
        Returns a sql expression which filters the timestamp column
        """
        return func.extract("isodow", ts_col) == self.weekday_idx 
Example #11
Source File: arg_checker.py    From Rqalpha-myquant-learning with Apache License 2.0 5 votes vote down vote up
def _are_valid_query_entities(self, func_name, entities):
        from sqlalchemy.orm.attributes import InstrumentedAttribute
        for e in entities:
            if not isinstance(e, InstrumentedAttribute):
                raise RQInvalidArgument(
                    _(u"function {}: invalid {} argument, should be entity like "
                      u"Fundamentals.balance_sheet.total_equity, got {} (type: {})").format(
                        func_name, self.arg_name, e, type(e)
                    )) 
Example #12
Source File: search.py    From planespotter with MIT License 4 votes vote down vote up
def _sub_operator(model, argument, fieldname):
    """Recursively calls :func:`QueryBuilder._create_operation` when argument
    is a dictionary of the form specified in :ref:`search`.

    This function is for use with the ``has`` and ``any`` search operations.

    """
    if isinstance(model, InstrumentedAttribute):
        submodel = model.property.mapper.class_
    elif isinstance(model, AssociationProxy):
        submodel = get_related_association_proxy_model(model)
    else:  # TODO what to do here?
        pass
    if isinstance(argument, dict):
        fieldname = argument['name']
        operator = argument['op']
        argument = argument.get('val')
        relation = None
        if '__' in fieldname:
            fieldname, relation = fieldname.split('__')
        return QueryBuilder._create_operation(submodel, fieldname, operator,
                                              argument, relation)
    # Support legacy has/any with implicit eq operator
    return getattr(submodel, fieldname) == argument


#: The mapping from operator name (as accepted by the search method) to a
#: function which returns the SQLAlchemy expression corresponding to that
#: operator.
#:
#: Each of these functions accepts either one, two, or three arguments. The
#: first argument is the field object on which to apply the operator. The
#: second argument, where it exists, is either the second argument to the
#: operator or a dictionary as described below. The third argument, where it
#: exists, is the name of the field.
#:
#: For functions that accept three arguments, the second argument may be a
#: dictionary containing ``'name'``, ``'op'``, and ``'val'`` mappings so that
#: :func:`QueryBuilder._create_operation` may be applied recursively. For more
#: information and examples, see :ref:`search`.
#:
#: Some operations have multiple names. For example, the equality operation can
#: be described by the strings ``'=='``, ``'eq'``, ``'equals'``, etc.