Exemplo n.º 1
0
class EntryTag(db.Entity):
    """ Tags for an entry """
    entry = orm.Required(Entry)
    key = orm.Required(str)  # the search key

    orm.composite_key(entry, key)
    orm.composite_key(key, entry)
Exemplo n.º 2
0
class Poll(db.Entity):
    id = orm.PrimaryKey(int, size=64, auto=True)
    chat_id = orm.Required(int, size=64)
    message_id = orm.Required(int, size=64)
    accuser_id = orm.Required(int, size=64)
    accused_id = orm.Required(int, size=64)
    accused_message = orm.Optional(str, 4096)
    accused_message_id = orm.Required(int, size=64)
    reason = orm.Required(str)
    votes = orm.Set("Vote")
    orm.composite_key(chat_id, message_id)
    orm.composite_key(chat_id, accused_id)
Exemplo n.º 3
0
class Trend(db.Entity):
    _table_ = 'trends'
    id = orm.PrimaryKey(int, auto=True)
    keyword = orm.Optional(Keyword)
    timestamp = orm.Optional(int)
    articles = orm.Set('Article')
    orm.composite_key(keyword, timestamp)
Exemplo n.º 4
0
class Author(db.Entity):
    _table_ = 'authors'
    id = orm.PrimaryKey(int, auto=True)
    name = orm.Optional(str)
    website = orm.Optional(Website)
    articles = orm.Set('Article')
    orm.composite_key(name, website)
Exemplo n.º 5
0
class TagDb(db.Entity):
    _table_ = "tag"
    id = PrimaryKey(int, auto=True)
    tag_type = Required(str)
    value = Required(str)
    songs = Set(SongDb)
    composite_key(tag_type, value)
Exemplo n.º 6
0
class User(db.Entity):
    id = PrimaryKey(int, auto=True)
    uuid = Required(str)  # 唯一uuid
    name = Optional(str, volatile=True, nullable=True)  # 账户名
    avatar = Optional(str, volatile=True, nullable=True)  # 头像
    email = Required(str, volatile=True, nullable=True)  # 账户邮箱

    introduction = Optional(str, volatile=True, nullable=True)  # 介绍
    roles = Required(str, volatile=True, nullable=True)  # 角色

    phone = Required(str, volatile=True, unique=True)  # 手机号

    hashed_password = Required(str, volatile=True)
    is_active = Required(int, default="1", sql_default="1", volatile=True)
    is_visitor = Required(int, default="0", sql_default="0", volatile=True)
    is_superuser = Required(int, default="0", sql_default="0", volatile=True)

    create_time = Required(datetime,
                           default=datetime.now,
                           sql_default='CURRENT_TIMESTAMP',
                           volatile=True)
    update_time = Required(datetime,
                           default=datetime.now,
                           sql_default='CURRENT_TIMESTAMP',
                           volatile=True)

    composite_key(name, phone)
Exemplo n.º 7
0
class Tag(db.Entity):
    """Organizational tag for feed sources."""

    label: Attribute = Required(str)
    sources: Attribute = Set(SourceUserData)
    user: Attribute = Required('User')
    composite_key(label, user)
Exemplo n.º 8
0
class SongPlay(db.Entity):
    timestamp = Required(datetime.datetime)
    station = Required(str)
    title = Optional(str)  # means, can be blank, can't be NULL.
    artist = Optional(str) # means, can be blank, can't be NULL.
    # Prevent dupes
    composite_key(station, timestamp, title, artist)
Exemplo n.º 9
0
class RoundAction(db.Entity, HasPlayer):
    round = orm.Optional(Round, reverse="round_actions")
    human_player = orm.Optional("User", reverse="round_actions")
    # The index of AI player for the game
    ai_player = orm.Optional(int)
    word = orm.Optional(str)
    score_gained = orm.Optional(int)
    clicked_pass = orm.Optional(bool)
    occurred_at = orm.Optional(datetime.datetime, sql_default='CURRENT_TIMESTAMP')
    orm.composite_key(round, ai_player, human_player)

    @property
    def played_word(self) -> bool:
        return self.word is not None

    def to_dict(self):
        return {
            "humanPlayer": self.human_player.id if self.human_player is not None else None,
            "aiPlayer": self.ai_player,
            "word": self.word,
            "scoreGained": self.score_gained,
            "clickedPass": self.clicked_pass,

            # Timestamp in milliseconds since epoch.
            # Convert to JavaScript Date: new Date(<occurred_at>)
            "occurredAt": int(time.mktime(self.occurred_at.timetuple())) * 1000,
        }
Exemplo n.º 10
0
    class Result(db.Entity):
        """
        overall results of processing a dataset with some tool
        """

        dataset = Required(DataSet)
        outputs = Set(lambda: Result)
        # input processed data used, for example for refine tools
        input = Optional(lambda: Result)

        # TODO use Enum (needs type database converter?)
        result = Required(str)  # 'ok', 'error', 'pending'

        # TODO use Enum (needs type database converter?)
        tool = Required(str)  # 'autoproc', 'edna', etc

        # we support only one entry per dataset, tool and input combination,
        # as when we re-run a tool, it overwrites old results
        composite_key(dataset, tool, input)

        # dataset statistics reference, when processed with processing tool
        process_result = Optional(lambda: ProcessResult)  # type: ignore

        # structure refine statistics reference, when processed with refine tool
        refine_result = Optional(lambda: RefineResult)  # type: ignore

        # ligand fit statistics reference, when processed with ligand fitting tool
        ligfit_result = Optional(lambda: LigfitResult)  # type: ignore
Exemplo n.º 11
0
class ReactionSearchCache(metaclass=LazyEntityMeta, database='CGRdb'):
    id = PrimaryKey(int, auto=True)
    signature = Required(bytes)
    operator = Required(str)
    date = Required(datetime, default=datetime.utcnow)
    _reactions = Required(IntArray,
                          optimistic=False,
                          index=False,
                          column='reactions',
                          lazy=True)
    _tanimotos = Required(FloatArray,
                          optimistic=False,
                          index=False,
                          column='tanimotos',
                          lazy=True,
                          sql_type='real[]')
    composite_key(signature, operator)

    def reactions(self, page=1, pagesize=100):
        if page < 1:
            raise ValueError('page should be greater or equal than 1')
        elif pagesize < 1:
            raise ValueError('pagesize should be greater or equal than 1')

        start = (page - 1) * pagesize
        end = start + pagesize
        ris = select(x._reactions[start:end] for x in self.__class__
                     if x.id == self.id).first()
        if not ris:
            return []

        # preload molecules
        rs = {
            x.id: x
            for x in self._database_.Reaction.select(lambda x: x.id in ris)
        }
        rs = [rs[x] for x in ris]
        self._database_.Reaction.prefetch_structure(rs)
        return rs

    def tanimotos(self, page=1, pagesize=100):
        if page < 1:
            raise ValueError('page should be greater or equal than 1')
        elif pagesize < 1:
            raise ValueError('pagesize should be greater or equal than 1')

        start = (page - 1) * pagesize
        end = start + pagesize
        sts = select(x._tanimotos[start:end] for x in self.__class__
                     if x.id == self.id).first()
        return list(sts)

    def __len__(self):
        return self._size

    @cached_property
    def _size(self):
        return select(
            raw_sql('array_length(x.reactions, 1)') for x in self.__class__
            if x.id == self.id).first()
Exemplo n.º 12
0
class NodeResolution(db.Entity):
    node = P.Required(Node)
    run_id = P.Required(RunId)
    success = P.Required(bool)
    exception_message = P.Optional(str)
    traceback = P.Optional(str)
    P.composite_key(node, run_id)
Exemplo n.º 13
0
class Article(Entity, EntityMixins):
    '''
    Representa la entidad Artículo.
    '''

    # Definición de atributos de la entidad (Base de datos)
    id = PrimaryKey(int, auto=True)
    price = Required(float)
    name = Required(str)
    line = Required(str)
    brand = Required(str)
    provider = Required(str)
    image = Optional(str)
    composite_key(name, provider)

    # Definición de los atributos de la entidad (Scrapy)
    class ScrapyItem(scrapy.Item):
        price = scrapy.Field(input_processor=ToFloat(),
                             output_processor=TakeFirst(),
                             mandatory=True)
        name = scrapy.Field(output_processor=TakeFirst(), mandatory=True)
        line = scrapy.Field(input_processor=NameFormatter(),
                            output_processor=TakeFirst(),
                            mandatory=True)
        brand = scrapy.Field(input_processor=NameFormatter(),
                             output_processor=TakeFirst(),
                             mandatory=True)
        provider = scrapy.Field(output_processor=TakeFirst(), mandatory=True)
        image = scrapy.Field(output_processor=TakeFirst(), mandatory=False)
Exemplo n.º 14
0
class Participant(db.Entity):
    id = PrimaryKey(UUID, default=uuid4, auto=True)
    metadata = Required(Json, default={})
    created_at = Required(dt, default=lambda: dt.utcnow(), index=True)
    updated_at = Required(dt, default=lambda: dt.utcnow())
    exam = Required(Exam)
    user = Required(User)
    composite_key(user, exam)
Exemplo n.º 15
0
class CodeGroup(db.Entity):
    code = PrimaryKey(UUID, auto=True)
    group = Required(Group)
    meeting = Required(Meeting)

    code_tasks = Set("CodeTasks")
    code_files = Set("CodeFile")
    composite_key(group, meeting)
Exemplo n.º 16
0
class Entry(db.Entity):
    """An individual entry in a feed."""

    link: Attribute = Required(str)
    source: Attribute = Required('Source')
    summary: Attribute = Optional(str)
    title: Attribute = Required(str)
    updated: Attribute = Required(datetime)
    composite_key(source, link, title, updated)
Exemplo n.º 17
0
class ScrobbleDb(db.Entity):
    _table_ = "scrobble"
    id = PrimaryKey(int, auto=True)
    song = Required("SongDb")
    title = Required(str)
    artist = Required(str)
    album = Required(str)
    date = Required(datetime, volatile=True)
    composite_key(title, artist, album)
Exemplo n.º 18
0
 class FiscalNumber(db.Entity):
     _table_ = '%s_fiscal' % schema if DEBUG else (schema, 'fiscal')
     id = PrimaryKey(int, auto=True)
     sign = Required(str)
     drive = Required(str)
     document = Required(str)
     date = Required(datetime)
     seller = Required('Seller')
     composite_key(sign, drive, document)
     goods = Set('Goods')
Exemplo n.º 19
0
class MusicBrainzDetails(db.Entity):
    searched_title = Required(str)
    searched_artist = Required(str)
    musicbrainz_id = Optional(str)
    musicbrainz_json = Optional(str)
    # Only use the DECISION_[whatever] entries
    match_decision_source = Required(str, index=True)

    # Make searching on this fast + make it unique
    composite_key(searched_title, searched_artist)
Exemplo n.º 20
0
class Port(db.Entity):
    id = PrimaryKey(UUID, auto=True)
    number = Required(int, nullable=True)
    host = Required(str, nullable=True)
    permit = Required(bool)
    mode = Required(Mode)
    user = Required(User)
    force = Required(bool, default=0)
    alive = Required(bool, default=1)
    composite_key(number, host)
Exemplo n.º 21
0
class StoryComment(db.Entity):
    """ Модель комментария к рассказу """

    id = orm.PrimaryKey(int, auto=True)
    local_id = orm.Required(int)
    parent = orm.Optional('StoryComment', reverse='answers', nullable=True, default=None)
    author = orm.Optional(Author, nullable=True, default=None)
    author_username = orm.Optional(str, 64)  # На случай, если учётную запись автора удалят
    date = orm.Required(datetime, 6, default=datetime.utcnow)
    updated = orm.Required(datetime, 6, default=datetime.utcnow)
    deleted = orm.Required(bool, default=False)
    last_deleted_at = orm.Optional(datetime, 6, index=True)
    last_deleted_by = orm.Optional(Author)
    story = orm.Required(Story)
    text = orm.Optional(orm.LongStr, lazy=False)
    ip = orm.Required(str, 50, default=ipaddress.ip_address('::1').exploded)
    vote_count = orm.Required(int, size=16, unsigned=True, default=0)
    vote_total = orm.Required(int, default=0)

    # Optimizations
    tree_depth = orm.Required(int, size=16, unsigned=True, default=0)
    answers_count = orm.Required(int, size=16, unsigned=True, default=0)
    edits_count = orm.Required(int, size=16, unsigned=True, default=0)
    root_id = orm.Required(int)  # for pagination
    story_published = orm.Required(bool)
    last_edited_at = orm.Optional(datetime, 6)  # only for text updates
    last_edited_by = orm.Optional(Author)  # only for text updates

    extra = orm.Required(orm.LongStr, lazy=False, default='{}')

    votes = orm.Set('StoryCommentVote')
    edits = orm.Set('StoryCommentEdit')
    answers = orm.Set('StoryComment', reverse='parent')

    bl = Resource('bl.story_comment')

    orm.composite_key(story, local_id)
    orm.composite_index(deleted, story_published)
    orm.composite_index(author, deleted, story_published)
    orm.composite_index(story, root_id, tree_depth)

    @property
    def brief_text(self):
        return htmlcrop(self.text, current_app.config['BRIEF_COMMENT_LENGTH'])

    @property
    def text_as_html(self):
        return self.bl.text2html(self.text)

    @property
    def brief_text_as_html(self):
        return self.bl.text2html(self.brief_text)

    def before_update(self):
        self.updated = datetime.utcnow()
Exemplo n.º 22
0
class StoryTag(db.Entity):
    """ Модель, хранящая действующие теги рассказа """

    story = orm.Required('Story')
    tag = orm.Required(Tag)
    created_at = orm.Required(datetime, 6, default=datetime.utcnow)

    orm.composite_key(story, tag)

    def __repr__(self):
        return '<StoryTag: {} for {}>'.format(self.tag.name, self.story.id)
Exemplo n.º 23
0
class Submission(db.Entity):
    id = PrimaryKey(UUID, default=uuid4, auto=True)
    answer = Required(str)
    mark = Required(Mark, default=Mark.unmarked)
    marks_obtained = Required(int, default=0)
    comment = Optional(str)
    metadata = Required(Json, default={})
    created_at = Required(dt, default=lambda: dt.utcnow(), index=True)
    updated_at = Required(dt, default=lambda: dt.utcnow())
    question = Required(Question)
    user = Required(User)
    composite_key(user, question)
Exemplo n.º 24
0
class Meeting(db.Entity):
    id = PrimaryKey(UUID, auto=True)
    year = Required(int)
    date = Required(datetime)
    last_upload = Required(datetime)
    lp = Required(int)
    meeting_no = Required(int)
    check_for_deadline = Required(bool)

    composite_key(year, lp, meeting_no)
    group_meetings = Set("GroupMeeting")
    archive = Optional("ArchiveCode")
Exemplo n.º 25
0
        class TorrentTagOp(db.Entity):
            id = orm.PrimaryKey(int, auto=True)

            torrent_tag = orm.Required(lambda: TorrentTag)
            peer = orm.Required(lambda: Peer)

            operation = orm.Required(int)
            clock = orm.Required(int)
            signature = orm.Required(bytes)
            updated_at = orm.Required(datetime.datetime,
                                      default=datetime.datetime.utcnow)

            orm.composite_key(torrent_tag, peer)
Exemplo n.º 26
0
class Domain(db.Entity):
    """acl JMENO dstdomain"""
    id = PrimaryKey(UUID, auto=True)
    string = Required(str)
    mode = Required(Mode)
    user = Required('User')
    alive = Required(bool, default=True)  # aktivní?
    # admin může šahat do šablony a user má možnost si šablonu nakopírovat
    template = Required(bool, default=False)
    regexp = Required(bool, default=False)  # acl  JMENO url_regex -i
    ipaddress = Required(bool, default=False)  # acl JMENO dst
    permit = Optional(bool)
    composite_key(string, mode, user, template, regexp, ipaddress)
Exemplo n.º 27
0
class Vote(db.Entity):
    """ Модель голосований """

    author = orm.Optional(Author)
    story = orm.Optional(Story)
    date = orm.Required(datetime, 6, default=datetime.utcnow)
    updated = orm.Required(datetime, 6, default=datetime.utcnow, optimistic=False)
    ip = orm.Required(str, 50, default=ipaddress.ip_address('::1').exploded, optimistic=False)
    vote_value = orm.Required(int, default=0, optimistic=False)
    revoked_at = orm.Optional(datetime, 6)
    extra = orm.Required(orm.LongStr, lazy=False, default='{}')

    orm.composite_key(author, story)
Exemplo n.º 28
0
class Question(db.Entity):
    id = PrimaryKey(UUID, default=uuid4, auto=True)
    number = Optional(int, index=True)
    text = Required(str)
    multi_choice = Optional(StrArray)
    marks = Required(int)
    answer = Optional(str)
    metadata = Required(Json, default={})
    created_at = Required(dt, default=lambda: dt.utcnow(), index=True)
    updated_at = Required(dt, default=lambda: dt.utcnow())
    exam = Required(Exam)
    submissions = Set('Submission')
    composite_key(exam, number)
Exemplo n.º 29
0
class Node(db.Entity):
    file = P.Required(File)
    start_line = P.Required(int)
    start_column = P.Required(int)
    end_line = P.Required(int)
    end_column = P.Required(int)
    resolutions = P.Set('NodeResolution')
    P.composite_key(file, start_line, start_column, end_line, end_column)

    @staticmethod
    def parse_sloc_dict(strn):
        return dict(
            zip(['start_line', 'start_column', 'end_line', 'end_column'],
                re.split(r"\-|:", strn)))
Exemplo n.º 30
0
    class ChannelVote(db.Entity):
        """
        This ORM class represents votes cast for a channel. A single instance (row), represents a vote from a single
        peer (public key) for a single channel (ChannelMetadata entry, essentially represented by a public_key+id_
        pair). To allow only a single vote from the channel, it keeps track of when the vote was cast (vote_date)
        and what amount was used locally to bump it (last_amount).
        """

        rowid = orm.PrimaryKey(int, size=64, auto=True)
        voter = orm.Required("ChannelPeer")
        channel = orm.Required("ChannelMetadata", reverse='individual_votes')
        orm.composite_key(voter, channel)
        last_amount = orm.Optional(float, default=0.0)
        vote_date = orm.Optional(datetime, default=datetime.utcnow)