Example #1
0
class Solution(BaseModel):
    exercise = ForeignKeyField(Exercise, backref='solutions')
    solver = ForeignKeyField(User, backref='solutions')
    checker = ForeignKeyField(User, null=True, backref='solutions')
    is_checked = BooleanField(default=False)
    grade = IntegerField(
        default=0, constraints=[Check('grade <= 100'), Check('grade >= 0')],
    )
    submission_timestamp = DateTimeField()
    json_data_str = TextField()

    @classmethod
    def next_unchecked(cls):
        unchecked_exercises = cls.select().where(cls.is_checked == False)  # NOQA: E712, E501
        try:
            return unchecked_exercises.dicts().get()
        except cls.DoesNotExist:
            return {}

    @classmethod
    def next_unchecked_of(cls, exercise_id):
        try:
            return cls.select().where(
                (cls.is_checked == 0) & (exercise_id == cls.exercise)
            ).dicts().get()
        except cls.DoesNotExist:
            return {}
Example #2
0
    class Meta:
        """Meta class."""

        constraints = [
            Check("start_time is NULL or start_time LIKE '__:__'"),
            Check("end_time is NULL or end_time LIKE '__:__'")
        ]
Example #3
0
class Artist(BaseModel):
    name = CharField(null=False, unique=True, constraints=[Check('length(name) >= 1'), Check('length(name) <= 30')])
    email = CharField(null=False, unique=True, constraints=[Check('length(email) >=1'), Check('length(email) <= 40')])


    def __str__(self):
        return(f'Name: {self.name}, Email: {self.email}')
Example #4
0
class Event(Model):
    status = CharField(default="created")# in progress, finished

    name = CharField()
    begin = DateTimeField(default=datetime.datetime.now())
    running_time = IntegerField(default=120, constraints=[Check('running_time >= 0')])
    projection_type = CharField()

    sold_seats = IntegerField(default=0, constraints=[Check('sold_seats >= 0')])
    booked_seats = IntegerField(default=0, constraints=[Check('booked_seats >= 0')])
    revenue = IntegerField(default = 0, constraints=[Check('revenue >= 0')])

    room_reserved = BooleanField(default = False)
    equipment_reserved = BooleanField(default = False)
    management = BooleanField(default = False)
    guest_attendance = BooleanField(default = False)
    debate = BooleanField(default = False)
    presentation = BooleanField(default = False)

    manager = ForeignKeyField(User, backref="events")
    projection_room = ForeignKeyField(ProjectionRoom, backref="events")

    class Meta:
        database = db
        table_name = "events"
Example #5
0
class Student(BaseModel):
    id = AutoField(primary_key=True, )
    vk_id = BigIntegerField(
        unique=True,
        constraints=[
            Check("vk_id > 0"),
        ],
    )
    first_name = CharField()
    second_name = CharField()
    group_id = ForeignKeyField(
        Group,
        backref="groups",
        on_delete="CASCADE",
        on_update="CASCADE",
    )
    email = CharField(null=True)
    phone_number = BigIntegerField(
        null=True,
        constraints=[
            Check("phone_number < 99999999999"),
        ],
    )
    subgroup = IntegerField(null=True)
    academic_status = ForeignKeyField(
        AcademicStatus,
        backref="academicstatuses",
        default=1,
        on_delete="RESTRICT",
        on_update="CASCADE",
    )

    class Meta:
        table_name = "students"
Example #6
0
class Order(BaseModel):
    id = AutoField(primary_key=True)
    shipping_information = ForeignKeyField(ShippingInformation,
                                           null=True,
                                           default=None)
    credit_card = ForeignKeyField(CreditCard, null=True, default=None)
    email = CharField(null=True, default=None)
    total_price = FloatField(null=True,
                             default=None,
                             constraints=[Check('total_price>0')])
    transaction = ForeignKeyField(Transaction, null=True, default=None)
    paid = BooleanField(null=False, default=False)
    shipping_price = FloatField(null=True,
                                constraints=[Check('shipping_price>=0')])

    def setTotalPrice(self, products):

        sum = 0
        for p in products:
            sum += (p.product.price * p.product_quantity)

        self.total_price = sum

    def setShippingPrice(self, products):
        totalWeight = 0
        for p in products:
            totalWeight += (p.product.weight * p.product_quantity)

        if totalWeight < 500:
            self.shipping_price = 5.00
        elif totalWeight < 2000:
            self.shipping_price = 10.00
        else:
            self.shipping_price = 25.00
Example #7
0
class Event(Model):
    id: int = PrimaryKeyField()
    received: datetime = DateTimeField(default=fn.now)

    received_from: Server = ForeignKeyField(Server,
                                            null=True,
                                            on_update='cascade')
    """
    Server that we got this Event from.
    In general, this has nothing to do with which server produced the event originally.
    """

    server: str = TextField()
    """Name of the server on which the post affected by this event is published."""

    authors: List[str] = ArrayField(TextField)
    """Name of the user who should be the «owner» of the post."""

    parent: str = TextField(null=True)
    """Full identifier of parent post."""

    path: str = TextField(null=True)
    """
    Identification of the post affected by this event.
    This is the same path as in :data:`Post.path`.
    """

    diff: Dict[str, Any] = BinaryJSONField(
        default={}, constraints=[Check("jsonb_typeof(diff) = 'object'")])
    """Changes which should be applied to the post."""

    signatures: Dict[str, str] = BinaryJSONField(
        default={}, constraints=[Check("jsonb_typeof(signatures) = 'object'")])
    """
Example #8
0
class Artwork(BaseModel):
    artist = ForeignKeyField(Artist, backref='artworks')
    name = CharField(null=False, unique=True, constraints=[Check('length(name) >=1'), Check('length(name) <= 30')])
    price = DecimalField(null=False, constraints=[Check('price > 0'), Check('length(price) <= 5000')])
    available = BooleanField(null=False)


    def __str__(self):
        return(f'Artist: {self.artist}, Name of Artwork: {self.name}, Price: {self.price}, Available: {self.available}')
class Customer(BaseModel):
    """
        This class defines Customer, which maintains details of customers
    """
    customer_ID = CharField(primary_key=True,
                            constraints=[Check('length(customer_id)==5')])
    first_name = CharField(max_length=30)
    last_name = CharField(max_length=30)
    home_address = CharField(max_length=100)
    phone_number = CharField(constraints=[Check('length(phone_number)==10')])
    email_address = CharField(max_length=30)
    status = BooleanField()
    credit_limit = IntegerField()
Example #10
0
class Share(BaseModel):
    ticker = ForeignKeyField(Ticker)
    date = DateField(index=True)
    open = MoneyField(constraints=[Check('open >= 0')])
    high = MoneyField(constraints=[Check('high >= 0')])
    low = MoneyField(constraints=[Check('low >= 0')])
    close = MoneyField(constraints=[Check('close >= 0')])
    volume = IntegerField(constraints=[Check('volume >= 0')])

    class Meta:
        constraints = (
            SQL(f'CONSTRAINT share_unique_idx UNIQUE ("ticker_id", "date")'),
        )
Example #11
0
class EntityData(TimestampsMixin, OutputModel):
    """
    A key-value pair holding arbitrary data for an entity. Together, the 'item_type', 'of_list', and
    'relation_type' provide a specification for the type of the data.
    """

    entity = ForeignKeyField(Entity, on_delete="CASCADE")
    source = TextField(index=True, default="tex-pipeline")
    key = TextField(index=True)
    value = TextField(null=True)

    item_type = TextField(
        index=True,
        choices=(
            ("int", None),
            ("float", None),
            ("string", None),
            ("relation-id", None),
        ),
    )
    " Base type of data. This can be used for casting data when it's retrieved from the datatbase. "

    of_list = BooleanField(index=True)
    " Whether this data point is an element in a list. "

    relation_type = TextField(
        index=True,
        null=True,
        constraints=[
            Check(
                "(item_type = 'relation-id' AND relation_type IS NOT NULL) OR"
                + "(item_type != 'relation-id' AND relation_type IS NULL)")
        ],
    )
    """
Example #12
0
class Maquina(BaseModel):
    codigo = CharField(null=False, unique=True, max_length=20)
    descripcion = TextField(null=True)
    anotaciones = TextField(null=True)
    seccion = ForeignKeyField(Seccion, related_name='maquinas')
    horas_trabajo_diario = IntegerField(
        default=8,
        db_column='horas_trabajo_diario',
        constraints=[Check('horas_trabajo_diario <= 24')])

    # @property
    # def horas_trabajo_diario(self):
    #     return self.__horas_trabajo_diario
    #
    # @horas_trabajo_diario.setter
    # def horas_trabajo_diario(self, horas):
    #     self.__horas_trabajo_diario = horas

    class Meta:
        order_by = (
            'seccion',
            'codigo',
        )

    def __str__(self):
        return '{} -> {}'.format(self.codigo, self.seccion.codigo)
Example #13
0
class Comment(BaseModel):
    commenter = ForeignKeyField(User, backref='comments')
    timestamp = DateTimeField(default=datetime.now)
    line_number = IntegerField(constraints=[Check('line_number >= 1')])
    comment = ForeignKeyField(CommentText)
    file = ForeignKeyField(SolutionFile, backref='comments')
    is_auto = BooleanField(default=False)

    @classmethod
    def by_solution(
            cls,
            solution: Solution,
    ) -> Union[Iterable['Comment'], 'Comment']:
        return cls.select().join(
            SolutionFile,
        ).filter(SolutionFile.solution == solution)

    @property
    def solution(self) -> Solution:
        return self.file.solution

    @classmethod
    def create_comment(
        cls,
        commenter: User,
        line_number: int,
        comment_text: CommentText,
        file: SolutionFile,
        is_auto: bool,
    ) -> 'Comment':
        return cls.get_or_create(
            commenter=commenter,
            line_number=line_number,
            comment=comment_text,
            file=file,
            is_auto=is_auto,
        )

    @classmethod
    def _by_file(cls, file_id: int):
        fields = [
            cls.id, cls.line_number, cls.is_auto,
            CommentText.id.alias('comment_id'), CommentText.text,
            SolutionFile.id.alias('file_id'),
            User.fullname.alias('author_name'),
        ]
        return (
            cls
            .select(*fields)
            .join(SolutionFile)
            .switch()
            .join(CommentText)
            .switch()
            .join(User)
            .where(cls.file == file_id)
        )

    @classmethod
    def by_file(cls, file_id: int) -> Tuple[Dict[Any, Any], ...]:
        return tuple(cls._by_file(file_id).dicts())
Example #14
0
class Product(BaseModel):
    id = AutoField(primary_key=True, null=False)
    name = CharField(null=False)
    type = CharField(null=False)
    description = CharField(null=False)
    image = CharField(null=False)
    height = IntegerField(null=False, constraints=[Check('height>0')])
    weight = IntegerField(null=False, constraints=[Check('weight>0')])
    price = FloatField(null=False, constraints=[Check('price>0')])
    rating = IntegerField(null=False,
                          constraints=[Check('rating>=0'),
                                       Check('rating<=5')])
    in_stock = BooleanField(null=False)

    def __str__(self):
        return self.id
Example #15
0
class Coin(BaseModel):
  """Data model of a Coin

  Attributes
  ----------
  denomination : CharField
    The denomination of a coin
  quantity : IntegerField
    The available quantity of a coin, must be equal or
    greater than 0
  value : IntegerField
    The value of a coin, must be greater than 0
  """
  denomination = CharField(unique=True)
  quantity = IntegerField(default=0, constraints=[Check('quantity >= 0')])
  value = IntegerField(constraints=[Check('value > 0')])
Example #16
0
class User(BaseModel):
    uuid = UUIDField(unique=True)
    first_name = CharField()
    last_name = CharField()
    email = CharField(unique=True)
    password = CharField()
    superuser = BooleanField(default=False)
    status = CharField(
        default='enable',
        constraints=[Check("status IN ('deleted','blocked','enable')")])

    @classmethod
    def get_schema(cls):
        return UserSchema()

    def verify_password(self, origin_password):
        return pbkdf2_sha256.verify(origin_password, self.password)

    def favorite_items(self):
        return [favorite.item.json() for favorite in self.favorites]

    def add_favorite(self, item):
        favorite = Favorites.create(
            uuid=uuid.uuid4(),
            user=self,
            item=item,
        )
        return favorite

    def remove_favorite(self, item):
        Favorites.delete().where(Favorites.item == item,
                                 Favorites.user == self).execute()
        return None
class Park(BaseModel):
    park_id = CharField(unique=True,
                        constraints=[Check('length(park_id) <= 500')])
    park_name = CharField(null=False,
                          constraints=[Check('length(park_name) <= 500')])
    park_city = CharField(null=False,
                          constraints=[Check('length(park_city) <= 500')])
    park_state = CharField(null=False,
                           constraints=[Check('length(park_state) <= 500')])
    park_description = CharField(
        null=False, constraints=[Check('length(park_description) <= 1000')])
    latitude = DecimalField(null=False,
                            constraints=[Check('length(latitude) <= 500')])
    longitude = DecimalField(null=False,
                             constraints=[Check('length(longitude) <= 500')])

    def __str__(self):
        return f"{self.park_id} {self.park_name} {self.park_city} {self.park_state} {self.park_description} {self.latitude} {self.longitude}"

    def dump(self):
        return {
            "park": {
                "id": self.park_id,
                "name": self.park_name,
                "city": self.park_city,
                "state": self.park_state,
                "description": self.park_description,
                "latitude": float(self.latitude),
                "longitude": float(self.longitude)
            }
        }
Example #18
0
class CurrentLightingProfile(Model):
    channel = CharField(
        primary_key=True,
        constraints=[
            Check("channel='%s' OR channel='%s'" %
                  (LightingChannel.RING.value, LightingChannel.LOGO.value))
        ])
    mode = IntegerField()
    speed = IntegerField()
    direction = CharField(constraints=[
        Check("direction='%s' OR direction='%s'" %
              (LightingDirection.FORWARD.value,
               LightingDirection.BACKWARD.value))
    ])
    timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])

    class Meta:
        legacy_table_names = False
        database = INJECTOR.get(SqliteDatabase)
Example #19
0
class Feed(BaseModel):
    id = PrimaryKeyField(index=True)
    url = CharField(index=True)
    title = CharField()
    priority = IntegerField(
        default=3,
        index=True,
        constraints=[Check('priority >= 0'),
                     Check('priority <= 5')])
    created_date = DateTimeField(default=datetime.datetime.now, index=True)
    is_disabled = BooleanField(default=False, index=True)

    def to_dict(self):
        return {
            'id': self.id,
            'url': self.url,
            'title': self.title,
            'priority': self.priority,
            'is_disabled': self.is_disabled,
        }
Example #20
0
class Item(BaseModel):
    uuid = UUIDField(unique=True)
    name = CharField()
    price = DecimalField(max_digits=20)
    description = TextField()
    category = CharField()
    availability = IntegerField(constraints=[Check('availability >= 0')])

    @classmethod
    def get_schema(cls):
        return ItemSchema()
Example #21
0
class Product(BaseModel):
  """Data model of a product

  Attributes
  ----------
  code : CharField
    A code to identify the product
  name : CharField
    The name of a product
  price : IntegerField
    The price of product, must be greater than 0
  quantity : IntegerField
    The available quantity of a product, must be equal or
    greater than 0
  """

  code = CharField(unique=True)
  name = CharField(unique=True)
  price = IntegerField(constraints=[Check('price > 0')])
  quantity = IntegerField(default=0, constraints=[Check('quantity >= 0')])
Example #22
0
class Category(Model):
    '''
    Categories of fees: teenagers, elderly, disabled
    '''

    title = CharField()
    price = IntegerField(default=0, constraints=[Check('price >= 0')])

    class Meta:
        database = db
        table_name = "categories"
Example #23
0
class SBDAPIMessage(SQLiteBaseModel):
    unique_id = IntegerField(unique=True, constraints=[Check('unique_id > 0')])
    msg_id = IntegerField(
        null=True,
        constraints=[Check('msg_id >= 0'),
                     Check('msg_id <= 65535')])
    ts_sent = DateTimeField(default=datetime.utcnow)
    ts_sent_ack = DateTimeField(null=True)
    ts_forward = DateTimeField(null=True)
    ts_forward_ack = DateTimeField(null=True)
    status = IntegerField(
        default=0,
        choices=((0, 'not-sent'), (1, 'sent not acknowledged'),
                 (2, 'sent and acknowledged'), (3,
                                                'forwarded not acknowledged'),
                 (4, 'forwarded and acknowledged'), (5, 'failed')))
    tailnum = CharField()
    ack = IntegerField()
    payload = TextField()
    remarks = TextField(null=True)
Example #24
0
class ProjectionRoom(Model):
    '''
    The place where the film is being screened
    '''

    location = CharField()
    total_seats = IntegerField(default=0,
                               constraints=[Check('total_seats >= 0')])

    class Meta:
        database = db
        table_name = "projection_rooms"
Example #25
0
class BaseModel(Model):
    ci = CharField(primary_key=True)
    nacionalidad = CharField(1)
    cedula = IntegerField(constraints=[Check('cedula > 0')])
    nombre = CharField()

    estado = CharField(null=True)
    municipio = CharField(null=True)
    parroquia = CharField(null=True)
    centro = TextField(null=True)
    direccion = TextField(null=True)
    consultado = DateTimeField(default=datetime.datetime.now)
Example #26
0
class CurrentSpeedProfile(Model):
    channel = CharField(
        primary_key=True,
        constraints=[
            Check("channel='%s' OR channel='%s'" %
                  (ChannelType.FAN.value, ChannelType.PUMP.value))
        ])
    profile = ForeignKeyField(SpeedProfile, unique=True)
    timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])

    class Meta:
        legacy_table_names = False
        database = INJECTOR.get(SqliteDatabase)
Example #27
0
    class Event(BaseModel):
        """A non-message event that occurs in a chat thread."""

        id = AutoField()
        actor = ForeignKeyField(User, backref="acted_events")
        timestamp = DateTimeField()
        type = CharField()  # EventType.X
        target = ForeignKeyField(User, backref="targeted_events", null=True)
        duration = IntegerField(constraints=[Check("duration >= 0")],
                                null=True)

        class Meta:
            indexes = ((("actor", "timestamp", "target"), True), )
Example #28
0
class Location(BaseModel):
    latitude = DoubleField(constraints=[
        Check('-90 < latitude AND latitude < 90')
    ])
    longitude = DoubleField(constraints=[
        Check('-180 < longitude AND longitude < 180')
    ])

    _type = CharField(null=True)
    country = CharField(null=True)
    country_code = CharField(null=True)
    state = CharField(null=True)
    city = CharField(null=True)
    district = CharField(null=True)
    postcode = CharField(null=True)
    street = CharField(null=True)
    number = IntegerField(null=True)

    created_at = DateTimeField(default=datetime.now)
    updated_at = DateTimeField(default=datetime.now)

    def __str__(self):
        return f'{self.__class__}: {self.__data__}'
Example #29
0
class SpeedProfile(Model):
    id = AutoIncrementField()
    channel = CharField(constraints=[
        Check("channel='%s' OR channel='%s'" %
              (ChannelType.FAN.value, ChannelType.PUMP.value))
    ])
    name = CharField()
    read_only = BooleanField(default=False)
    single_step = BooleanField(default=False)
    timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])

    class Meta:
        legacy_table_names = False
        database = INJECTOR.get(SqliteDatabase)
Example #30
0
File: db.py Project: paxet/retadys
def migrate_v1():
    ddbb = get_db()
    migrator = SqliteMigrator(ddbb)
    fecha_entrega_prevista = DateTimeField(formats='%d-%m-%Y %H:%M:%S', null=True)
    horas_trabajo_diario = IntegerField(default=8,
                                        db_column='horas_trabajo_diario',
                                        constraints=[Check('horas_trabajo_diario <= 24')])
    with ddbb.transaction():
        migrate(
            migrator.add_column('programacion', 'fecha_entrega_prevista', fecha_entrega_prevista),
            migrator.add_column('maquina', 'horas_trabajo_diario', horas_trabajo_diario),
        )
        actulizado = True
    return actulizado