コード例 #1
0
    def new_cls(cls, abs_cls, table_name, cls_name, bind_key=None):
        """
        生成模型类
        :param abs_cls:
        :param table_name:
        :param cls_name:
        :param bind_key:
        :return:
        """
        # 使用抽象类来生成子类
        indexes = list()
        for v in abs_cls.UNION_UNIQUE_INDEX:
            indexes.append(
                db.UniqueConstraint(*v,
                                    name='uix_' + table_name + '_' +
                                    '_'.join(v)))
        for v in abs_cls.UNION_INDEX:
            indexes.append(db.Index('ix_' + table_name + '_' + '_'.join(v),
                                    *v))

        return type(
            cls_name, (abs_cls, ),
            dict(
                __module__=abs_cls.__module__,
                __name__=cls_name,
                __tablename__=table_name,
                __bind_key__=bind_key,
                __table_args__=tuple(indexes),
            ))
コード例 #2
0
ファイル: comments.py プロジェクト: guo-2000/it_management
class Comment(Model):
    __tablename__ = 'comments'

    comment_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, index=True, comment='评论用户id')
    parent_id = db.Column(db.Integer, default=None, comment='被评论的帖子或评论的id')
    type = db.Column(db.Integer, default=0, comment='是什么的评论,0是帖子,1是评论')
    content = db.Column(db.String(120), nullable=False, comment='内容')
    comments_num = db.Column(db.Integer, default=0, comment='评论数量')
    updated_at = db.Column(db.DateTime,
                           server_default=func.now(),
                           comment='修改时间')

    __table_args__ = (db.Index('ix_parent_id_type', 'parent_id', 'type'), )

    def to_dict(self):
        return {
            'comment_id': self.comment_id,
            'parent_id': self.parent_id,
            'type': self.type,
            'content': self.content,
            'comments_num': self.comments_num,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

    def update_time(self):
        self.updated_at = func.now()
コード例 #3
0
class Order(db.Model):
    __tablename__ = 'order'
    __table_args__: Tuple[ForeignKeyConstraint, Index] = (
        db.ForeignKeyConstraint(
            ('funding_funding_id', 'funding_email', 'funding_code'),
            ['funding.funding_id', 'funding.email', 'funding.code']),
        db.Index('fk_order_funding1_idx', 'funding_funding_id',
                 'funding_email', 'funding_code'))

    code: str = db.Column(db.String(10), primary_key=True, nullable=False)
    email: str = db.Column(db.String(50), primary_key=True, nullable=False)
    payee: str = db.Column(db.String(10), nullable=False)
    destination: str = db.Column(db.String(50), nullable=False)
    status: Type[Enum] = db.Column(db.Enum(OrderStatusEnum),
                                   nullable=False,
                                   server_default=db.FetchedValue())
    ordered_at: str = db.Column(db.DateTime,
                                nullable=False,
                                server_default=db.FetchedValue())
    funding_funding_id: int = db.Column(db.Integer,
                                        primary_key=True,
                                        nullable=False)
    funding_email: str = db.Column(db.String(50),
                                   primary_key=True,
                                   nullable=False)
    funding_code: str = db.Column(db.String(10),
                                  primary_key=True,
                                  nullable=False)

    funding: Funding = db.relationship(
        'Funding',
        primaryjoin='and_(Order.funding_funding_id == Funding.funding_id, '
        'Order.funding_email == Funding.email, '
        'Order.funding_code == Funding.code)',
        backref='orders')
コード例 #4
0
class User(db.Model):
    """Pangea User model.

    To make ownership of sample libraries easier, users and organizations
    are treated as the same entity.
    """

    __tablename__ = 'users'

    uuid = db.Column(UUID(as_uuid=True),
                     primary_key=True,
                     server_default=db.text('uuid_generate_v4()'))
    organizations = association_proxy("memberships", "organizations")
    username = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(128), unique=True, nullable=False)
    is_deleted = db.Column(db.Boolean, default=False, nullable=False)
    is_fake = db.Column(db.Boolean, default=False, nullable=False)
    created_at = db.Column(db.DateTime, nullable=False)

    __table_args__ = (db.Index('_user_lower_username_idx',
                               func.lower(username),
                               unique=True), )

    def __init__(self,
                 username,
                 email,
                 is_deleted=False,
                 is_fake=False,
                 created_at=datetime.datetime.utcnow()):
        """Initialize Pangea User model."""
        self.username = username
        self.email = email
        self.is_deleted = is_deleted
        self.is_fake = is_fake
        self.created_at = created_at

    def save(self):
        db.session.add(self)
        db.session.commit()
        return self

    @classmethod
    def from_uuid(cls, uuid):
        return cls.query.filter_by(uuid=uuid).one()

    @classmethod
    def from_name(cls, name):
        return cls.query.filter_by(username=name).one()

    def serializable(self):
        out = {
            'user': {
                'uuid': self.uuid,
                'username': self.username,
                'organizations': [org.uuid for org in self.organizations],
                'email': self.email,
                'is_deleted': self.is_deleted,
                'created_at': self.created_at,
            },
        }
        return out

    def serialize(self):
        return json.dumps(self.serializable())
コード例 #5
0
class SampleGroup(db.Model):  # pylint: disable=too-many-instance-attributes
    """MetaGenScope Sample Group model."""

    __tablename__ = 'sample_groups'

    uuid = db.Column(UUID(as_uuid=True),
                     primary_key=True,
                     server_default=db.text('uuid_generate_v4()'))
    name = db.Column(db.String(128), index=True, nullable=False)
    organization_uuid = db.Column(db.ForeignKey('organizations.uuid'),
                                  nullable=False)
    description = db.Column(db.String(300), nullable=False, default='')
    is_library = db.Column(db.Boolean, default=False, nullable=False)
    is_public = db.Column(db.Boolean, default=True, nullable=False)
    created_at = db.Column(db.DateTime, nullable=False)
    samples = db.relationship('Sample', lazy=True)
    analysis_results = db.relationship('SampleGroupAnalysisResult',
                                       backref='parent',
                                       lazy=True)

    # Duplicate owner properties/indices because we don't know how we will be looking it up
    __table_args__ = (db.Index('_sample_group_lower_name_idx',
                               func.lower(name),
                               unique=True), )

    def __init__(  # pylint: disable=too-many-arguments
        self,
        name,
        organization_uuid,
        description='',
        is_library=False,
        is_public=True,
        created_at=datetime.datetime.utcnow()):
        """Initialize MetaGenScope User model."""
        self.name = name
        self.organization_uuid = organization_uuid
        self.description = description
        self.is_library = is_library
        self.is_public = is_public
        self.created_at = created_at

    def sample(self, sample_name, metadata={}, force_new=False):
        """Return a sample bound to this library.

        Create and save the sample if it does not already exist.
        """
        samps = [samp for samp in self.samples if samp.name == sample_name]
        if samps and not force_new:
            return samps[0]
        return Sample(sample_name, self.uuid, metadata=metadata).save()

    def analysis_result(self, module_name):
        """Return an AR for the module bound to this sample.

        Create and save the AR if it does not already exist.
        """
        ars = [
            ar for ar in self.analysis_results if ar.module_name == module_name
        ]
        if ars:
            result = ars[0]
        else:
            result = SampleGroupAnalysisResult(module_name, self.uuid).save()
        return result

    @property
    def sample_uuids(self):
        return [sample.uuid for sample in self.samples]

    @property
    def tools_present(self):
        """Return list of names for Tool Results present across all Samples in this group."""
        # Cache samples
        samples = self.samples

        tools_present_in_all = set([])
        for i, sample in enumerate(samples):
            tool_results = set(sample.tool_result_names)
            if i == 0:
                tools_present_in_all |= tool_results
            else:
                tools_present_in_all &= tool_results
        return list(tools_present_in_all)

    def serializable(self):
        out = {
            'sample_group': {
                'uuid': self.uuid,
                'name': self.name,
                'organization_uuid': self.organization_uuid,
                'description': self.description,
                'is_library': self.is_library,
                'is_public': self.is_public,
                'created_at': self.created_at,
                'sample_uuids': [sample.uuid for sample in self.samples],
                'analysis_result_uuids':
                [ar.uuid for ar in self.analysis_results],
            },
        }
        return out

    def serialize(self):
        return json.dumps(self.serializable())

    def save(self):
        db.session.add(self)
        db.session.commit()
        return self

    @classmethod
    def from_uuid(cls, uuid):
        return cls.query.filter_by(uuid=uuid).one()

    @classmethod
    def from_name(cls, name):
        return cls.query.filter_by(name=name).one()
コード例 #6
0
ファイル: expense.py プロジェクト: deb17/moneycare
        value = round(Decimal(value), 2)
        self.amount_str = str(value)

    @classmethod
    def amount_num(cls, amount_str):
        '''Needed because we cannot use the hybrid expression to get a
        numeric field in a query in sqlite. Rather we select `amount_str`
        and use this method to convert it to a decimal number.
        '''
        if current_user.allow_decimals:
            return Decimal(amount_str)

        return round(Decimal(amount_str), 0)

    def set_tags(self, taglist):

        for tagname in taglist.split(','):
            if tagname:
                tag = Tag.query.filter_by(user_id=self.user_id,
                                          tagname=tagname.lower()).first()
                if not tag:
                    tag = Tag(user_id=self.user_id, tagname=tagname.lower())
                self.tags.append(tag)

    def __repr__(self):
        return f'<Expense: {self.amount}>'


db.Index('idx_expenses_date_updated_on', Expense.date, Expense.updated_on)
コード例 #7
0
              nullable=False),
    db.Column('funding_email', db.String(50), primary_key=True,
              nullable=False),
    db.Column('funding_code', db.String(10), primary_key=True, nullable=False),
    db.Column('idea_idea_id', db.Integer, primary_key=True, nullable=False),
    db.Column('idea_email', db.String(50), primary_key=True, nullable=False),
    db.Column('idea_code', db.String(10), primary_key=True, nullable=False),
    db.ForeignKeyConstraint(
        ('funding_funding_id', 'funding_email', 'funding_code'),
        ['funding.funding_id', 'funding.email', 'funding.code'],
        ondelete='CASCADE',
        onupdate='CASCADE'),
    db.ForeignKeyConstraint(('idea_idea_id', 'idea_email', 'idea_code'),
                            ['idea.idea_id', 'idea.email', 'idea.code'],
                            onupdate='CASCADE'),
    db.Index('fk_funding_has_idea_idea1_idx', 'idea_idea_id', 'idea_email',
             'idea_code'),
    db.Index('fk_funding_has_idea_funding1_idx', 'funding_funding_id',
             'funding_email', 'funding_code'))

t_funding_has_tag: Table = db.Table(
    'funding_has_tag',
    db.Column('funding_funding_id',
              db.Integer,
              primary_key=True,
              nullable=False),
    db.Column('funding_email', db.String(50), primary_key=True,
              nullable=False),
    db.Column('funding_code', db.String(10), primary_key=True, nullable=False),
    db.Column('tag_title',
              db.ForeignKey('tag.title'),
              primary_key=True,