예제 #1
0
 def _col_after_parent_attach(col, table):
     int_col = type_coerce(col, SmallInteger)
     e = CheckConstraint(
         int_col.in_(x.value for x in type_.enum
                     if x not in type_.exclude_values),
         f'valid_enum_{col.name}')
     e.info['alembic_dont_render'] = True
     assert e.table is table
예제 #2
0
class ChangeRequest(Base):
    __tablename__ = 'change_requests'
    id = Column(Integer, primary_key=True)
    created_by_user_id = Column(Integer,
                                ForeignKey('users.id'),
                                nullable=False)
    reviewed_by_user_id = Column(Integer, ForeignKey('users.id'))

    created_at = Column(DateTime(timezone=True), nullable=False)
    reviewed_at = Column(DateTime(timezone=True), nullable=True)
    status = Column(Enum(ChangeStatus),
                    default=ChangeStatus.PENDING,
                    nullable=False)
    comment = Column(String(1024), nullable=True)
    object_type = Column(Enum(EditableObjectType), nullable=False)
    object_id = Column(Integer, nullable=True)
    change_type = Column(Enum(ChangeType), nullable=False)

    created_by = relationship('User', foreign_keys=[created_by_user_id])
    reviewed_by = relationship('User', foreign_keys=[reviewed_by_user_id])
    entity = relationship(
        'Entity',
        primaryjoin="and_(Entity.id == foreign(ChangeRequest.object_id), "
        "ChangeRequest.object_type == 'ENTITY')",
        overlaps="schema")
    schema = relationship(
        'Schema',
        primaryjoin="and_(Schema.id == foreign(ChangeRequest.object_id), "
        "ChangeRequest.object_type == 'SCHEMA')",
        overlaps="entity")

    __table_args__ = (CheckConstraint(
        "object_id IS NOT NULL OR (change_type = 'CREATE' AND status <> 'APPROVED')"
    ), )
예제 #3
0
class FollowedUser(Base):
    """Tracks which user follows which user.

    E.g. if user 1 follows user 2, user 1 will see changes of user 2 in their
    feed.
    """
    __tablename__ = 'feed_followed_users'

    followed_user_id = Column(
        Integer, ForeignKey(users_schema + '.user.id'),
        nullable=False)
    followed_user = relationship(
        User, primaryjoin=followed_user_id == User.id
    )

    follower_user_id = Column(
        Integer, ForeignKey(users_schema + '.user.id'),
        nullable=False)
    follower_user = relationship(
        User, primaryjoin=follower_user_id == User.id
    )

    __table_args__ = (
        PrimaryKeyConstraint(followed_user_id, follower_user_id),
        CheckConstraint(
            'followed_user_id != follower_user_id',
            name='check_feed_followed_user_self_follow'),
        Base.__table_args__
    )
예제 #4
0
class Game(Base):
    """
    A mastermind game with its setup, players and moves.
    The score can be calculated with the number of guesses (1 point
    for the codemaker for each guess + an extra point if
    the codebreaker uses all the moves without discovering the code).
    """
    __tablename__ = GAME_TABLE
    id = Column(Integer, primary_key=True, autoincrement=True)
    created = Column(DateTime, default=datetime.datetime.utcnow)

    # The players!
    codemaker_id = Column(Integer, ForeignKey(USER_TABLE + '.name'))
    codebreaker_id = Column(Integer, ForeignKey(USER_TABLE + '.name'))
    codemaker = relationship("User", foreign_keys=[codemaker_id])
    codebreaker = relationship("User", foreign_keys=[codebreaker_id])

    # The codes and the moves
    code_id = Column(Integer, ForeignKey(CODE_TABLE + '.id'))
    code = relationship('Code', foreign_keys=[code_id])
    guesses = relationship('Guess', back_populates="game", uselist=True)

    # Setup for the game (8, 10 or 12 moves max) TODO: Add constraint
    max_moves = Column(Integer, default=8)
    __table_args__ = (CheckConstraint(
        'max_moves == 8 or max_moves == 10 or max_moves == 12',
        name='correct_nr_moves'), {})
예제 #5
0
파일: table_def.py 프로젝트: LLNL/RASE
class ScenarioBackgroundMaterial(Base):
    """many-to-many table between scenario and material"""
    __tablename__ = 'scenario_background_materials'
    id            = Column(Integer, primary_key=True)
    dose          = Column(Float)
    fd_mode       = Column(String, CheckConstraint("fd_mode IN ('DOSE','FLUX')"))
    material      = relationship('Material', lazy='joined')
    scenario_id   = Column(String, ForeignKey('scenarios.id'))
    material_name = Column(String, ForeignKey('materials.name'))
예제 #6
0
class Sites(Base, movieDbBaseClass):
    """
    Table for all sites.
    """
    __tablename__ = 'sites'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    url = Column(String(250), nullable=False)
    title_xpath = Column(String(250))
    active = Column(Integer())
    locations_ref = Column(Integer, ForeignKey("locations.id"))
    CheckConstraint("active  in (0, 1)", name="site_active_constraint")
예제 #7
0
    def test_reflect_check_constraint(self):
        meta = self.metadata

        cc_table = Table(
            'pgsql_cc', meta,
            Column('a', Integer()),
            CheckConstraint('a > 1 AND a < 5', name='cc1'),
            CheckConstraint('a = 1 OR (a > 2 AND a < 5)', name='cc2'))

        cc_table.create()

        reflected = Table('pgsql_cc', MetaData(testing.db), autoload=True)

        check_constraints = dict((uc.name, uc.sqltext.text)
                                 for uc in reflected.constraints
                                 if isinstance(uc, CheckConstraint))

        eq_(check_constraints, {
            u'cc1': u'(a > 1) AND (a < 5)',
            u'cc2': u'(a = 1) OR ((a > 2) AND (a < 5))'
        })
예제 #8
0
class Report(Base):
    __tablename__ = "report"

    report_id = Column(String(128), primary_key=True)
    input_dir = Column(String(256))
    project_name = Column(String(128), nullable=False)
    result = Column(JSON)  # array
    last_modified_at = Column(DateTime, default=func.current_timestamp())

    report_file_relations = relationship("ReportFileRelation",
                                         back_populates="report")

    CheckConstraint(project_name.in_(project_names))
예제 #9
0
class ESSyncStatus(Base):
    """A table with a single row that indicates the last time the
    ElasticSearch index was updated.
    """
    __tablename__ = 'es_sync_status'

    last_update = Column(DateTime(timezone=True))

    # make sure there is only one row in this table
    id = Column(Integer, primary_key=True, default=1)
    __table_args__ = (CheckConstraint('id = 1', name='one_row_constraint'), {
        'schema': schema
    })
예제 #10
0
class Trivia(Base):
    __tablename__: str = 'trivia'
    __table_args__ = (
        CheckConstraint('to_time > from_time', name="to_bigger_from"),
    )
    triviaID: Column = Column('trivia_id', Integer, primary_key=True)
    createdByID: Column = Column('created_by_id', Integer, ForeignKey(Account.id))
    description: Column = Column('description', String(5000))
    alertText: Column = Column('alert_text', String(1000))
    fromTime: Column = Column('from_time', DateTime)
    toTime: Column = Column('to_time', DateTime)

    createdBy = relationship(Account)
    questions = relationship('TriviaQuestion', back_populates='trivia')
예제 #11
0
class Trivia(Base):
    __tablename__: str = 'trivia'
    __table_args__ = (
        CheckConstraint('toTime > fromTime'),
    )
    triviaID: Column = Column(Integer, primary_key=True)
    createdByID: Column = Column(Integer, ForeignKey('accounts.id'))
    description: Column = Column(String(5000))
    alertText: Column = Column(String(1000))
    fromTime: Column = Column(DateTime)
    toTime: Column = Column(DateTime)

    createdBy = relationship('Account')
    questions = relationship('TriviaQuestion', back_populates='trivia')
예제 #12
0
def _create_reminder_table_construct():
    log.info("Creating reminder table construct.")

    return table(
        REMINDER_TABLE,
        Column("id", Integer, primary_key=True),
        Column(
            "created_at",
            DateTime(timezone=True),
            server_default=func.current_timestamp(),
            nullable=False,
        ),
        Column("last_reminded_at", DateTime(timezone=True),),
        Column("timezone", String(), CheckConstraint("is_timezone(timezone)"),),
        Column("is_canceled", Boolean(), nullable=False, server_default="false"),
        Column("attributes", JSONB, nullable=False),
    )
예제 #13
0
def upgrade(migrate_engine):
    meta.bind = migrate_engine

    tsk = Table("task", meta, autoload=True)

    rs = Table(
        "to_do",
        meta,
        Column("id", Integer, primary_key=True),
        Column("task_id",
               Integer,
               ForeignKey(tsk.c.id),
               nullable=False,
               index=True),
        Column("description", UnicodeText),
        Column("status", Integer, CheckConstraint("status IN (-1, 0, 1)")),
        *get_audit_mixin_columns(),
    )

    rs.create()
예제 #14
0
class Change(Base):
    __tablename__ = 'changes'
    id = Column(Integer, primary_key=True)
    change_request_id = Column(Integer,
                               ForeignKey('change_requests.id'),
                               nullable=False)
    attribute_id = Column(Integer, ForeignKey('attributes.id'), nullable=True)

    object_id = Column(Integer, nullable=True)
    value_id = Column(Integer, nullable=False)
    content_type = Column(Enum(ContentType), nullable=False)
    change_type = Column(Enum(ChangeType), nullable=False)
    field_name = Column(String, nullable=True)
    data_type = Column(Enum(ChangeAttrType), nullable=False)

    change_request = relationship('ChangeRequest')
    attribute = relationship('Attribute')

    __table_args__ = (CheckConstraint(
        'NOT(attribute_id IS NULL AND field_name IS NULL)'
        ' AND NOT (attribute_id IS NOT NULL AND field_name IS NOT NULL)'), )
예제 #15
0
def create_reminder_table():
    log.info("Creating reminder table.")

    op.execute(
        """CREATE OR REPLACE FUNCTION is_timezone(tz TEXT) RETURNS BOOLEAN as $$
        DECLARE
            date TIMESTAMPTZ;
        BEGIN
            date := now() AT TIME ZONE tz;
            RETURN TRUE;
        EXCEPTION WHEN invalid_parameter_value THEN
            RETURN FALSE;
        END;
        $$ language plpgsql STABLE;""")

    op.create_table(
        REMINDER_TABLE,
        Column("id", Integer, primary_key=True),
        Column(
            "created_at",
            DateTime(timezone=True),
            server_default=func.current_timestamp(),
            nullable=False,
        ),
        Column(
            "last_reminded_at",
            DateTime(timezone=True),
        ),
        Column(
            "timezone",
            String(),
            CheckConstraint("is_timezone(timezone)"),
        ),
        Column("is_canceled",
               Boolean(),
               nullable=False,
               server_default="false"),
        Column("attributes", JSONB, nullable=False),
    )
예제 #16
0
    # object_ids of type objects representative for all descendants (used as preview)
    Column("_type_objects", ARRAY(String), nullable=True),
    # object_ids of type objects directly under this node (used as preview for the node's objects)
    Column("_own_type_objects", ARRAY(String), nullable=True),
    # Number of children of this node
    Column("_n_children", BigInteger, nullable=True),
    # Number of objects directly below this node
    Column("_n_objects", BigInteger, nullable=True),
    # Number of all objects anywhere below this node
    Column("_n_objects_deep", BigInteger, nullable=True),
    # Validity of cached values
    Column("cache_valid", Boolean, nullable=False, server_default="f"),
    # An orig_id must be unique inside a project
    Index("idx_orig_proj", "orig_id", "project_id", unique=True),
    # A node may not be its own child
    CheckConstraint("node_id != parent_id"),
)

nodes_objects = Table(
    "nodes_objects",
    metadata,
    Column(
        "node_id",
        None,
        ForeignKey("nodes.node_id", ondelete="CASCADE"),
        index=True,
        nullable=False,
    ),
    Column(
        "project_id",
        None,
예제 #17
0
class Transaction(Base, Mergeable):
    """Securities transaction.
    """

    id = Column(Integer, primary_key=True)
    type = Column(
        Enum(TransactionType, name="transaction_type"),
        nullable=False,
        comment=f"One of {tuple(TransactionType.__members__.keys())}",
    )
    uniqueid = Column(String,
                      nullable=False,
                      unique=True,
                      comment="FI transaction unique identifier")
    datetime = Column(
        DateTime,
        nullable=False,
        comment="Effective date/time: ex-date for reorgs, return of capital",
    )
    fiaccount_id = Column(
        Integer,
        ForeignKey("fiaccount.id", onupdate="CASCADE"),
        nullable=False,
        comment=
        ("Financial institution account (for transfers, destination FI account)"
         " - FK fiaccount.id"),
    )
    # Multiple join paths from Transaction to FiAccount (fiaccount; fiaccountfrom)
    # so can't use relationship(back_populates) on both sides of the the join;
    # must use relationship(backref) on the ForeignKey side.
    fiaccount = relationship("FiAccount",
                             foreign_keys=[fiaccount_id],
                             backref="transactions")
    security_id = Column(
        Integer,
        ForeignKey("security.id", onupdate="CASCADE"),
        nullable=False,
        comment="FK security.id",
    )
    # Multiple join paths from Transaction to Security (security; securityfrom)
    # so can't use relationship(back_populates) on both sides of the the join;
    # must use relationship(backref) on the ForeignKey side.
    security = relationship("Security",
                            foreign_keys=[security_id],
                            backref="transactions")
    units = Column(
        Numeric,
        CheckConstraint("units <> 0", name="units_nonzero"),
        comment=("Change in shares, contracts, etc. caused by Transaction "
                 "(for splits, transfers, exercise: destination security "
                 "change in units)"),
    )
    # Currency denomination of Transaction.cash
    currency = Column(CurrencyType)
    # Change in money amount caused by Transaction
    cash = Column(Numeric)
    fromfiaccount_id = Column(
        "fromfiaccount_id",
        Integer,
        ForeignKey("fiaccount.id", onupdate="CASCADE"),
        comment="For transfers: source FI account (FK fiaccount.id)",
    )
    # Multiple join paths from Transaction to FiAccount (fiaccount; fiaccountfrom)
    # so can't use relationship(back_populates) on both sides of the the join;
    # must use relationship(backref) on the ForeignKey side.
    fromfiaccount = relationship("FiAccount",
                                 foreign_keys=[fromfiaccount_id],
                                 backref="fromtransactions")
    fromsecurity_id = Column(
        Integer,
        ForeignKey("security.id", onupdate="CASCADE"),
        comment=
        "For transfers, spinoffs, exercise: source security (FK security.id)",
    )
    # Multiple join paths from Transaction to Security (security; securityfrom)
    # so can't use relationship(back_populates) on both sides of the the join;
    # must use relationship(backref) on the ForeignKey side.
    fromsecurity = relationship("Security",
                                foreign_keys=[fromsecurity_id],
                                backref="transactionsFrom")
    fromunits = Column(
        "fromunits",
        Numeric,
        comment=
        "For splits, transfers, exercise: source security change in units",
    )
    #  "It should be noted that a check constraint is satisfied if the check expression
    #  evaluates to true or the null value. Since most expressions will evaluate to the
    #  null value if any operand is null, they will not prevent null values in the
    #  constrained columns."
    #  https://www.postgresql.org/docs/11/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS
    numerator = Column(
        Numeric,
        CheckConstraint("numerator > 0", name="numerator_positive"),
        comment=
        "For splits, spinoffs: normalized units of destination security",
    )
    denominator = Column(
        Numeric,
        CheckConstraint("denominator > 0", name="denominator_positive"),
        comment="For splits, spinoffs: normalized units of source security",
    )
    memo = Column(Text)
    dtsettle = Column(
        DateTime, comment="Settlement date: pay date for return of capital")
    sort = Column(
        Enum(TransactionSort, name="transaction_sort"),
        comment="Sort algorithm for gain recognition",
    )
    securityprice = Column(
        "securityprice",
        Numeric,
        CheckConstraint("securityprice >= 0",
                        name="securityprice_not_negative"),
        comment=
        "For spinoffs: unit price used to fair-value destination security",
    )
    fromsecurityprice = Column(
        "fromsecurityprice",
        Numeric,
        CheckConstraint("fromsecurityprice >= 0",
                        name="fromsecurityprice_not_negative"),
        comment="For spinoffs: unit price used to fair-value source security",
    )

    __table_args__ = (CheckConstraint(TRANSACTION_CONSTRAINT,
                                      name="enforce_subtype_nulls"), {
                                          "comment": "Securities Transactions"
                                      })

    signature = ("fiaccount", "uniqueid")

    @classmethod
    def between(cls, session, dtstart, dtend):
        """Convenience method for common query.
        """
        transactions = (session.query(cls).filter(
            and_(
                cls.datetime >= dtstart,
                cls.datetime < dtend,
            )).order_by(
                cls.datetime,
                cls.type,
                cls.uniqueid,
            ))
        return transactions
예제 #18
0
 def _col_after_parent_attach(col, table):
     e = CheckConstraint(type_coerce(col, type_).in_(x.value for x in type_.enum if x not in type_.exclude_values),
                         'valid_enum_{}'.format(col.name))
     e.info['alembic_dont_render'] = True
     assert e.table is table
예제 #19
0
class Queue(Base, AsteriskOptionsMixin):

    EXCLUDE_OPTIONS = {
        'name',
        'category',
        'commented',
    }
    EXCLUDE_OPTIONS_CONFD = {
        'musicclass',
    }
    AST_TRUE_INTEGER_COLUMNS = {
        'ringinuse',
        'timeoutrestart',
        'autofill',
        'setinterfacevar',
        'setqueueentryvar',
        'setqueuevar',
        'reportholdtime',
        'random-periodic-announce',
    }

    _options = [
    ]  # This should eventually be a column to set arbitrary asterisk options

    __tablename__ = 'queue'
    __table_args__ = (PrimaryKeyConstraint('name'),
                      Index('queue__idx__category', 'category'),
                      CheckConstraint("autopause in ('no', 'yes', 'all')"))

    name = Column(String(128))
    musicclass = Column(String(128))
    announce = Column(String(128))
    context = Column(String(39))
    timeout = Column(Integer, server_default='0')
    monitor_type = Column(
        'monitor-type',
        Enum('no',
             'mixmonitor',
             name='queue_monitor_type',
             metadata=Base.metadata))
    monitor_format = Column('monitor-format', String(128))
    queue_youarenext = Column('queue-youarenext', String(128))
    queue_thereare = Column('queue-thereare', String(128))
    queue_callswaiting = Column('queue-callswaiting', String(128))
    queue_holdtime = Column('queue-holdtime', String(128))
    queue_minutes = Column('queue-minutes', String(128))
    queue_seconds = Column('queue-seconds', String(128))
    queue_thankyou = Column('queue-thankyou', String(128))
    queue_reporthold = Column('queue-reporthold', String(128))
    periodic_announce = Column('periodic-announce', Text)
    announce_frequency = Column('announce-frequency', Integer)
    periodic_announce_frequency = Column('periodic-announce-frequency',
                                         Integer)
    announce_round_seconds = Column('announce-round-seconds', Integer)
    announce_holdtime = Column('announce-holdtime', String(4))
    retry = Column(Integer)
    wrapuptime = Column(Integer)
    maxlen = Column(Integer)
    servicelevel = Column(Integer)
    strategy = Column(String(11))
    joinempty = Column(String(255))
    leavewhenempty = Column(String(255))
    ringinuse = Column(Integer, nullable=False, server_default='0')
    reportholdtime = Column(Integer, nullable=False, server_default='0')
    memberdelay = Column(Integer)
    weight = Column(Integer)
    timeoutrestart = Column(Integer, nullable=False, server_default='0')
    commented = Column(Integer, nullable=False, server_default='0')
    category = Column(Enum('group',
                           'queue',
                           name='queue_category',
                           metadata=Base.metadata),
                      nullable=False)
    timeoutpriority = Column(String(10), nullable=False, server_default='app')
    autofill = Column(Integer, nullable=False, server_default='1')
    autopause = Column(String(3), nullable=False, server_default='no')
    setinterfacevar = Column(Integer, nullable=False, server_default='0')
    setqueueentryvar = Column(Integer, nullable=False, server_default='0')
    setqueuevar = Column(Integer, nullable=False, server_default='0')
    membermacro = Column(String(1024))
    min_announce_frequency = Column('min-announce-frequency',
                                    Integer,
                                    nullable=False,
                                    server_default='60')
    random_periodic_announce = Column('random-periodic-announce',
                                      Integer,
                                      nullable=False,
                                      server_default='0')
    announce_position = Column('announce-position',
                               String(1024),
                               nullable=False,
                               server_default='yes')
    announce_position_limit = Column('announce-position-limit',
                                     Integer,
                                     nullable=False,
                                     server_default='5')
    defaultrule = Column(String(1024))

    groupfeatures = relationship(
        'GroupFeatures',
        primaryjoin="""and_(Queue.category == 'group',
                            Queue.name == GroupFeatures.name)""",
        foreign_keys='Queue.name',
        uselist=False,
    )

    queuefeatures = relationship(
        'QueueFeatures',
        primaryjoin="""and_(Queue.category == 'queue',
                            Queue.name == QueueFeatures.name)""",
        foreign_keys='Queue.name',
        uselist=False,
    )

    @hybrid_property
    def enabled(self):
        if self.commented is None:
            return None
        return self.commented == 0

    @enabled.setter
    def enabled(self, value):
        self.commented = int(value is False) if value is not None else None

    @hybrid_property
    def ring_in_use(self):
        return bool(self.ringinuse)

    @ring_in_use.setter
    def ring_in_use(self, value):
        self.ringinuse = int(value)

    @property
    def label(self):
        try:
            if self.category == 'group':
                return self.groupfeatures.label
            elif self.category == 'queue':
                return self.queuefeatures.displayname
        except AttributeError:
            pass
        return 'unknown'
예제 #20
0
 def _set_table(self, column, table):
     e = CheckConstraint(
         type_coerce(column, self).in_(x.value for x in self.enum),
         'valid_enum_{}'.format(column.name))
     e.info['alembic_dont_render'] = True
     assert e.table is table
예제 #21
0
 def _col_after_parent_attach(col, table):
     e = CheckConstraint(type_coerce(col, type_).in_(x.value for x in type_.enum if x not in type_.exclude_values),
                         'valid_enum_{}'.format(col.name))
     e.info['alembic_dont_render'] = True
     assert e.table is table
예제 #22
0
class SalarySettings(Base):
    # Code revision required after categories feature is added
    # Code revision required after holiday times feature is added
    # Code revision required after Shabbat times feature is added
    __tablename__ = "salary_settings"

    user_id = Column(
        Integer,
        ForeignKey("users.id"),
        primary_key=True,
    )
    # category_id = Column(
    #     Integer, ForeignKey("categories.id"), primary_key=True,
    # )
    category_id = Column(
        Integer,
        primary_key=True,
    )
    wage = Column(
        Float,
        nullable=False,
        default=SalaryConfig.MINIMUM_WAGE,
    )
    off_day = Column(
        Integer,
        CheckConstraint("0<=off_day<=6"),
        nullable=False,
        default=SalaryConfig.SATURDAY,
    )
    # holiday_category_id = Column(
    #     Integer, ForeignKey("holiday_categories.id"), nullable=False,
    #     default=SalaryConfig.ISRAELI_JEWISH,
    # )
    holiday_category_id = Column(
        Integer,
        nullable=False,
        default=SalaryConfig.ISRAELI_JEWISH,
    )
    regular_hour_basis = Column(
        Float,
        nullable=False,
        default=SalaryConfig.REGULAR_HOUR_BASIS,
    )
    night_hour_basis = Column(
        Float,
        nullable=False,
        default=SalaryConfig.NIGHT_HOUR_BASIS,
    )
    night_start = Column(
        Time,
        nullable=False,
        default=SalaryConfig.NIGHT_START,
    )
    night_end = Column(
        Time,
        nullable=False,
        default=SalaryConfig.NIGHT_END,
    )
    night_min_len = Column(
        Time,
        nullable=False,
        default=SalaryConfig.NIGHT_MIN_LEN,
    )
    first_overtime_amount = Column(
        Float,
        nullable=False,
        default=SalaryConfig.FIRST_OVERTIME_AMOUNT,
    )
    first_overtime_pay = Column(
        Float,
        nullable=False,
        default=SalaryConfig.FIRST_OVERTIME_PAY,
    )
    second_overtime_pay = Column(
        Float,
        nullable=False,
        default=SalaryConfig.SECOND_OVERTIME_PAY,
    )
    week_working_hours = Column(
        Float,
        nullable=False,
        default=SalaryConfig.WEEK_WORKING_HOURS,
    )
    daily_transport = Column(
        Float,
        CheckConstraint(f"daily_transport<={SalaryConfig.MAXIMUM_TRANSPORT}"),
        nullable=False,
        default=SalaryConfig.STANDARD_TRANSPORT,
    )

    user = relationship("User", back_populates="salary_settings")

    # category = relationship("Category", back_populates="salary_settings")
    # holiday_category =relationship("HolidayCategory",
    #                                back_populates="salary_settings")

    def __repr__(self):
        return f"<SalarySettings ({self.user_id}, {self.category_id})>"
예제 #23
0
파일: int_enum.py 프로젝트: NIIF/indico
 def _set_table(self, column, table):
     e = CheckConstraint(type_coerce(column, self).in_(x.value for x in self.enum),
                         'valid_enum_{}'.format(column.name))
     e.info['alembic_dont_render'] = True
     assert e.table is table
예제 #24
0
class UserSIP(Base):

    __tablename__ = 'usersip'

    id = Column(Integer, nullable=False)
    tenant_uuid = Column(String(36),
                         ForeignKey('tenant.uuid', ondelete='CASCADE'),
                         nullable=False)
    name = Column(String(40), nullable=False)
    type = Column(Enum('friend',
                       'peer',
                       'user',
                       name='useriax_type',
                       metadata=Base.metadata),
                  nullable=False)
    username = Column(String(80))
    secret = Column(String(80), nullable=False, server_default='')
    md5secret = Column(String(32), nullable=False, server_default='')
    context = Column(String(39))
    language = Column(String(20))
    accountcode = Column(String(20))
    amaflags = Column(Enum('default',
                           'omit',
                           'billing',
                           'documentation',
                           name='useriax_amaflags',
                           metadata=Base.metadata),
                      nullable=False,
                      server_default='default')
    allowtransfer = Column(Integer)
    fromuser = Column(String(80))
    fromdomain = Column(String(255))
    subscribemwi = Column(Integer, nullable=False, server_default='0')
    buggymwi = Column(Integer)
    call_limit = Column('call-limit',
                        Integer,
                        nullable=False,
                        server_default='10')
    callerid = Column(String(160))
    fullname = Column(String(80))
    cid_number = Column(String(80))
    maxcallbitrate = Column(Integer)
    insecure = Column(
        Enum('port',
             'invite',
             'port,invite',
             name='usersip_insecure',
             metadata=Base.metadata))
    nat = Column(
        Enum('no',
             'force_rport',
             'comedia',
             'force_rport,comedia',
             'auto_force_rport',
             'auto_comedia',
             'auto_force_rport,auto_comedia',
             name='usersip_nat',
             metadata=Base.metadata))
    promiscredir = Column(Integer)
    usereqphone = Column(Integer)
    videosupport = Column(
        Enum('no',
             'yes',
             'always',
             name='usersip_videosupport',
             metadata=Base.metadata))
    trustrpid = Column(Integer)
    sendrpid = Column(String(16))
    allowsubscribe = Column(Integer)
    allowoverlap = Column(Integer)
    dtmfmode = Column(
        Enum('rfc2833',
             'inband',
             'info',
             'auto',
             name='usersip_dtmfmode',
             metadata=Base.metadata))
    rfc2833compensate = Column(Integer)
    qualify = Column(String(4))
    g726nonstandard = Column(Integer)
    disallow = Column(String(100))
    allow = Column(Text)
    autoframing = Column(Integer)
    mohinterpret = Column(String(80))
    useclientcode = Column(Integer)
    progressinband = Column(
        Enum('no',
             'yes',
             'never',
             name='usersip_progressinband',
             metadata=Base.metadata))
    t38pt_udptl = Column(Integer)
    t38pt_usertpsource = Column(Integer)
    rtptimeout = Column(Integer)
    rtpholdtimeout = Column(Integer)
    rtpkeepalive = Column(Integer)
    deny = Column(String(31))
    permit = Column(String(31))
    defaultip = Column(String(255))
    host = Column(String(255), nullable=False, server_default='dynamic')
    port = Column(Integer)
    regexten = Column(String(80))
    subscribecontext = Column(String(80))
    vmexten = Column(String(40))
    callingpres = Column(Integer)
    parkinglot = Column(Integer)
    protocol = Column(enum.trunk_protocol,
                      nullable=False,
                      server_default='sip')
    category = Column(Enum('user',
                           'trunk',
                           name='useriax_category',
                           metadata=Base.metadata),
                      nullable=False)
    outboundproxy = Column(String(1024))
    transport = Column(String(255))
    remotesecret = Column(String(255))
    directmedia = Column(String(20))
    callcounter = Column(Integer)
    busylevel = Column(Integer)
    ignoresdpversion = Column(Integer)
    session_timers = Column(
        'session-timers',
        Enum('originate',
             'accept',
             'refuse',
             name='usersip_session_timers',
             metadata=Base.metadata))
    session_expires = Column('session-expires', Integer)
    session_minse = Column('session-minse', Integer)
    session_refresher = Column(
        'session-refresher',
        Enum('uac',
             'uas',
             name='usersip_session_refresher',
             metadata=Base.metadata))
    callbackextension = Column(String(255))
    timert1 = Column(Integer)
    timerb = Column(Integer)
    qualifyfreq = Column(Integer)
    contactpermit = Column(String(1024))
    contactdeny = Column(String(1024))
    unsolicited_mailbox = Column(String(1024))
    use_q850_reason = Column(Integer)
    encryption = Column(Integer)
    snom_aoc_enabled = Column(Integer)
    maxforwards = Column(Integer)
    disallowed_methods = Column(String(1024))
    textsupport = Column(Integer)
    commented = Column(Integer, nullable=False, server_default='0')
    _options = Column("options",
                      ARRAY(String, dimensions=2),
                      nullable=False,
                      default=list,
                      server_default='{}')

    __table_args__ = (
        PrimaryKeyConstraint('id'),
        UniqueConstraint('name'),
        Index('usersip__idx__category', 'category'),
        CheckConstraint(
            directmedia.in_(
                ['no', 'yes', 'nonat', 'update', 'update,nonat', 'outgoing'])),
    )
class ConsumableMixin(object):
    added_fat = Column(REAL, ColumnDefault(0.0), CheckConstraint("added_fat >= 0.0"))
    carbohydrates = Column(REAL, ColumnDefault(0.0), CheckConstraint("carbohydrates >= 0.0"))
    quantity = Column(REAL, CheckConstraint("quantity >= 0.0"), nullable=False)