Пример #1
0
class Identifiable(object):

  """A model with an ``id`` property that is the primary key."""
  id = db.Column(db.Integer, primary_key=True)  # noqa

  # REST properties
  _api_attrs = reflection.ApiAttributes(
      reflection.Attribute('id', create=False, update=False),
      reflection.Attribute('type', create=False, update=False),
  )

  _inflector = ModelInflectorDescriptor()

  @builder.simple_property
  def type(self):
    return self.__class__.__name__

  @classmethod
  def eager_query(cls, **kwargs):  # pylint: disable=unused-argument
    """Sub-query for eager loading."""

    mapper_class = cls._sa_class_manager.mapper.base_mapper.class_
    return db.session.query(cls).options(
        db.Load(mapper_class).undefer_group(
            mapper_class.__name__ + '_complete'),
    )

  @classmethod
  def eager_inclusions(cls, query, include_links):
    """Load related items listed in include_links eagerly."""
    options = []
    for include_link in include_links:
      inclusion_class = getattr(cls, include_link).property.mapper.class_
      options.append(
          orm.subqueryload(include_link)
          .undefer_group(inclusion_class.__name__ + '_complete'))
    return query.options(*options)

  @declared_attr
  def __table_args__(cls):  # pylint: disable=no-self-argument
    extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args')
    table_args = []
    table_dict = {}
    for table_arg in extra_table_args:
      if callable(table_arg):
        table_arg = table_arg()
      if isinstance(table_arg, (list, tuple, set)):
        if isinstance(table_arg[-1], (dict,)):
          table_dict.update(table_arg[-1])
          table_args.extend(table_arg[:-1])
        else:
          table_args.extend(table_arg)
      elif isinstance(table_arg, (dict,)):
        table_dict.update(table_arg)
      else:
        table_args.append(table_arg)
    if table_dict:
      table_args.append(table_dict)
    return tuple(table_args,)
Пример #2
0
class Identifiable(object):

  """A model with an ``id`` property that is the primary key."""
  id = db.Column(db.Integer, primary_key=True)  # noqa

  # REST properties
  _publish_attrs = ['id', 'type']
  _update_attrs = []

  _inflector = ModelInflectorDescriptor()

  @computed_property
  def type(self):
    return self.__class__.__name__

  @classmethod
  def eager_query(cls):
    mapper_class = cls._sa_class_manager.mapper.base_mapper.class_
    return db.session.query(cls).options(
        db.Load(mapper_class).undefer_group(
            mapper_class.__name__ + '_complete'),
    )

  @classmethod
  def eager_inclusions(cls, query, include_links):
    """Load related items listed in include_links eagerly."""
    options = []
    for include_link in include_links:
      inclusion_class = getattr(cls, include_link).property.mapper.class_
      options.append(
          orm.subqueryload(include_link)
          .undefer_group(inclusion_class.__name__ + '_complete'))
    return query.options(*options)

  @declared_attr
  def __table_args__(cls):
    extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args')
    table_args = []
    table_dict = {}
    for table_arg in extra_table_args:
      if callable(table_arg):
        table_arg = table_arg()
      if isinstance(table_arg, (list, tuple, set)):
        if isinstance(table_arg[-1], (dict,)):
          table_dict.update(table_arg[-1])
          table_args.extend(table_arg[:-1])
        else:
          table_args.extend(table_arg)
      elif isinstance(table_arg, (dict,)):
        table_dict.update(table_arg)
      else:
        table_args.append(table_arg)
    if len(table_dict) > 0:
      table_args.append(table_dict)
    return tuple(table_args,)
Пример #3
0
class Base(object):
  """Base Model for data platform models."""
  created_at = db.Column(db.DateTime, nullable=False)
  updated_at = db.Column(db.DateTime, nullable=False)

  # Note for created_by_id and updated_by_id
  # This field is nullable because we do not have front-end interface for
  # creating and modifying attributes type entries
  @declared_attr
  def created_by_id(cls):  # pylint: disable=no-self-argument
    return db.Column(db.Integer, db.ForeignKey('people.id'), nullable=True)

  @declared_attr
  def updated_by_id(cls):  # pylint: disable=no-self-argument
    """Id of user who did the last modification of the object."""
    return db.Column(db.Integer, db.ForeignKey('people.id'), nullable=True)

  @declared_attr
  def modified_by(cls):  # pylint: disable=no-self-argument
    """Relationship to user referenced by updated_by_id."""
    return db.relationship(
        'Person',
        primaryjoin='{}.updated_by_id == Person.id'.format(cls.__name__),
        foreign_keys='{}.updated_by_id'.format(cls.__name__),
        uselist=False,
    )

  @declared_attr
  def created_by(cls):  # pylint: disable=no-self-argument
    """Relationship to user referenced by updated_by_id."""
    return db.relationship(
        'Person',
        primaryjoin='{}.created_by_id == Person.id'.format(cls.__name__),
        foreign_keys='{}.created_by_id'.format(cls.__name__),
        uselist=False,
    )

  _inflector = ModelInflectorDescriptor()
Пример #4
0
class Identifiable(object):
    """A model with an ``id`` property that is the primary key."""
    id = db.Column(db.Integer, primary_key=True)  # noqa

    # REST properties
    _publish_attrs = ['id', 'type']
    _update_attrs = []
    _stub_attrs = ['id', 'type']

    _inflector = ModelInflectorDescriptor()

    @computed_property
    def type(self):
        return self.__class__.__name__

    @classmethod
    def eager_query(cls):
        mapper_class = cls._sa_class_manager.mapper.base_mapper.class_
        return db.session.query(cls).options(
            db.Load(mapper_class).undefer_group(mapper_class.__name__ +
                                                '_complete'), )

    @classmethod
    def eager_inclusions(cls, query, include_links):
        options = []
        for include_link in include_links:
            inclusion_class = getattr(cls, include_link).property.mapper.class_
            options.append(
                orm.subqueryload(include_link).undefer_group(
                    inclusion_class.__name__ + '_complete'))
        return query.options(*options)

    @declared_attr
    def __table_args__(cls):
        extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args')
        table_args = []
        table_dict = {}
        for table_arg in extra_table_args:
            if callable(table_arg):
                table_arg = table_arg()
            if isinstance(table_arg, (list, tuple, set)):
                if isinstance(table_arg[-1], (dict, )):
                    table_dict.update(table_arg[-1])
                    table_args.extend(table_arg[:-1])
                else:
                    table_args.extend(table_arg)
            elif isinstance(table_arg, (dict, )):
                table_dict.update(table_arg)
            else:
                table_args.append(table_arg)
        if len(table_dict) > 0:
            table_args.append(table_dict)
        return tuple(table_args, )

    # FIXME: This is not the right place, but there is no better common base
    # FIXME: class. I don't know what copy_into is used for. My guess would
    # FIXME: be cloning of some sort. I'm not sure that this code will work
    # FIXME: with custom attributes.
    def copy_into(self, _other, columns, **kwargs):
        target = _other or type(self)()

        columns = set(columns).union(kwargs.keys())
        for name in columns:
            if name in kwargs:
                value = kwargs[name]
            else:
                value = getattr(self, name)
            setattr(target, name, value)

        return target