Beispiel #1
0
class Defensives(BaseSchema):
    __tablename__ = 'defensives'

    id = Column(Integer,
                Sequence('defensive_id_seq', start=1000000),
                primary_key=True)

    blocks = Column(Integer, CheckConstraint('blocks >= 0'), default=0)
    interceptions = Column(Integer,
                           CheckConstraint('interceptions >= 0'),
                           default=0)
    recoveries = Column(Integer, CheckConstraint('recoveries >= 0'), default=0)
    corners_conceded = Column(Integer,
                              CheckConstraint('corners_conceded >= 0'),
                              default=0)
    fouls_conceded = Column(Integer,
                            CheckConstraint('fouls_conceded >= 0'),
                            default=0)
    challenges_lost = Column(Integer,
                             CheckConstraint('challenges_lost >= 0'),
                             default=0)
    handballs_conceded = Column(Integer,
                                CheckConstraint('handballs_conceded >= 0'),
                                default=0)
    penalties_conceded = Column(Integer,
                                CheckConstraint('penalties_conceded >= 0'),
                                default=0)
    error_goals = Column(Integer,
                         CheckConstraint('error_goals >= 0'),
                         default=0)
    error_shots = Column(Integer,
                         CheckConstraint('error_shots >= 0'),
                         default=0)

    lineup_id = Column(Integer, ForeignKey('lineups.id'))
    lineup = relationship('MatchLineups', backref=backref('st_defensives'))
Beispiel #2
0
class FuncKeyDestUser(Base):

    __tablename__ = 'func_key_dest_user'
    __table_args__ = (
        ForeignKeyConstraint(['func_key_id', 'destination_type_id'],
                             ['func_key.id', 'func_key.destination_type_id']),
        CheckConstraint('destination_type_id=1'),
    )

    func_key_id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('userfeatures.id'), primary_key=True)
    destination_type_id = Column(Integer, primary_key=True, server_default="1")

    func_key = relationship("FuncKey")
    userfeatures = relationship("UserFeatures")
Beispiel #3
0
class MembershipFee(IntegerIdModel):
    name = Column(String, nullable=False)
    regular_fee = Column(Money,
                         CheckConstraint('regular_fee >= 0'),
                         nullable=False)

    # Timedelta a person has to be member in the given period to be charged any
    # membership fee at all(grace period)
    grace_period = Column(Interval, nullable=False)

    # Timedelta after which members are being charged a late fee for not paying
    # in time + will be added to a group with "payment_in_default" property
    payment_deadline = Column(Interval, nullable=False)

    # Timedelta after which the membership will be cancelled
    payment_deadline_final = Column(Interval, nullable=False)

    begins_on = Column(Date, nullable=False)
    ends_on = Column(Date, nullable=False)

    def __contains__(self, date):
        return date in closed(self.begins_on, self.ends_on)

    __table_args__ = (CheckConstraint('begins_on < ends_on'), )
Beispiel #4
0
class Remark(db.Model):
    """Remark model. Each SolutionGroup can have a remark. Each remark consists of its text
    (a reviewer's comment on the solution) and the percentage of the maximum points it attained.
    This percentage can be between 0 and 1.5 (e.g. in the case of a particularly innovative
    solution.)
    """

    # Note: Remark must be defined before SolutionGroup because SolutionGroup references it.
    __tablename__ = "remarks"
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text, nullable=False)
    score_percentage = db.Column(db.Float(), nullable=False)
    author_id = db.Column(db.Integer,
                          db.ForeignKey("users.id", ondelete="SET NULL"))
    date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    solution_group_id = db.Column(db.Integer,
                                  db.ForeignKey("solution_groups.id",
                                                ondelete="CASCADE"),
                                  nullable=False)
    solution_group = db.relationship('SolutionGroup',
                                     foreign_keys=[solution_group_id],
                                     back_populates='remarks')

    __table_args__ = (
        CheckConstraint(score_percentage >= 0,
                        name='check_score_percentage_positive'),
        CheckConstraint(score_percentage <= 1.5,
                        name='check_score_percentage_not_exceeded'),
    )

    def __repr__(self):
        """
        Override the default string representation method
        """
        return f'<RemarkID:{self.id};SGID:{self.solution_group_id};Text:{get_text_snippet(self.text)}>'
Beispiel #5
0
class FuncKeyDestQueue(Base):

    __tablename__ = 'func_key_dest_queue'
    __table_args__ = (
        ForeignKeyConstraint(['func_key_id', 'destination_type_id'],
                             ['func_key.id', 'func_key.destination_type_id']),
        CheckConstraint('destination_type_id = 3')
    )

    func_key_id = Column(Integer, primary_key=True)
    destination_type_id = Column(Integer, primary_key=True, server_default="3")
    queue_id = Column(Integer, ForeignKey('queuefeatures.id'), primary_key=True)

    func_key = relationship("FuncKey")
    queue = relationship("QueueFeatures")
class FuncKeyDestConference(Base):

    __tablename__ = 'func_key_dest_conference'
    __table_args__ = (
        ForeignKeyConstraint(['func_key_id', 'destination_type_id'],
                             ['func_key.id', 'func_key.destination_type_id']),
        CheckConstraint('destination_type_id = 4')
    )

    func_key_id = Column(Integer, primary_key=True)
    destination_type_id = Column(Integer, primary_key=True, server_default="4")
    conference_id = Column(Integer, ForeignKey('meetmefeatures.id'), primary_key=True)

    func_key = relationship("FuncKey")
    conference = relationship("MeetmeFeatures")
Beispiel #7
0
class INVSELL(INVBUYSELL):
    """ Declarative mixin for OFX INVSELL aggregate """
    markdown = Column(OFXNumeric(), CheckConstraint('markdown >= 0'))
    withholding = Column(OFXNumeric(), CheckConstraint('withholding >= 0'))
    taxexempt = Column(OFXBoolean())
    gain = Column(OFXNumeric())
    loanid = Column(String(length=32))
    statewithholding = Column(OFXNumeric(),
                              CheckConstraint('statewithholding >= 0'))
    penalty = Column(OFXNumeric())

    # Be careful about multiple inheritance.  Subclasses of INV{BUY,SELL}
    # also inherit from INVTRAN, which also uses __table_args__ to define
    # define uniqueness constraint for the natural PKs (acctfrom_id, fitid).
    # This is OK because the polymorphic inheritance scheme for INVTRAN
    # subclasses only requires the uniqueness constraint on the base table
    # (i.e. INVTRAN) which holds these PKs, so INVTRAN subclasses are free
    # to clobber __table_args__ by inheriting it from INV{BUY,SELL}...
    # ...but be careful.
    __table_args__ = (CheckConstraint("""
            total = -1 * units * (unitprice - markdown)
                    - (commission + fees + load + taxes + penalty
                        + withholding + statewithholding)
            """), )
Beispiel #8
0
class RoleAssignment(db.Model):
    __tablename__ = "roleassignment"
    __table_args__ = (
        #
        CheckConstraint(
            "(CAST(anonymous AS INTEGER) = 1)"
            " OR "
            "((CAST(anonymous AS INTEGER) = 0)"
            " AND "
            " ((user_id IS NOT NULL AND group_id IS NULL)"
            "  OR "
            "  (user_id IS NULL AND group_id IS NOT NULL)))",
            name="roleassignment_ck_user_xor_group",
        ),
        #
        UniqueConstraint(
            "anonymous",
            "user_id",
            "group_id",
            "role",
            "object_id",
            name="assignment_mapped_role_unique",
        ),
    )

    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    role = Column(RoleType, index=True, nullable=False)
    anonymous = Column(
        "anonymous",
        Boolean,
        index=True,
        nullable=True,
        default=False,
        server_default=sql.false(),
    )
    user_id = Column(Integer,
                     ForeignKey("user.id", ondelete="CASCADE"),
                     index=True)
    user = relationship(User, lazy="joined")
    group_id = Column(Integer,
                      ForeignKey("group.id", ondelete="CASCADE"),
                      index=True)
    group = relationship(Group, lazy="joined")

    object_id = Column(Integer,
                       ForeignKey(Entity.id, ondelete="CASCADE"),
                       index=True)
    object = relationship(Entity, lazy="select")
Beispiel #9
0
class CollectionContent(BASE, ModelBase):
    """Represents files"""
    __tablename__ = 'ess_coll_content'
    content_id = Column(BigInteger().with_variant(Integer, "sqlite"),
                        Sequence('ESS_CONTENT_ID_SEQ'))
    coll_id = Column(BigInteger)
    scope = Column(String(SCOPE_LENGTH))
    name = Column(String(NAME_LENGTH))
    min_id = Column(BigInteger)
    max_id = Column(BigInteger)
    content_type = Column(ContentType.db_type(name='ESS_CONTENT_TYPE'),
                          default=ContentType.FILE)
    # size = Column(BigInteger)
    # md5 = Column(String(32))
    # adler32 = Column(String(8))
    edge_id = Column(Integer)
    status = Column(ContentStatus.db_type(name='ESS_CONTENT_STATUS'),
                    default=ContentStatus.NEW)
    priority = Column(Integer())
    num_success = Column(Integer())
    num_failure = Column(Integer())
    last_failed_at = Column(DateTime)
    pfn_size = Column(BigInteger)
    pfn = Column(String(1024))
    object_metadata = Column(JSON())
    _table_args = (
        PrimaryKeyConstraint('content_id', name='ESS_COLL_CONTENT_PK'),
        # PrimaryKeyConstraint('scope', 'name', 'coll_id', 'content_type', 'min_id', 'max_id', 'edge_id', 'content_id', name='ESS_COLL_CONTENT_PK'),
        ForeignKeyConstraint(['edge_id'], ['ess_edges.edge_id'],
                             name='ESS_CONTENT_EDGE_ID_FK'),
        ForeignKeyConstraint(['coll_id'], ['ess_coll.coll_id'],
                             name='ESS_CONTENT_COLL_ID_FK'),
        CheckConstraint('status IS NOT NULL', name='ESS_CONTENT_STATUS_NN'),
        UniqueConstraint('scope',
                         'name',
                         'coll_id',
                         'content_type',
                         'min_id',
                         'max_id',
                         'edge_id',
                         name='ESS_CONTENT_UQ'),
        Index('ESS_CONTENT_SCOPE_NAME_IDX', 'scope', 'name', 'edge_id',
              'status'),
        Index('ESS_CONTENT_SCOPE_NAME_MM_IDX', 'scope', 'name', 'content_type',
              'min_id', 'max_id', 'edge_id', 'status'),
        Index('ESS_CONTENT_COLLECTION_ID_IDX', 'coll_id', 'status'),
        Index('ESS_CONTENT_EDGE_ID_IDX', 'edge_id', 'status'),
        Index('ESS_CONTENT_STATUS_PRIO_IDX', 'status', 'priority'))
Beispiel #10
0
def test_enum_detection(metadata):
    Table("simple_items", metadata, Column("enum", VARCHAR(255)),
          CheckConstraint(r"simple_items.enum IN ('A', '\'B', 'C')"))

    assert (generate_code(metadata) == """\
# coding: utf-8
from sqlalchemy import Column, Enum, MetaData, Table

metadata = MetaData()


t_simple_items = Table(
    'simple_items', metadata,
    Column('enum', Enum('A', "\\\\'B", 'C'))
)
""")
Beispiel #11
0
class Step(db.Model):
    """
    Represents one of N build steps for a plan.
    """
    # TODO(dcramer): only a single step is currently supported
    id = Column(GUID, primary_key=True, default=uuid4)
    plan_id = Column(GUID, ForeignKey('plan.id', ondelete='CASCADE'), nullable=False)
    date_created = Column(DateTime, default=datetime.utcnow, nullable=False)
    date_modified = Column(DateTime, default=datetime.utcnow, nullable=False)
    # implementation should be class path notation
    implementation = Column(String(128), nullable=False)
    order = Column(Integer, nullable=False)
    data = Column(JSONEncodedDict)

    plan = relationship('Plan', backref=backref('steps', order_by='Step.order'))

    __repr__ = model_repr('plan_id', 'implementation')
    __tablename__ = 'step'
    __table_args__ = (
        UniqueConstraint('plan_id', 'order', name='unq_plan_key'),
        CheckConstraint(order >= 0, name='chk_step_order_positive'),
    )

    def __init__(self, **kwargs):
        super(Step, self).__init__(**kwargs)
        if self.id is None:
            self.id = uuid4()
        if self.date_created is None:
            self.date_created = datetime.utcnow()
        if self.date_modified is None:
            self.date_modified = self.date_created

    def get_implementation(self, load=True):
        try:
            cls = import_string(self.implementation)
        except Exception:
            return None

        if not load:
            return cls

        try:
            # XXX(dcramer): It's important that we deepcopy data so any
            # mutations within the BuildStep don't propagate into the db
            return cls(**deepcopy(self.data))
        except Exception:
            return None
Beispiel #12
0
class ShotBlocks(BaseSchema):
    __tablename__ = 'shotblocks'

    id = Column(Integer,
                Sequence('shotblock_id_seq', start=1000000),
                primary_key=True)

    freekick = Column(Integer, CheckConstraint('freekick >= 0'), default=0)
    insidebox = Column(Integer, CheckConstraint('insidebox >= 0'), default=0)
    outsidebox = Column(Integer, CheckConstraint('outsidebox >= 0'), default=0)
    headed = Column(Integer, CheckConstraint('headed >= 0'), default=0)
    leftfoot = Column(Integer, CheckConstraint('leftfoot >= 0'), default=0)
    rightfoot = Column(Integer, CheckConstraint('rightfoot >= 0'), default=0)
    other = Column(Integer, CheckConstraint('other >= 0'), default=0)
    total = Column(Integer, CheckConstraint('total >= 0'), default=0)

    lineup_id = Column(Integer, ForeignKey('lineups.id'))
    lineup = relationship('MatchLineups', backref=backref('st_shotblocks'))
Beispiel #13
0
class ArticleContent(UserVisibleContent):
    __tablename__ = "content_article"
    __mapper_args__ = {'polymorphic_identity': 'article'}
    _approval = Enum("approved", "seen", "dissassociated", name="approval")
    id = Column(Integer(),
                ForeignKey('content_user_visible.id'),
                primary_key=True)
    rating = Column(Float(),
                    nullable=False,
                    default=0,
                    doc="Controlled by postgres trigger")
    ratings = relationship("Rating",
                           backref=backref('content'),
                           cascade="all,delete-orphan")
    approval = Column(_approval, nullable=True)

    __table_args__ = (CheckConstraint("rating >= 0 AND rating <= 1"), {})

    # AllanC TODO:
    # Could have derived fields for count="20" min="1" max="10"
    # This is used by Yahoos RSS guide and could be very usefull for statistical processing in future
    # http://video.search.yahoo.com/mrss - see <media:community>

    # Setup __to_dict__fields
    __to_dict__ = copy.deepcopy(UserVisibleContent.__to_dict__)
    _extra_article_fields = {
        'rating': None,
        'approval': None,
    }
    __to_dict__['default'].update(_extra_article_fields)
    __to_dict__['full'].update(_extra_article_fields)

    def __init__(self):
        Content.__init__(self)
        self.__type__ = 'article'

    def rate(self, member, rating):
        from civicboom.lib.database.actions import rate_content
        return rate_content(self, member, rating)

    def parent_seen(self):
        from civicboom.lib.database.actions import parent_seen
        return parent_seen(self)

    def parent_approve(self):
        from civicboom.lib.database.actions import parent_approve
        return parent_approve(self)
class ApplicationDestNode(Base):

    __tablename__ = 'application_dest_node'

    application_uuid = Column(
        String(36),
        ForeignKey('application.uuid', ondelete='CASCADE'),
        primary_key=True,
    )
    type_ = Column(
        'type',
        String(32),
        CheckConstraint("type in ('holding', 'mixing')"),
        nullable=False,
    )
    music_on_hold = Column(String(128))
    answer = Column(Boolean, nullable=False, default=False)
Beispiel #15
0
def create_table(metadata, molecule_design_library_tbl, rack_tbl):
    "Table factory."
    tbl = Table('library_plate', metadata,
                Column('library_plate_id', Integer, primary_key=True),
                Column('molecule_design_library_id', Integer,
                       ForeignKey(molecule_design_library_tbl.c.\
                                  molecule_design_library_id,
                                  onupdate='CASCADE', ondelete='RESTRICT'),
                       nullable=False),
                Column('rack_id', Integer,
                       ForeignKey(rack_tbl.c.rack_id,
                                  onupdate='CASCADE', ondelete='RESTRICT'),
                       nullable=False),
                Column('layout_number', Integer, nullable=False),
                Column('has_been_used', Boolean, nullable=False),
                CheckConstraint('layout_number > 0'))
    return tbl
Beispiel #16
0
class Approval(Base):
    """승인 정보. 퀴즈 정답을 맞혀야 승인 대상 계정에 접근할 수 있습니다."""
    __tablename__ = 'approval'
    # 기본 키
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
    # 생성 시각
    created_at = Column(
        DateTime(timezone=True), nullable=False, default=utcnow
    )
    # 승인 대상 계정의 UUID
    account_id = Column(UUID(as_uuid=True), ForeignKey('account.id'))
    # 승인 만료 시각
    expired_at = Column(DateTime(timezone=True), nullable=False)
    # 승인된 시각
    approved_at = Column(DateTime(timezone=True), nullable=True)
    # 승인에 필요한 퀴즈 정답
    quiz_answer = Column(Unicode, nullable=False)
    # 승인 대상 계정
    account = relationship('Account', back_populates='approvals')

    __table_args__ = (
        CheckConstraint('created_at < expired_at', name='ck_expired_at'),
    )

    def approve(self, *, now: Optional[datetime.datetime] = None) -> str:
        if now is None:
            now = utcnow()
        assert self.approved_at is None
        assert self.expired_at >= now
        self.approved_at = now

    @hybrid_property
    def activated(self) -> bool:
        return self.expired_at >= utcnow()

    @activated.expression
    def activated(cls):
        return cls.expired_at >= now()

    @hybrid_property
    def approved(self) -> bool:
        return self.approved_at is not None

    @approved.expression
    def approved(cls):
        return cls.approved_at.isnot(None)
Beispiel #17
0
def test_noconstraints_table(metadata):
    simple_items = Table("simple_items", metadata, Column("number", INTEGER),
                         CheckConstraint("number > 2"))
    simple_items.indexes.add(Index("idx_number", simple_items.c.number))

    assert (generate_code(metadata, noconstraints=True) == """\
# coding: utf-8
from sqlalchemy import Column, Integer, MetaData, Table

metadata = MetaData()


t_simple_items = Table(
    'simple_items', metadata,
    Column('number', Integer, index=True)
)
""")
Beispiel #18
0
def create_table(metadata, job_tbl):
    "Table factory."
    tbl = Table(
        'iso_job', metadata,
        Column('job_id',
               Integer,
               ForeignKey(job_tbl.c.job_id,
                          onupdate='CASCADE',
                          ondelete='CASCADE'),
               nullable=False),
        Column('number_stock_racks',
               Integer,
               CheckConstraint('number_stock_racks >= 0'),
               nullable=False))

    PrimaryKeyConstraint(tbl.c.job_id)
    return tbl
Beispiel #19
0
class Callfiltermember(Base):

    __tablename__ = 'callfiltermember'
    __table_args__ = (UniqueConstraint('callfilterid', 'type', 'typeval'),
                      CheckConstraint("bstype in ('boss', 'secretary')"))

    id = Column(Integer, primary_key=True)
    callfilterid = Column(Integer, nullable=False, server_default='0')
    type = Column(Enum('user',
                       name='callfiltermember_type',
                       metadata=Base.metadata),
                  nullable=False)
    typeval = Column(String(128), nullable=False, server_default='0')
    ringseconds = Column(Integer, nullable=False, server_default='0')
    priority = Column(Integer, nullable=False, server_default='0')
    bstype = Column(enum.generic_bsfilter, nullable=False)
    active = Column(Integer, nullable=False, server_default='0')
Beispiel #20
0
class Touches(BaseSchema):
    __tablename__ = 'touches'

    id = Column(Integer, Sequence('touch_id_seq', start=1000000), primary_key=True)

    dribble_overruns = Column(Integer, CheckConstraint('dribble_overruns >= 0'), default=0)
    dribble_success = Column(Integer, CheckConstraint('dribble_success >= 0'), default=0)
    dribble_failure = Column(Integer, CheckConstraint('dribble_failure >= 0'), default=0)
    balltouch_success = Column(Integer, CheckConstraint('balltouch_success >= 0'), default=0)
    balltouch_failure = Column(Integer, CheckConstraint('balltouch_failure >= 0'), default=0)
    possession_loss = Column(Integer, CheckConstraint('possession_loss >= 0'), default=0)
    total = Column(Integer, CheckConstraint('total >= 0'), default=0)

    lineup_id = Column(Integer, ForeignKey('lineups.id'))
    lineup = relationship('MatchLineups', backref=backref('st_touches'))
Beispiel #21
0
class Callfiltermember(Base):

    __tablename__ = 'callfiltermember'
    __table_args__ = (UniqueConstraint('callfilterid', 'type', 'typeval'),
                      CheckConstraint("bstype in ('boss', 'secretary')"))

    id = Column(Integer, primary_key=True)
    callfilterid = Column(Integer, nullable=False, server_default='0')
    type = Column(Enum('user',
                       name='callfiltermember_type',
                       metadata=Base.metadata),
                  nullable=False)
    typeval = Column(String(128), nullable=False, server_default='0')
    ringseconds = Column(Integer, nullable=False, server_default='0')
    priority = Column(Integer, nullable=False, server_default='0')
    bstype = Column(enum.generic_bsfilter, nullable=False)
    active = Column(Integer, nullable=False, server_default='0')

    callfilter_exten = column_property(
        select([
            Callfilter.exten
        ]).where(and_(
            Callfilter.id == callfilterid,
            bstype == 'secretary')).correlate_except(Callfilter).as_scalar())

    func_keys = relationship('FuncKeyDestBSFilter',
                             cascade='all, delete-orphan')

    user = relationship('UserFeatures',
                        primaryjoin="""and_(Callfiltermember.type == 'user',
                                            Callfiltermember.typeval == cast(UserFeatures.id, String))""",
                        foreign_keys='Callfiltermember.typeval')

    @hybrid_property
    def timeout(self):
        if self.ringseconds == 0:
            return None
        return self.ringseconds

    @timeout.setter
    def timeout(self, value):
        if value is None:
            self.ringseconds = 0
        else:
            self.ringseconds = value
Beispiel #22
0
class Request(BASE, ModelBase):
    """Represents a pre-cache request from other service"""
    __tablename__ = 'requests'
    request_id = Column(BigInteger().with_variant(Integer, "sqlite"),
                        Sequence('REQUEST_ID_SEQ', schema=DEFAULT_SCHEMA_NAME),
                        primary_key=True)
    scope = Column(String(SCOPE_LENGTH))
    name = Column(String(NAME_LENGTH))
    requester = Column(String(20))
    request_type = Column(EnumWithValue(RequestType))
    transform_tag = Column(String(20))
    workload_id = Column(Integer())
    priority = Column(Integer())
    status = Column(EnumWithValue(RequestStatus))
    substatus = Column(Integer())
    locking = Column(EnumWithValue(RequestLocking))
    created_at = Column("created_at",
                        DateTime,
                        default=datetime.datetime.utcnow)
    updated_at = Column("updated_at",
                        DateTime,
                        default=datetime.datetime.utcnow,
                        onupdate=datetime.datetime.utcnow)
    next_poll_at = Column("next_poll_at",
                          DateTime,
                          default=datetime.datetime.utcnow)
    accessed_at = Column("accessed_at",
                         DateTime,
                         default=datetime.datetime.utcnow,
                         onupdate=datetime.datetime.utcnow)
    expired_at = Column("expired_at", DateTime)
    errors = Column(JSON())
    request_metadata = Column(JSON())
    processing_metadata = Column(JSON())

    _table_args = (
        PrimaryKeyConstraint('request_id', name='REQUESTS_PK'),
        CheckConstraint('status IS NOT NULL', name='REQUESTS_STATUS_ID_NN'),
        # UniqueConstraint('name', 'scope', 'requester', 'request_type', 'transform_tag', 'workload_id', name='REQUESTS_NAME_SCOPE_UQ '),
        Index('REQUESTS_SCOPE_NAME_IDX', 'workload_id', 'request_id', 'name',
              'scope'),
        Index('REQUESTS_STATUS_PRIO_IDX', 'status', 'priority', 'workload_id',
              'request_id', 'locking', 'updated_at', 'next_poll_at',
              'created_at'))
Beispiel #23
0
class GoalTotals(BaseSchema):
    __tablename__ = 'goaltotals'

    id = Column(Integer, Sequence('goaltotal_id_seq', start=1000000), primary_key=True)

    is_firstgoal = Column(Boolean, default=False)
    is_winner = Column(Boolean, default=False)
    freekick = Column(Integer, CheckConstraint('freekick >= 0'), default=0)
    openplay = Column(Integer, CheckConstraint('openplay >= 0'), default=0)
    corners = Column(Integer, CheckConstraint('corners >= 0'), default=0)
    throwins = Column(Integer, CheckConstraint('throwins >= 0'), default=0)
    penalties = Column(Integer, CheckConstraint('penalties >= 0'), default=0)
    substitute = Column(Integer, CheckConstraint('substitute >= 0'), default=0)
    other = Column(Integer, CheckConstraint('other >= 0'), default=0)

    lineup_id = Column(Integer, ForeignKey('lineups.id'))
    lineup = relationship('MatchLineups', backref=backref('st_goal_totals'))
Beispiel #24
0
    class PendingAdmin(Base):
        __tablename__ = "pending_society_admins"

        # There is no ForeignKey constraint here because this table exists to
        # reference users that don't exist yet.
        crsid = Column(CRSID_TYPE,
                       CheckConstraint('crsid = lower(crsid)'),
                       primary_key=True)
        society_society = Column(SOCIETY_TYPE,
                                 ForeignKey('societies.society'),
                                 name="society",
                                 primary_key=True)

        def __str__(self):
            return "{0} {1}".format(self.crsid, self.society.society)

        def __repr__(self):
            return '<PendingAdmin {0} {1}>'.format(self.crsid,
                                                   self.society.society)
Beispiel #25
0
class Participant(db.Model):
    __tablename__ = 'participants'
    __table_args__ = (
        CheckConstraint('(email IS NULL) = (auth_uid IS NULL)', 'email_uid_null'),
    )

    id = db.Column(db.Integer, primary_key=True)
    auth_uid = db.Column(db.String, nullable=True)
    name = db.Column(db.String, nullable=False)
    email = db.Column(db.String, nullable=True)
    code = db.Column(
        db.String,
        nullable=False,
        index=True,
        default=generate_random_participant_code,
        unique=True,
    )
    _answers = db.Column('answers', JSONB, nullable=True, default={})
    comment = db.Column(
        'comment', db.String, nullable=False, default='', server_default=''
    )
    newdle_id = db.Column(
        db.Integer, db.ForeignKey('newdles.id'), nullable=False, index=True
    )

    newdle = db.relationship('Newdle', lazy=True, back_populates='participants')

    @hybrid_property
    def answers(self):
        return {parse_dt(k): Availability[v] for k, v in sorted(self._answers.items())}

    @answers.expression
    def answers(cls):
        return cls._answers

    @answers.setter
    def answers(self, value):
        self._answers = {format_dt(k): v.name for k, v in value.items()}

    def __repr__(self):
        return '<Participant {}: {}{}>'.format(
            self.id, self.name, ' ({})'.format(self.email) if self.email else ''
        )
Beispiel #26
0
class SQLUser(Base):
    __tablename__ = "users"
    __tableargs__ = (CheckConstraint("username ~ '^[-A-z0-9]+$'"), )

    user_uuid = Column(PGUUID, primary_key=True)
    username = Column(satypes.String(length=200),
                      nullable=False,
                      unique=True,
                      index=True)
    password = Column(satypes.String, nullable=False)
    timezone = Column(satypes.String, nullable=False)

    email_obj: "RelationshipProperty[UserEmail]" = relationship("UserEmail",
                                                                uselist=False,
                                                                backref="user")

    api_key_obj: "RelationshipProperty[APIKey]" = relationship("APIKey",
                                                               uselist=False,
                                                               backref="user")
Beispiel #27
0
class SupplyOrderPart(Base):
    __tablename__ =  'supply_order_parts'

    supply_order_part_id = Column(Integer,autoincrement=True,primary_key=True)
    description = Column(String, nullable=False, default="")
    _indexed_description = Column("indexed_description", String, nullable=False)
    quantity = Column(Float,nullable=False)

    # Unit price
    unit_price = Column(MoneyType,nullable=False)
    position = Column(Integer,nullable=False)
    label = Column(String)
    supply_order_id = Column(Integer, ForeignKey('supply_orders.supply_order_id'))


    __table_args__ = (CheckConstraint( 'quantity > 0',
                                       name='actual_quantity'),
                      UniqueConstraint('supply_order_id','position',
                                       name='positions_are_strictly_ordered'))
class FuncKeyDestService(Base):

    DESTINATION_TYPE_ID = 5

    __tablename__ = 'func_key_dest_service'
    __table_args__ = (
        PrimaryKeyConstraint('func_key_id', 'destination_type_id',
                             'extension_id'),
        ForeignKeyConstraint(['func_key_id', 'destination_type_id'],
                             ['func_key.id', 'func_key.destination_type_id']),
        CheckConstraint(
            'destination_type_id = {}'.format(DESTINATION_TYPE_ID)),
    )

    func_key_id = Column(Integer)
    destination_type_id = Column(
        Integer, server_default="{}".format(DESTINATION_TYPE_ID))
    extension_id = Column(Integer, ForeignKey('extensions.id'))

    type = 'service'

    func_key = relationship(FuncKey,
                            cascade='all,delete-orphan',
                            single_parent=True)

    extension = relationship(Extension)
    extension_typeval = association_proxy(
        'extension',
        'typeval',
        # Only to keep value persistent in the instance
        creator=lambda _typeval: Extension(type='extenfeatures',
                                           typeval=_typeval))

    def to_tuple(self):
        return (('service', self.service), )

    @hybrid_property
    def service(self):
        return self.extension_typeval

    @service.setter
    def service(self, value):
        self.extension_typeval = value
class FuncKeyDestService(Base):

    __tablename__ = 'func_key_dest_service'
    __table_args__ = (PrimaryKeyConstraint('func_key_id',
                                           'destination_type_id',
                                           'extension_id'),
                      ForeignKeyConstraint(
                          ['func_key_id', 'destination_type_id'],
                          ['func_key.id', 'func_key.destination_type_id']),
                      ForeignKeyConstraint(['extension_id'],
                                           ['extensions.id']),
                      CheckConstraint('destination_type_id = 5'))

    func_key_id = Column(Integer)
    destination_type_id = Column(Integer, server_default="5")
    extension_id = Column(Integer)

    func_key = relationship("FuncKey")
    extension = relationship("Extension")
Beispiel #30
0
class Assists(BaseSchema):
    __tablename__ = "assists"

    id = Column(Integer, Sequence('assist_id_seq', start=1000000), primary_key=True)

    corners = Column(Integer, CheckConstraint('corners >= 0'), default=0)
    freekicks = Column(Integer, CheckConstraint('freekicks >= 0'), default=0)
    throwins = Column(Integer, CheckConstraint('throwins >= 0'), default=0)
    goalkicks = Column(Integer, CheckConstraint('goalkicks >= 0'), default=0)
    setpieces = Column(Integer, CheckConstraint('setpieces >= 0'), default=0)
    total = Column(Integer, CheckConstraint('total >= 0'), default=0)

    lineup_id = Column(Integer, ForeignKey('lineups.id'))
    lineup = relationship('MatchLineups', backref=backref('st_assists'))
Beispiel #31
0
 def __init__(self, col):
   CheckConstraint.__init__(self, "length(" + str(col) + ") > 0")