class District(BaseModel):
    id = IntegerField(column_name="d_id", null=False)
    warehouse_id = ForeignKeyField(Warehouse,
                                   backref="w_id",
                                   column_name="d_w_id",
                                   null=False)
    name = CharField(column_name="d_name", max_length=10, null=False)
    street_1 = CharField(column_name="d_street_1", max_length=20, null=False)
    street_2 = CharField(column_name="d_street_2", max_length=20)
    city = CharField(column_name="d_city", max_length=20, null=False)
    state = FixedCharField(column_name="d_state", max_length=2)
    zip = FixedCharField(column_name="d_zip", max_length=9, null=False)
    tax = DecimalField(column_name="d_tax",
                       max_digits=4,
                       decimal_places=4,
                       null=False)
    ytd = DecimalField(
        column_name="d_ytd",
        max_digits=12,
        decimal_places=2,
        null=False,
        default=0.00,
    )
    next_order_id = IntegerField(column_name="d_next_o_id",
                                 null=False,
                                 default=1)

    class Meta:
        primary_key = CompositeKey("warehouse_id", "id")
Пример #2
0
class Customer(BaseModel):
    id = IntegerField(column_name="c_id", null=False)
    warehouse_id = IntegerField(column_name="c_w_id", null=False)
    district_id = IntegerField(column_name="c_d_id", null=False)
    first_name = CharField(column_name="c_first", max_length=16, null=False)
    middle_name = FixedCharField(column_name="c_middle",
                                 max_length=2,
                                 null=False)
    last_name = CharField(column_name="c_last", max_length=16, null=False)
    street_1 = CharField(column_name="c_street_1", max_length=20, null=False)
    street_2 = CharField(column_name="c_street_2", max_length=20)
    city = CharField(column_name="c_city", max_length=20, null=False)
    state = FixedCharField(column_name="c_state", max_length=2)
    zip = FixedCharField(column_name="c_zip", max_length=9, null=False)
    phone_number = FixedCharField(column_name="c_phone", max_length=16)
    since = DateTimeField(column_name="c_since",
                          null=False,
                          default=datetime.utcnow())
    credit = CharField(column_name="c_credit", max_length=2)
    credit_limit = DecimalField(column_name="c_credit_lim",
                                max_digits=12,
                                decimal_places=2)
    discount = DecimalField(column_name="c_discount",
                            max_digits=4,
                            decimal_places=4)
    balance = DecimalField(
        column_name="c_balance",
        max_digits=12,
        decimal_places=2,
        null=False,
        default=0.00,
    )
    ytd_payment = FloatField(column_name="c_ytd_payment",
                             null=False,
                             default=0.00)
    payment_count = IntegerField(column_name="c_payment_cnt",
                                 null=False,
                                 default=0)
    delivery_count = IntegerField(column_name="c_delivery_cnt",
                                  null=False,
                                  default=0)
    data = CharField(column_name="c_data", max_length=500)

    @property
    def formatted_name(self):
        """
        Getter for formatted customer name
        :return: formatted customer name
        """
        return (f"{self.first_name} {self.last_name}"
                if self.middle_name is None else
                f"{self.middle_name} {self.first_name} {self.last_name}")

    class Meta:
        primary_key = CompositeKey("warehouse_id", "district_id", "id")
        constraints = [
            SQL("FOREIGN KEY (c_w_id, c_d_id) "
                "REFERENCES district (d_w_id, d_id)")
        ]
Пример #3
0
class UserBase(MySQLModel):
    '''用户表基类'''
    username = FixedCharField(unique=True, max_length=50)
    password = FixedCharField(max_length=100)
    email = FixedCharField(unique=True, max_length=50)
    status = db_option(default='active', comment='用户状态:active(默认)/delete(已删除)')
    createAt = db_autoDate()

    class Meta:
        db_table = 'user'
Пример #4
0
class Account_Info(BaseModel):
    csrf_token = FixedCharField(max_length=13,
                                null=False,
                                verbose_name='账号凭证之一')
    cookie2 = FixedCharField(max_length=32, null=False, verbose_name='账号凭证之二')
    login_id = CharField(max_length=30,
                         null=False,
                         primary_key=True,
                         verbose_name='登录账号')
    member_id = CharField(max_length=30,
                          null=False,
                          verbose_name='官方正版接口 会员id')
    update_time = DateTimeField(null=False, verbose_name='更新时间')
Пример #5
0
class Feature(BaseModel):
    project = ForeignKeyField(Project,
                              index=True,
                              related_name='features',
                              on_delete='CASCADE')
    ref = CharField(max_length=250, index=True)
    lat = IntegerField()  # times 1e7
    lon = IntegerField()
    action = FixedCharField(max_length=1)
    feature = TextField()
    feature_md5 = FixedCharField(max_length=32)
    audit = TextField(null=True)
    validates_count = IntegerField(default=0)
Пример #6
0
class User_campaign(Member):
    campaignId = IntegerField(null=False,
                              primary_key=True,
                              verbose_name='推广计划id')
    title = FixedCharField(max_length=60, null=False, verbose_name='推广计划名称')
    budget = SmallIntegerField(null=False, verbose_name='推广计划预算')
    promoteArea = FixedCharField(null=False,
                                 max_length=255,
                                 verbose_name='投放地域')
    schedule = SmallIntegerField(null=False, verbose_name='投放时段')
    onlineStatus = BooleanField(null=False, verbose_name='推广计划状态')
    settleStatus = BooleanField(null=False)
    cositeFlag = BooleanField(null=False, verbose_name='站外推广')
    createTime = DateTimeField(null=False, verbose_name='推广计划创建时间')
    modifiedTime = DateTimeField(null=False, verbose_name='推广计划被修改时间')
Пример #7
0
class BoardNoodle(PartAccessorMixin, BaseModel):
    """Represents an instance of a noodle on a player's board."""

    board = ForeignKeyField(Board, related_name='noodles', on_delete='CASCADE')
    noodle = ForeignKeyField(Noodle, on_delete='CASCADE')
    # The position of the root part on the board
    position = IntegerField()
    # The orientations of each part (excluding the root), relative to one another
    part1 = FixedCharField(max_length=2)
    part2 = FixedCharField(max_length=2)
    part3 = FixedCharField(max_length=2)
    part4 = FixedCharField(max_length=2)

    def __str__(self):
        return '<BoardNoodle: {}>'.format(self.id)
Пример #8
0
class User(_BaseModel):
    class Meta:
        table_name = "auth_user"

    cpf = FixedCharField(max_length=11, unique=True)
    password = FixedCharField(max_length=60)

    display_name = CharField(max_length=100)
    phone = CharField(max_length=50, default=None, null=True)
    email = CharField(max_length=50, unique=True, default=None, null=True)

    last_login = DateTimeField(default=None, null=True)

    verified_at = BooleanField(default=None, null=True)
    deactivated_at = BooleanField(default=None, null=True)
Пример #9
0
class IDSRuleFielding(BaseModel):
    """IDSRuleFielding model"""

    ids_rule = ForeignKeyField(IDSRule, related_name='fieldings')
    team = ForeignKeyField(Team, related_name='ids_fieldings')
    submission_round = ForeignKeyField(Round,
                                       related_name='submitted_ids_fieldings',
                                       null=True)
    available_round = ForeignKeyField(Round,
                                      related_name='available_ids_fieldings',
                                      null=True)
    sha256 = FixedCharField(max_length=64, null=True)  # FIXME

    @classmethod
    def latest(cls, cs, team):
        """Get latest IDS fielding for provided team and CS.

        :param cs: CS for which IDS fielding need to be fetched.
        :param team: Team for which IDS fielding need to be fetched.
        :return: list containing latest IDS fielding.
        """

        query = cls.select(cls).join(IDSRule, on=(cls.ids_rule == IDSRule.id))
        predicate = (IDSRule.cs == cs) \
                    & (cls.team == team) \
                    & (cls.available_round == Round.current_round())
        result = query.where(predicate).limit(1)
        if result:
            return result[0]
Пример #10
0
class Test(IndexedBlobModel, BaseModel):  # Inherited classes order matters!
    """Test model"""
    blob = BlobField()
    cs = ForeignKeyField(ChallengeSet, related_name='tests')
    job = ForeignKeyField(Job, related_name='tests')
    drilled = BooleanField(null=False, default=False)
    colorguard_traced = BooleanField(null=False, default=False)
    poll_created = BooleanField(null=False, default=False)
    sha256 = FixedCharField(max_length=64)

    @classmethod
    def unsynced_testcases(cls, prev_sync_time):
        """Return test cases not synced"""
        return cls.select().where(cls.created_at > prev_sync_time)

    def to_cqe_pov_xml(self):
        """
            Method to convert job into to cqe xml format
            :return Xml Containing test data in CQE POV format
        """
        pov_header = """<?xml version="1.0" standalone="no" ?>
                        <!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
                     """
        pov = CQE_POV(str(self.cs.id), [])  # pylint:disable=no-member
        pov.actions.append(Write([Data(self.blob)]))

        return pov_header + str(pov)
Пример #11
0
class Crash(IndexedBlobModel, BaseModel): # Inherited classes order matters!
    blob = BlobField(null=True)
    cs = ForeignKeyField(ChallengeSet, related_name='crashes')
    exploited = BooleanField(default=False)
    explored = BooleanField(default=False)
    job = ForeignKeyField(Job, related_name='crashes')
    triaged = BooleanField(null=False, default=False)
    kind = EnumField(choices=['unclassified',
                              'unknown',
                              'ip_overwrite',
                              'partial_ip_overwrite',
                              'uncontrolled_ip_overwrite',
                              'bp_overwrite',
                              'partial_bp_overwrite',
                              'write_what_where',
                              'write_x_where',
                              'uncontrolled_write',
                              'arbitrary_read',
                              'null_dereference',
                              'arbitrary_transmit',
                              'arbitrary_receive'],
                     enum_name='enum_crash_kind',
                     default='unclassified',
                     null=True)
    crash_pc = BigIntegerField(null=True) # pc at the time of the crash
    bb_count = BigIntegerField(null=True) # basic block count
    sha256 = FixedCharField(max_length=64)

    class Meta:     # pylint: disable=no-init,too-few-public-methods,old-style-class
        db_table = 'crashes'
class SFS(Model):
    """ Abstract soldier class """
    _SIN = FixedCharField(9, primary_key=True)
    _trainings = CharField(null=True)
    _rank = CharField()
    _lname = CharField()
    _fname = CharField()

    def killed_in_action(self):
        """ When a soldier dies his instance gets deleted """
        del self

    def expire_training(self):
        """ Is not implemented at this level """
        raise NotImplementedError

    def train(self):
        """ Is not implemented at this level """
        raise NotImplementedError

    def to_dict(self):
        """ Is not implemented at this level """
        raise NotImplementedError

    class Meta:
        database = db
Пример #13
0
class PresencePoint(BaseModel):
    sample = ForeignKeyField(Sample, backref='sample')
    user = ForeignKeyField(User, backref='user')
    status = FixedCharField()

    class Meta:
        primary_key = CompositeKey('sample', 'user')
Пример #14
0
class Codes(Model):
    code = FixedCharField(max_length=4, primary_key=True)
    sent = BooleanField(default=False)
    used = BooleanField(default=False)

    class Meta:
        database = db
Пример #15
0
class CSOR(SFS):
    """ CSOR Class """
    DIVISION = FixedCharField(4, default='CSOR')

    _training_pay = IntegerField()
    _deployment_pay = IntegerField()
    _section_call_sign = FixedCharField(3)
    _kill_count = IntegerField(default=0)

    def expire_training(self, training):
        """ It adds the training to the training inventory """
        if training in self._trainings:
            self._trainings.remove(training)
        else:
            print(
                f"{self._rank} {self._lname} was never trained on {training}")

    def train(self, training):
        """ Adds training to the training inventory """
        self._trainings.append(self.validate_training(training))

    def to_dict(self):
        """ Returns a dictionary with the attributes of the CSOR Member """

        return dict(Service_Number=self._SIN,
                    Rank=self._rank,
                    Last_Name=self._lname,
                    First_Name=self._fname,
                    Division=self.DIVISION,
                    Training_Pay=self._training_pay,
                    Deployment_Pay=self._deployment_pay,
                    Trainings=self._trainings,
                    Call_Sign=self._section_call_sign,
                    Kill_Count=self._kill_count)

    def update_soldier_info(self, call_sign, kills, rank, lname, fname, tpay,
                            dpay):
        """ Updates the solder info """
        self._section_call_sign = call_sign
        self._kill_count = kills
        self._rank = rank
        self._lname = lname
        self._fname = fname
        self._training_pay = tpay
        self._deployment_pay = dpay
Пример #16
0
class User_exception(Member):
    param = CharField(max_length=500,
                      default='',
                      null=True,
                      verbose_name='错误参数')
    reason = CharField(max_length=500, null=False, verbose_name='错误原因')
    cn_reason = FixedCharField(max_length=20,
                               null=False,
                               verbose_name='中文错误出处')
Пример #17
0
class FieldSignatureMixin(SignalModel):
    """Mixin that provides reliable multi column unique indexes.

    This is done by computing the combined values of specified columns into a
    SHA1 hash that can have a unique index applied to it. This value will be
    stored in a field named ``signature``. When a field is archived, this hash
    is set to null to prevent issues going forward.

    This mixin is needed because MySQL cannot have a unique index across
    multiple columns if one or more of the columns are nullable. They have
    marked this issues a WONTFIX because MySQL is a fickle beast.

    Attributes:
        signature (str|None): This is a ``sha1`` hash computed from the fields
            defined in the ``Meta.signature_fields``. This is nulled out if the
            instance is archived.
        Meta.signature_fields (tuple[str]): The names of the fields to factor
            into the computed signature.
    """
    # This is where the signature is stored
    signature = FixedCharField(max_length=40, null=True, unique=True)

    # This is an overridable list of fields that should be used to compose the
    # hash, in order (not that order matters when composing a hash, as long as
    # it stays consistent).
    class Meta:
        signature_fields = ()

    def update_signature(self):
        """Update the signature field by hashing the ``signature_fields``.

        Raises:
            AttributeError: This is raised if ``Meta.signature_fields`` has no
                values in it or if a field in there is not a field on the
                model.
        """
        if not self._meta.signature_fields:
            raise AttributeError(
                "No fields defined in {}.Meta.signature_fields. Please define "
                "at least one.".format(type(self).__name__)
            )

        # If the field is archived, unset the signature so records in the
        # future can have this value.
        if getattr(self, 'archived', False):
            self.signature = None
            return

        # Otherwise, combine the values of the fields together and SHA1 them
        computed = [getattr(self, value) or ' '
                    for value in self._meta.signature_fields]
        computed = ''.join([text_type(value) for value in computed])

        # If computed is a falsey value, that means all the fields were
        # None or blank and that will lead to some pain.
        if computed:
            self.signature = sha1(computed.encode('utf-8')).hexdigest()
Пример #18
0
class Game(DeepFieldModel):
    name_id = FixedCharField(12, unique=True)
    local_start_time = TimeField("%H:%M", null=True)
    time_of_day = SmallIntegerField(null=True)
    field_type = SmallIntegerField(null=True)
    date = DateField()
    venue_id = ForeignKeyField(Venue, null=True)
    home_team_id = ForeignKeyField(Team)
    away_team_id = ForeignKeyField(Team)
class Warehouse(BaseModel):
    id = IntegerField(column_name="w_id", primary_key=True, null=False)
    name = CharField(column_name="w_name", max_length=10, null=False)
    street_1 = CharField(column_name="w_street_1", max_length=20, null=False)
    street_2 = CharField(column_name="w_street_2", max_length=20)
    city = CharField(column_name="w_city", max_length=20, null=False)
    state = FixedCharField(column_name="w_state", max_length=9)
    zip = FixedCharField(column_name="w_zip", max_length=9, null=False)
    tax = DecimalField(
        column_name="w_tax", max_digits=4, decimal_places=4, null=False
    )
    ytd = DecimalField(
        column_name="w_ytd",
        max_digits=12,
        decimal_places=2,
        null=False,
        default=0.00,
    )
Пример #20
0
class User_adgroup(Member):
    campaignId = IntegerField(null=False, index=True, verbose_name='推广计划id')
    adGroupId = IntegerField(null=False, index=True, verbose_name='推广单元id')
    auditState = BooleanField(null=False, verbose_name='未知')
    bidPrice = SmallIntegerField(null=False, verbose_name='推广单元默认出价')
    createTime = DateTimeField(null=False, verbose_name='推广单元创建时间')
    modifiedTime = DateTimeField(null=False, verbose_name='推广单元修改时间')
    offerId = IntegerField(null=False, verbose_name='供应商品id')
    onlineState = BooleanField(null=False, verbose_name='推广单元状态')
    title = FixedCharField(max_length=60, null=False, verbose_name='商品单元名称')
Пример #21
0
class Session(_BaseModel):
    class Meta:
        table_name = "auth_session"

    user = ForeignKeyField(User)
    token = FixedCharField(max_length=128, unique=True)

    last_access = DateTimeField(default=datetime.datetime.utcnow())
    expire_date = DateTimeField(default=datetime.datetime.utcnow() +
                                relativedelta.relativedelta(years=1))
Пример #22
0
class Token(Model):
    address = FixedCharField(max_length=42, unique=True)
    symbol = CharField()
    icon = CharField(null=True)  # emoji
    decimals = SmallIntegerField()
    default_slippage = SmallIntegerField()
    effective_buy_price = CharField(null=True)

    class Meta:
        database = db
Пример #23
0
class Version(BaseModel):
    """Version information contains a version number, date and time information, and a possibly empty git commit."""

    date = DateTimeField(index=True)
    description = TextField()
    major = IntegerField(index=True)
    minor = IntegerField(index=True)
    patch = IntegerField(index=True)
    commit = FixedCharField(max_length=40, index=True, null=True)

    class Meta:
        order_by = ('-major', '-minor', '-patch', '-date')
Пример #24
0
class Bangumi(NeoDB):
    id = IntegerField(primary_key=True)
    name = TextField(unique=True, null=False)
    subtitle_group = TextField(null=False)
    keyword = TextField()
    update_time = FixedCharField(5, null=False)
    cover = TextField()
    status = IntegerField(default=0)

    week = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')

    def __init__(self, **kwargs):
        super(NeoDB, self).__init__(**kwargs)

        update_time = kwargs.get('update_time', '').title()
        if update_time and update_time not in self.week:
            raise ValueError('unexpected update time %s' % update_time)
        self.update_time = update_time
        self.subtitle_group = ', '.join(kwargs.get('subtitle_group', []))

    @classmethod
    def delete_all(cls):
        cls.update(status=STATUS_END).execute()

    @classmethod
    def get_updating_bangumi(cls, status=None, order=True):

        if status is None:
            data = cls.select(cls, Followed.status, Followed.episode) \
                .join(Followed, peewee.JOIN['LEFT_OUTER'], on=(cls.name == Followed.bangumi_name)) \
                .where(cls.status == STATUS_UPDATING).objects()
        else:
            data = cls.select(cls, Followed.status, Followed.episode) \
                .join(Followed, peewee.JOIN['LEFT_OUTER'], on=(cls.name == Followed.bangumi_name)) \
                .where((cls.status == STATUS_UPDATING) & (Followed.status == status)).objects()
        r = []
        for x in data:
            d = model_to_dict(x)
            d['status'] = x.status
            d['episode'] = x.episode
            r.append(d)
        data = r

        if order:
            weekly_list = defaultdict(list)
            for bangumi_item in data:
                weekly_list[bangumi_item['update_time'].lower()].append(
                    dict(bangumi_item))
        else:
            weekly_list = data

        return weekly_list
Пример #25
0
class ArticleList(BaseModel):
    """
    文章列表
    """
    md5 = FixedCharField(index=True, default="", max_length=32, help_text=u"文章标题+来源的md5值")
    origin = CharField(index=True, default="", help_text=u"来源")
    url = CharField(index=True, default="", help_text=u"文章链接")
    cover = CharField(help_text=u"封面图片链接", null=True)
    title = CharField(help_text=u"标题", null=True)
    author = CharField(null=True, default="", max_length=100, help_text=u"作者")
    post_date = DateTimeField(index=True, null=True, help_text=u"文章提交日期")
    create_date = DateTimeField(default=datetime.datetime.now)
    is_crawled = BooleanField(default=False, help_text="爬过标志")
Пример #26
0
class Teachers(BaseModel):

    name = FixedCharField(verbose_name='Teacher Name')

    def __str__(self):
        return self.name

    @classmethod
    def get_all(cls):
        result = {}
        result['teacherls'] = []
        ls = cls.select()
        return [{'name': item.name, 'id': item.id} for item in ls]
class Character(Model):
    class Meta(object):
        database = database

    level = ForeignKeyField(DungeonLevel, null=True)
    name = CharField(max_length=20)
    ascii_char = FixedCharField(max_length=2)
    fgcolor = CharField(max_length=15)
    bgcolor = CharField(max_length=15)
    character_state = CharField(max_length=10)
    character_class = ForeignKeyField(CharacterClass, null=True)
    dungeon_object = ForeignKeyField(DungeonObject, null=True)
    inventory = Inventory()
Пример #28
0
class User(Model):
    created_at = DateTimeField(default=datetime.now)
    updated_at = DateTimeField(default=datetime.now)
    deleted_at = DateTimeField(null=True)
    last_alert_sent_at: datetime = DateTimeField(default=datetime.now)
    total_alerts_sent = IntegerField(default=0)
    telegram_id = CharField(max_length=220, unique=True)
    chat_id = CharField(max_length=220)
    pincode: str = FixedCharField(max_length=6, null=True, index=True)
    age_limit: AgeRangePref = EnumField(choices=AgeRangePref, default=AgeRangePref.Unknown)
    enabled = BooleanField(default=False, index=True)

    class Meta:
        database = db
Пример #29
0
class User(BaseModel):
    """用户类"""

    # 主键:id
    id = IntegerField(primary_key=True)
    # 用户名
    name = CharField()
    # 密码
    password = CharField()
    # 手机号
    mobile = FixedCharField(11)

    class Meta:
        table_name = "user"
Пример #30
0
class Project(MySQLModel):
    '''项目表'''
    id = db_autoId()
    name = FixedCharField(unique=True, max_length=50)
    detail = TextField(null=True)
    currentRelease = ForeignKeyField(Release, null=True)
    ownerId = db_id()
    status = db_option(default='active', comment='active(默认)/done/delete')
    createAt = db_autoDate()
    startDate = db_autoDate()
    endDate = db_date()
    type = db_char(length=10, null=True)

    class Meta:
        db_table = 'project'