def upgrade():
    op.create_table('workflows',
    sa.Column('id', UUIDType(binary=False), nullable=False),
    sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
    sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
    sa.Column('name', sa.String(), nullable=False),
    sa.Column('project', sa.String(), nullable=False),
    sa.Column('status', sa.Enum('pending', 'progress', 'success', 'error', 'canceled', name='statustype'), nullable=False),
    sa.Column('payload', JSONBType(), nullable=True),
    sa.Column('periodic', sa.Boolean(), nullable=True),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_workflows'))
    )
    op.create_index(op.f('ix_workflows_created_at'), 'workflows', ['created_at'], unique=False)

    op.create_table('tasks',
    sa.Column('id', UUIDType(binary=False), nullable=False),
    sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
    sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
    sa.Column('key', sa.String(), nullable=False),
    sa.Column('status', sa.Enum('pending', 'progress', 'success', 'error', 'canceled', name='statustype'), nullable=False),
    sa.Column('previous', JSONBType(), nullable=True),
    sa.Column('workflow_id', UUIDType(binary=False), nullable=False),
    sa.ForeignKeyConstraint(['workflow_id'], ['workflows.id'], name=op.f('fk_tasks_workflow_id_workflows')),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_tasks'))
    )
    op.create_index(op.f('ix_tasks_created_at'), 'tasks', ['created_at'], unique=False)
Exemplo n.º 2
0
def upgrade():
    op.create_table(
        "workflows",
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("project", sa.String(255), nullable=False),
        sa.Column(
            "status",
            sa.Enum("pending",
                    "progress",
                    "success",
                    "error",
                    "canceled",
                    name="statustype"),
            nullable=False,
        ),
        sa.Column("payload", JSONBType(), nullable=True),
        sa.Column("periodic", sa.Boolean(), nullable=True),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_workflows")),
    )
    op.create_index(op.f("ix_workflows_created_at"),
                    "workflows", ["created_at"],
                    unique=False)

    op.create_table(
        "tasks",
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("key", sa.String(255), nullable=False),
        sa.Column(
            "status",
            sa.Enum("pending",
                    "progress",
                    "success",
                    "error",
                    "canceled",
                    name="statustype"),
            nullable=False,
        ),
        sa.Column("previous", JSONBType(), nullable=True),
        sa.Column("workflow_id", UUIDType(binary=False), nullable=False),
        sa.ForeignKeyConstraint(
            ["workflow_id"],
            ["workflows.id"],
            name=op.f("fk_tasks_workflow_id_workflows"),
        ),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_tasks")),
    )
    op.create_index(op.f("ix_tasks_created_at"),
                    "tasks", ["created_at"],
                    unique=False)
Exemplo n.º 3
0
 def id(cls):
     """
     Database identity for this model, used for foreign key references from other models
     """
     if cls.__uuid_primary_key__:
         return Column(UUIDType(binary=False), default=uuid1mc, primary_key=True)
     else:
         return Column(Integer, primary_key=True)
Exemplo n.º 4
0
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(UUIDType(binary=False), primary_key=True, default=uuid4)
    email = db.Column(EmailType, unique=True, nullable=False)
    password = db.Column(db.String(512), nullable=False)
    name = db.Column(db.String(512))

    def to_dict(self):
        return {'id': self.id.hex, 'name': self.name}
Exemplo n.º 5
0
class Seller(Base):
    __tablename__ = "sellers"

    id = Column(UUIDType(binary=False), primary_key=True, default=create_uuid)
    name = Column(String(255))
    cpf = Column(String(11), unique=True, index=True)
    email = Column(String(255), unique=True, index=True)
    password = Column(
        PasswordType(schemes=["pbkdf2_sha512", "md5_crypt"],
                     deprecated=["md5_crypt"]))
Exemplo n.º 6
0
 def uuid(cls):
     """UUID column, or synonym to existing :attr:`id` column if that is a UUID"""
     if hasattr(cls, '__uuid_primary_key__') and cls.__uuid_primary_key__:
         return synonym('id')
     else:
         return immutable(
             Column(UUIDType(binary=False),
                    default=uuid_.uuid4,
                    unique=True,
                    nullable=False))
Exemplo n.º 7
0
class Order(Base):
    __tablename__ = "orders"

    id = Column(UUIDType(binary=False), primary_key=True, default=create_uuid)
    cpf = Column(String(11), index=True)
    code = Column(String(255))
    amount = Column(Float(asdecimal=True))
    timestamp = Column(DateTime())
    status = Column(String(255), default="")
    cashback_percentage = Column(Integer(), default=0)
    cashback_amount = Column(Float(asdecimal=True), default=0)
def upgrade():
    op.create_table(
        "users",
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("username", sa.String(255), nullable=False),
        sa.Column("password", sa.String(255), nullable=False),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_users")),
        sa.UniqueConstraint("username", name=op.f("uq_users_username")),
    )
    op.create_index(op.f("ix_users_created_at"), "users", ["created_at"], unique=False)
Exemplo n.º 9
0
class Feature(db.Model):
    __tablename__ = "features"
    id = db.Column(UUIDType(), default=uuid.uuid4, primary_key=True)
    title = db.Column(db.String(64), default='No Title', index=True)
    description = db.Column(db.String(120), default='No Description')
    client = db.Column(db.String(64), default='No Client')
    client_priority = db.Column(db.Integer(), default='0')
    target_date = db.Column(db.DateTime(), default='2000-01-01 00:00:00')
    product_area = db.Column(db.String(64), default='Policies')

    def __repr__(self):
        return '<Feature {}>'.format(self.title)
Exemplo n.º 10
0
 def id(cls):  # NOQA: A003
     """
     Database identity for this model, used for foreign key references from other models
     """
     if cls.__uuid_primary_key__:
         return immutable(
             Column(
                 UUIDType(binary=False),
                 default=uuid_.uuid4,
                 primary_key=True,
                 nullable=False,
             ))
     else:
         return immutable(Column(Integer, primary_key=True, nullable=False))
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "users",
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("username", sa.String(), nullable=False),
        sa.Column("password", sa.String(), nullable=False),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_users")),
        sa.UniqueConstraint("username", name=op.f("uq_users_username")),
    )
    op.create_index(op.f("ix_users_created_at"),
                    "users", ["created_at"],
                    unique=False)
class Property(Base):
    __tablename__ = 'property'
    __table_args__ = (
        CheckConstraint('NOT(prop_resource IS NULL AND '
                        'prop_string IS NULL AND '
                        'prop_datetime IS NULL AND '
                        'prop_integer IS NULL AND '
                        'prop_url IS NULL'),
    )

    id = Column(UUIDType(), primary_key=True)
    resource_id = Column(BigInteger, ForeignKey("resource.ori_id"), nullable=False)
    predicate = Column(String, nullable=False)
    order = Column(SmallInteger, nullable=True)
    prop_resource = Column(BigInteger, ForeignKey("resource.ori_id"), nullable=True)
    prop_string = Column(String, nullable=True)
    prop_datetime = Column(DateTime, nullable=True)
    prop_integer = Column(BigInteger, nullable=True)
    prop_url = Column(String, nullable=True)

    resource = relationship("Resource", back_populates="properties", foreign_keys=resource_id)
Exemplo n.º 13
0
class Event(db.Model):
    __tablename__ = 'events'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(128), nullable=False, unique=True)
    category_id = db.Column(db.Integer, db.ForeignKey('event_categories.id'))
    generator_id = db.Column(db.Integer, db.ForeignKey('event_generators.id'))
    created_at = db.Column(db.DateTime, nullable=False, default=timezone.now)
    start_at = db.Column(db.DateTime, nullable=False)
    finish_at = db.Column(db.DateTime, nullable=False)
    payload = db.Column(JSONType, nullable=False, default={})
    is_active = db.Column(db.Boolean, nullable=False, default=True)

    on_start_task_id = db.Column(UUIDType(binary=False))
    on_finish_task_id = db.Column(UUIDType(binary=False))

    participations = db.relationship('EventParticipation', backref='event', lazy='dynamic')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.Schema = self.get_schema_class()

    @classmethod
    def get_schema_class(cls):
        class _Schema(ma.Schema):
            class Meta:
                model = cls
                fields = ('id', 'start_at', 'finish_at', 'payload', 'category')

        return _Schema

    def dumps(self) -> dict:
        return self.Schema().dump(self).data

    @hybrid_property
    def active(self) -> bool:
        return self.finish_at > timezone.now() >= self.start_at and self.is_active

    @active.expression
    def active(cls) -> bool:
        return db.and_(
            cls.finish_at > timezone.now(),
            cls.start_at <= timezone.now(),
            cls.is_active
        )

    @hybrid_property
    def started(self) -> bool:
        return self.start_at >= timezone.now()

    @hybrid_property
    def finished(self) -> bool:
        return self.finish_at < timezone.now()

    @hybrid_property
    def start_in(self) -> Optional[timedelta]:
        if self.start_at >= timezone.now():
            return self.start_at - timezone.now()

    @hybrid_property
    def finish_in(self) -> Optional[timedelta]:
        if self.finish_at >= timezone.now():
            return self.finish_at - timezone.now()

    async def on_start(self) -> None:
        # TODO: bulk get_users request
        for p in self.participations:
            user = await p.get_user()
            msg = {
                'type': EventStatus.STARTED.name,
                'data': self.dumps()
            }
            await user.send_message(message=json.dumps(msg),
                                    content_type='application/json')

    async def on_finish(self) -> None:
        # TODO: bulk get_users request
        for p in self.participations:
            user = await p.get_user()
            msg = {
                'type': EventStatus.FINISHED.name,
                'data': self.dumps()
            }
            await user.send_message(message=json.dumps(msg),
                                    content_type='application/json')

    @as_future
    def join(self, user_id: str) -> None:
        EventParticipation.create(user_id=user_id, event_id=self.id, status='joined')

    @as_future
    def leave(self, user_id: str) -> None:
        kwargs = dict(user_id=user_id, event_id=self.id, status='joined')
        p = EventParticipation.query.filter_by(**kwargs).first()
        if p is not None:
            p.status = 'leaved'
            p.save()
        else:
            logger.warning('User (%s) is not joined to event (%s), '
                           'so cannot leave.' % (user_id, self.id))
Exemplo n.º 14
0
def upgrade():
    op.create_table(
        'user', sa.Column('id', UUIDType(), nullable=False),
        sa.Column('avatar', sa.String(length=256), nullable=True),
        sa.Column('display_name', sa.Unicode(length=128), nullable=False),
        sa.Column('email', sa.String(length=128), nullable=False),
        sa.Column('moderator', sa.Boolean(), nullable=False),
        sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email'))
    op.create_table('tournament', sa.Column('id', UUIDType(), nullable=False),
                    sa.Column('begin_at', sa.DateTime(), nullable=False),
                    sa.Column('finish_at', sa.DateTime(), nullable=False),
                    sa.Column('final_match_id', UUIDType()),
                    sa.PrimaryKeyConstraint('id'))
    op.create_table(
        'submission', sa.Column('id', UUIDType(), nullable=False),
        sa.Column('tournament_id', UUIDType(), nullable=False),
        sa.Column('user_id', UUIDType(), nullable=False),
        sa.Column('code', sa.Text(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=False),
        sa.ForeignKeyConstraint(
            ['tournament_id'],
            ['tournament.id'],
        ), sa.ForeignKeyConstraint(
            ['user_id'],
            ['user.id'],
        ), sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('tournament_id', 'user_id', name='uc_submission'))
    op.create_table(
        'tournament_match_set', sa.Column('id', UUIDType(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=False),
        sa.Column('tournament_id', UUIDType(), nullable=False),
        sa.Column('final_match_id', UUIDType()),
        sa.ForeignKeyConstraint(
            ['tournament_id'],
            ['tournament.id'],
        ), sa.PrimaryKeyConstraint('id'))
    op.create_table(
        'tournament_match_set_item', sa.Column('id',
                                               UUIDType(),
                                               nullable=False),
        sa.Column('tournament_match_set_id', UUIDType(), nullable=False),
        sa.Column('submission_id', UUIDType(), nullable=False),
        sa.ForeignKeyConstraint(
            ['submission_id'],
            ['submission.id'],
        ),
        sa.ForeignKeyConstraint(
            ['tournament_match_set_id'],
            ['tournament_match_set.id'],
        ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('submission_id'))
    op.create_table(
        'match', sa.Column('id', UUIDType(), nullable=False),
        sa.Column('p1_id', UUIDType(), nullable=False),
        sa.Column('p1_parent_id', UUIDType(), nullable=True),
        sa.Column('p2_id', UUIDType(), nullable=False),
        sa.Column('p2_parent_id', UUIDType(), nullable=True),
        sa.Column('winner_id', UUIDType(), nullable=True),
        sa.Column('iteration', sa.Integer(), nullable=False),
        sa.Column('match_data',
                  postgresql.JSON(astext_type=sa.Text()),
                  nullable=False),
        sa.Column('disclosed', sa.Boolean(), nullable=False),
        sa.ForeignKeyConstraint(
            ['p1_id'],
            ['tournament_match_set_item.id'],
        ), sa.ForeignKeyConstraint(
            ['p1_parent_id'],
            ['match.id'],
        ),
        sa.ForeignKeyConstraint(
            ['p2_id'],
            ['tournament_match_set_item.id'],
        ), sa.ForeignKeyConstraint(
            ['p2_parent_id'],
            ['match.id'],
        ),
        sa.ForeignKeyConstraint(
            ['winner_id'],
            ['tournament_match_set_item.id'],
        ), sa.PrimaryKeyConstraint('id'))
    op.create_foreign_key('fk_tournament_final_match_id', 'tournament',
                          'match', ['final_match_id'], ['id'])
    op.create_foreign_key('fk_tournament_match_set_final_match_id',
                          'tournament_match_set', 'match', ['final_match_id'],
                          ['id'])
Exemplo n.º 15
0
class SurrogateUuidPK(object):
    """A mixin that adds a surrogate UUID 'primary key' column named
    ``id`` to any declarative-mapped class."""

    id = Column(UUIDType(binary=False), primary_key=True)