Ejemplo n.º 1
0
class Message(Base):
    __tablename__ = 'message'

    id = Column(Integer, primary_key=True)
    sender_id =  Column(Integer)
    sender_name = Column(LargeBinary(300))
    sender_username = Column(LargeBinary(200))
    sender_ip = Column(String(50))
    recipient_id = Column(Integer, ForeignKey('user.id'))
    title = Column(LargeBinary(300))
    content = Column(LargeBinary(2000))
    creation_time = Column(TIMESTAMP)
    user = relationship(User)

    @property
    def serialize(self):
        #Return object data in easily serializeable format
        return {
            'id'                : self.id,
            'sender_id'         : self.sender_id,
            'sender_name'       : self.sender_name,
            'sender_username'   : self.sender_username,
            'sender_ip'         : self.sender_ip,
            'recipient_id'      : self.recipient_id,
            'title'             : self.title,
            'content'           : self.content,
            'creation_time'     : self.creation_time
        }
Ejemplo n.º 2
0
class Picture(Base):
    __tablename__ = 'pictures'

    id = Column(String(16), primary_key=True, unique=True)
    name = Column(String(64), nullable=False)
    path = Column(String(64), server_default="", nullable=False)
    caption = Column(String(255))
    uid = Column(ForeignKey(u'people.id'), nullable=False)
    size = Column(BIGINT)
    sha1 = Column(LargeBinary(length=20))
    sha256 = Column(LargeBinary(length=32))
    thumbnail50x50 = Column(BLOB)
    format_original = Column(
        Enum('gif', 'heic', 'heif', 'ico', 'jpeg', 'mov', 'mp4', 'png', 'wmv'))
    is_encrypted = Column(BOOLEAN, nullable=False, server_default="False")
    duration = Column(Float)
    # selected EXIF fields
    compression = Column(String(16))
    datetime_original = Column(TIMESTAMP)
    gps_altitude = Column(Float)
    geolat = Column(INTEGER)
    geolong = Column(INTEGER)
    height = Column(INTEGER)
    make = Column(String(16))
    model = Column(String(32))
    orientation = Column(SMALLINT)
    #   Enum(u'Horizontal', u'Mirrored-h', u'Rotated-180',
    #        u'Mirrored-v', u'Mirrored-h-rot-270',
    #        u'Rotated-90', u'Mirrored-h-rot-90', u'Rotated-270')
    width = Column(INTEGER)

    privacy = Column(String(8), nullable=False, server_default=u'invitee')
    category_id = Column(ForeignKey(u'categories.id'), nullable=False)
    storage_id = Column(ForeignKey(u'storageitems.id'), nullable=False)
    created = Column(TIMESTAMP, nullable=False, server_default=func.now())
    modified = Column(TIMESTAMP)
    status = Column(Enum('active', u'disabled'), nullable=False)

    geo = [geolong / 1.0e7, geolat / 1.0e7]
    owner = relationship('Person',
                         foreign_keys=[uid],
                         backref=backref('picture_uid',
                                         cascade='all, delete-orphan'))
    storage = relationship('Storage')
    category = relationship('Category')

    def as_dict(self):
        retval = {
            col.name: getattr(self, col.name)
            for col in self.__table__.columns
        }
        if retval.get('sha1'):
            retval['sha1'] = retval['sha1'].hex()
        if retval.get('sha256'):
            retval['sha256'] = retval['sha256'].hex()
        if retval.get('thumbnail50x50'):
            retval['thumbnail50x50'] = (
                'data:image/%s;base64,' % retval['format_original'] +
                base64.b64encode(retval['thumbnail50x50']).decode('ascii'))
        return retval
Ejemplo n.º 3
0
    def __init__(self, client, **kwargs):
        '''
    Initialize the sql backend after timeseries has processed the configuration.
    '''
        self._metadata = MetaData()
        self._str_length = kwargs.get('string_length', 255)
        self._txt_length = kwargs.get('text_length', 32 * 1024)

        vtype = kwargs.get('value_type', float)
        if vtype in TYPE_MAP:
            self._value_type = TYPE_MAP[vtype]
            if self._value_type == String:
                self._value_type = String(self._str_length)
            elif self._value_type == Text:
                self._value_type = Text(self._txt_length)
            elif self._value_type == LargeBinary:
                self._value_type = LargeBinary(self._txt_length)

        elif issubclass(vtype, TypeEngine):
            if vtype == String:
                self._value_type = String(self._str_length)
            elif vtype == Text:
                self._value_type = Text(self._txt_length)
            elif vtype == LargeBinary:
                self._value_type = LargeBinary(self._txt_length)

        elif isinstance(vtype, TypeEngine):
            self._value_type = vtype

        else:
            raise ValueError("Unsupported type '%s'" % (vtype))

        self._table_name = kwargs.get('table_name', self._table_name)

        super(SqlBackend, self).__init__(client, **kwargs)
Ejemplo n.º 4
0
class BlockTransaction(Base):
    query = Session.query_property()

    __tablename__ = "blocktransaction"
    __table_args__ = (
        Index(
            "ix_blocktransaction_idx_block_header_hash",
            "idx",
            "block_header_hash",
            unique=True,
        ),
        Index(
            "ix_block_header_hash_transaction_hash",
            "block_header_hash",
            "transaction_hash",
            unique=True,
        ),
    )
    idx = Column(Integer, nullable=False)

    block_header_hash = Column(LargeBinary(32),
                               ForeignKey("block.header_hash"),
                               primary_key=True)
    transaction_hash = Column(LargeBinary(32),
                              ForeignKey("transaction.hash"),
                              primary_key=True)

    block = relationship("Block")
    transaction = relationship("Transaction")
Ejemplo n.º 5
0
class DbCacheTransactionNode(Base):
    """
    Link table for cache transactions and addresses
    """
    __tablename__ = 'cache_transactions_node'
    txid = Column(LargeBinary(32), ForeignKey('cache_transactions.txid'), primary_key=True)
    transaction = relationship("DbCacheTransaction", back_populates='nodes', doc="Related transaction object")
    index_n = Column(Integer, primary_key=True, doc="Order of input/output in this transaction")
    value = Column(BigInteger, default=0, doc="Value of transaction input")
    address = Column(String(255), index=True, doc="Address string base32 or base58 encoded")
    script = Column(LargeBinary, doc="Locking or unlocking script")
    witnesses = Column(LargeBinary, doc="Witnesses (signatures) used in Segwit transaction inputs")
    sequence = Column(BigInteger, default=0xffffffff,
                      doc="Transaction sequence number. Used for timelock transaction inputs")
    is_input = Column(Boolean, primary_key=True, doc="True if input, False if output")
    spent = Column(Boolean, default=None, doc="Is output spent?")
    ref_txid = Column(LargeBinary(32), index=True, doc="Transaction hash of input which spends this output")
    ref_index_n = Column(BigInteger, doc="Index number of transaction input which spends this output")

    def prev_txid(self):
        if self.is_input:
            return self.ref_txid

    def output_n(self):
        if self.is_input:
            return self.ref_index_n

    def spending_txid(self):
        if not self.is_input:
            return self.ref_txid

    def spending_index_n(self):
        if not self.is_input:
            return self.ref_index_n
Ejemplo n.º 6
0
class Account(Base):
    __tablename__ = "account"

    uid = Column(Integer, primary_key=True)
    username = Column(String(32), nullable=False, unique=True)
    email_address = Column(String(128), nullable=False, unique=True)
    password_hash = Column(LargeBinary(128), nullable=False)
    password_salt = Column(LargeBinary(16), nullable=False)

    student = relationship("Student", backref="account", uselist=False)
    faculty = relationship("Faculty", backref="account", uselist=False)

    @property
    def pw_hash(self):
        h = None
        try:
            h = self.password_hash.tobytes()
        except AttributeError:
            h = self.password_hash
        return h

    @property
    def pw_salt(self):
        s = None
        try:
            s = self.password_salt.tobytes()
        except AttributeError:
            s = self.password_salt
        return s
Ejemplo n.º 7
0
class DbCacheBlock(Base):
    """
    Block Cache Table

    Stores block headers
    """
    __tablename__ = 'cache_blocks'
    height = Column(Integer,
                    primary_key=True,
                    doc="Height or sequence number for this block")
    block_hash = Column(LargeBinary(32), index=True, doc="Hash of this block")
    network_name = Column(String(20), doc="Blockchain network name")
    version = Column(
        BigInteger,
        doc="Block version to specify which features are used (hex)")
    prev_block = Column(LargeBinary(32), doc="Block hash of previous block")
    merkle_root = Column(
        LargeBinary(32),
        doc="Merkle root used to validate transaction in block")
    time = Column(BigInteger,
                  doc="Timestamp to indicated when block was created")
    bits = Column(
        BigInteger,
        doc=
        "Encoding for proof-of-work, used to determine target and difficulty")
    nonce = Column(
        BigInteger,
        doc=
        "Nonce (number used only once or n-once) is used to create different block hashes"
    )
    tx_count = Column(Integer,
                      doc="Number of transactions included in this block")
Ejemplo n.º 8
0
class BlockUncle(Base):
    query = Session.query_property()

    __tablename__ = "blockuncle"
    __table_args__ = (
        Index(
            "ix_blockuncle_idx_block_header_hash",
            "idx",
            "block_header_hash",
            unique=True,
        ),
        Index(
            "ix_block_header_hash_uncle_hash",
            "block_header_hash",
            "uncle_hash",
            unique=True,
        ),
    )

    idx = Column(Integer, nullable=False)

    block_header_hash = Column(LargeBinary(32),
                               ForeignKey("block.header_hash"),
                               primary_key=True)
    uncle_hash = Column(LargeBinary(32),
                        ForeignKey("header.hash"),
                        primary_key=True)

    block = relationship("Block")
    uncle = relationship("Header")
Ejemplo n.º 9
0
class Usuario(Base):
    def __init__(self, nombre, email, contrasenia):
        self.nombre = nombre
        self.email = email
        self.__clave = Fernet.generate_key()
        self.__clave.decode()
        self.__token = self.__encrypt(contrasenia.encode(), self.__clave)

    def get_contrasenia(self):
        contrasenia_desencriptada = self.__decrypt(self.__token, self.__clave)
        contrasenia_desencriptada = contrasenia_desencriptada.decode("utf-8")
        return contrasenia_desencriptada

    def __encrypt(self, message: bytes, key: bytes) -> bytes:
        return Fernet(key).encrypt(message)

    def __decrypt(self, token: bytes, key: bytes) -> bytes:
        return Fernet(key).decrypt(token)

    __tablename__ = 'usuario'
    id = Column(Integer, primary_key=True, index=True, nullable=False)
    nombre = Column(String(15), index=True, nullable=False)
    email = Column(EmailType)
    __clave = Column(LargeBinary(2048), nullable=False)
    __token = Column(LargeBinary(2048), nullable=False)
Ejemplo n.º 10
0
class Receipt(Base):
    query = Session.query_property()

    __tablename__ = "receipt"

    transaction_hash = Column(LargeBinary(32),
                              ForeignKey("transaction.hash"),
                              primary_key=True)
    transaction = relationship("Transaction", back_populates="receipt")

    state_root = Column(LargeBinary(32), nullable=False)
    gas_used = Column(BigInteger, nullable=False)
    _bloom = Column(LargeBinary(1024), nullable=False)
    logs = relationship("Log", back_populates="receipt", order_by="Log.idx")

    @property
    def bloom(self) -> int:
        return big_endian_to_int(self._bloom)

    @bloom.setter
    def bloom(self, value: int) -> None:
        self._bloom = int_to_big_endian(value)

    @classmethod
    def from_ir(cls, receipt_ir: ReceiptIR,
                transaction_hash: Hash32) -> "Receipt":
        return cls(
            transaction_hash=transaction_hash,
            state_root=receipt_ir.state_root,
            gas_used=receipt_ir.gas_used,
            _bloom=receipt_ir.bloom,
        )
Ejemplo n.º 11
0
class LogTopic(Base):
    query = Session.query_property()

    __tablename__ = "logtopic"
    __table_args__ = (
        UniqueConstraint("idx",
                         "log_receipt_hash",
                         "log_idx",
                         name="ix_idx_log_receipt_hash_log_idx"),
        Index(
            "ix_idx_topic_topic_log_receipt_hash_log_idx",
            "idx",
            "topic_topic",
            "log_receipt_hash",
            "log_idx",
        ),
        ForeignKeyConstraint(("log_idx", "log_receipt_hash"),
                             ("log.idx", "log.receipt_hash")),
    )
    __mapper_args__ = {"confirm_deleted_rows": False}

    id = Column(Integer, primary_key=True)

    idx = Column(Integer, nullable=False)

    topic_topic = Column(LargeBinary(32),
                         ForeignKey("topic.topic"),
                         index=True,
                         nullable=False)
    log_idx = Column(Integer, nullable=False)
    log_receipt_hash = Column(LargeBinary(32), nullable=False)

    topic = relationship("Topic")
    log = relationship("Log", foreign_keys=[log_idx, log_receipt_hash])
Ejemplo n.º 12
0
class Thing(base):
    __tablename__ = 'things'
    thing_key = Column(String(255), primary_key=True)
    owner_id = Column(Integer(), ForeignKey('users.user_id'))
    thing_data = Column(LargeBinary(65535))
    thing_data_checksum = Column(LargeBinary(65535))
    encrypted = Column(Boolean())
Ejemplo n.º 13
0
class User(Base):
    #Table
    __tablename__ = 'user'
    #Mapper
    id = Column(Integer, primary_key=True)
    name = Column(LargeBinary(300))
    username = Column(LargeBinary(200))
    password_hash = Column(String(120))
    security_question = Column(LargeBinary(300))
    security_question_answer_hash = Column(String(120))

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)

    def hash_passw_phrase_answer(self, security_question_answer):
        self.security_question_answer_hash = pwd_context.encrypt(security_question_answer)

    def verify_passw_phrase_answer(self, security_question_answer):
        return pwd_context.verify(security_question_answer, self.security_question_answer_hash)

    @property
    def serialize(self):
        #Return object data in easily serializeable format
        return {
            'id'                            : self.id,
            'name'                          : self.name,
            'username'                      : self.username,
            'password_hash'                 : self.password_hash,
            'security_question'             : self.security_question,
            'security_question_answer_hash' : self.security_question_answer_hash
        }
Ejemplo n.º 14
0
class JCDFLOWSAVE(Base):
    __tablename__ = 'jcdflowsave'
    id = Column(Integer, primary_key=True)
    now_time = Column(String(40))
    request = Column(LargeBinary())
    response = Column(LargeBinary())
    path = Column(String(100))
    status = Column(Boolean)
Ejemplo n.º 15
0
class Parameters(Base):
    __tablename__ = 'parameters'

    id = Column(Integer, primary_key=True)
    parameters_id = Column(Integer, ForeignKey('training_data.id'))
    layer = Column(String(30))
    arr_param = Column(LargeBinary(length=(2 ** 32) - 1))
    arr_grad = Column(LargeBinary(length=(2 ** 32) - 1))
Ejemplo n.º 16
0
class PerfProfile(Model):
    __tablename__ = "perf_profiles"
    __table_args__ = (Index("perf_trace_created_on_idx", "created_on"), )

    uuid = Column(String(length=36), primary_key=True)
    plop_input = Column(LargeBinary(length=1000000), nullable=False)
    flamegraph_input = Column(LargeBinary(length=1000000), nullable=False)
    created_on = Column(DateTime, default=datetime.utcnow, nullable=False)
Ejemplo n.º 17
0
class UsbDevice(base):
    id = Column(Integer, primary_key=True)
    base_id = Column(Integer, ForeignKey('device.id'))

    vendor_id = Column(LargeBinary(length=2))
    product_id = Column(LargeBinary(length=2))

    base_device = relationship(
        "Device", back_populates="usb", single_parent=True)
Ejemplo n.º 18
0
class Word(Module):
    __tablename__ = "word"

    id = Column(BigInteger, primary_key=True, comment="单词ID")
    english = Column(String(256), unique=True, nullable=False, comment="英文")
    chinese = Column(String(256), nullable=False, comment="中文")
    phonetic_symbol = Column(String(256), comment="英标")
    img = Column(LargeBinary(length=2**16), comment="图片,二进制存储")
    audio = Column(LargeBinary(length=2**16), comment="音频,二进制存储")
Ejemplo n.º 19
0
class User(db.Model):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True, autoincrement=True)
    email = Column(String(50), unique=True, nullable=False)
    password_hash = Column(LargeBinary(128), unique=True, nullable=False)
    password_salt = Column(LargeBinary(128), unique=True, nullable=False)
    auth_token = Column(String(50), unique=True, nullable=True)

    @property
    def password(self):
        raise AttributeError("password not readable")

    @password.setter
    def password(self, password: str):
        salt = bcrypt.gensalt()
        password_bytes = bytes(password, "utf-8")
        self.password_salt = salt
        self.password_hash = bcrypt.hashpw(password_bytes, salt)

    def validate_password(self, password: str) -> bool:
        password_bytes = bytes(password, "utf-8")
        password_hash = bcrypt.hashpw(password_bytes, self.password_salt)
        is_valid = safe_str_cmp(password_hash, self.password_hash)
        return is_valid

    def messages(
        self,
        status: MessageFetchRequestStatus,
        inbox_outbox: Literal["inbox", "outbox"],
    ) -> Query:
        query: Query = MessagesUsers.query.join(MessagesUsers.message).filter(
            MessagesUsers.viewer_id == self.id
        )
        if inbox_outbox == "inbox":
            query = query.filter(Message.receiver_id == self.id)
        elif inbox_outbox == "outbox":
            query = query.filter(Message.sender_id == self.id)
        else:
            raise ValueError(f"Wrong value for {inbox_outbox=}")
        if status == MessageFetchRequestStatus.all_read:
            query = query.filter(Message.is_read == True)
        elif status == MessageFetchRequestStatus.all_unread:
            query = query.filter(Message.is_read == False)
        return query

    @classmethod
    def get_by_id(cls, user_id: str) -> Optional["User"]:
        return cls.query.filter(User.id == user_id).first()

    @classmethod
    def get_by_email(cls, email: str) -> Optional["User"]:
        return cls.query.filter(User.email == email).first()

    @classmethod
    def get_by_token(cls, auth_token: str) -> Optional["User"]:
        return cls.query.filter(auth_token == User.auth_token).first()
Ejemplo n.º 20
0
class ExampleSentence(Module):
    __tablename__ = "example_sentence"

    id = Column(BigInteger, primary_key=True, comment="单词例句ID")
    word_id = Column(BigInteger, ForeignKey("word.id", ondelete="CASCADE"), index=True, nullable=False, comment="单词ID")
    word = relationship("Word", backref="*example_sentence_from_word*")
    english = Column(Text, comment="例句英文")
    chinese = Column(Text, comment="例句中文")
    img = Column(LargeBinary(length=2**16), comment="图片,二进制存储")
    audio = Column(LargeBinary(length=(2**32)-1), comment="音频,二进制存储")
Ejemplo n.º 21
0
class Log(Base):
    query = Session.query_property()

    __tablename__ = "log"
    __table_args__ = (UniqueConstraint("idx",
                                       "receipt_hash",
                                       name="ix_idx_receipt_hash"), )

    id = Column(Integer, primary_key=True)
    idx = Column(Integer, nullable=False)

    receipt_hash = Column(
        LargeBinary(32),
        ForeignKey("receipt.transaction_hash"),
        index=True,
        nullable=False,
    )
    receipt = relationship("Receipt", back_populates="logs")

    address = Column(LargeBinary(20), index=True, nullable=False)
    topics = relationship("Topic", secondary="logtopic", order_by=LogTopic.idx)
    data = Column(LargeBinary, nullable=False)

    def __repr__(self) -> str:
        return (f"Log("
                f"idx={self.idx!r}, "
                f"receipt_hash={self.receipt_hash!r}, "
                f"address={self.address!r}, "
                f"data={self.data!r}, "
                f"topics={self.topics!r}"
                f")")

    def __str__(self) -> str:
        # TODO: use eth_utils.humanize_bytes once it is released
        if len(self.data) > 4:
            pretty_data = humanize_hash(Hash32(self.data))
        else:
            pretty_data = self.data.hex()

        if len(self.topics) == 0:  # type: ignore
            pretty_topics = "(anonymous)"
        else:
            pretty_topics = "|".join((
                humanize_hash(Hash32(topic.topic))
                for topic in self.topics  # type: ignore
            ))

        return f"Log[#{self.idx} A={humanize_hash(self.address)} D={pretty_data}/T={pretty_topics}]"  # type: ignore  # noqa: E501

    @classmethod
    def from_ir(cls, log_ir: LogIR, idx: int, receipt_hash: Hash32) -> "Log":
        return cls(idx=idx,
                   receipt_hash=receipt_hash,
                   address=log_ir.address,
                   data=log_ir.data)
Ejemplo n.º 22
0
class User(Base, _Exportable):
    __tablename__ = 'users'
    __summary_keys__ = ['id', 'name', 'created', 'admin']
    id = Column(String, primary_key=True)
    name = Column(String, nullable=False)
    salt = Column(LargeBinary(32), nullable=False)
    password = Column(LargeBinary(32), nullable=False)
    admin = Column(Boolean, server_default='False')
    created = Column(DateTime(timezone=True),
                     server_default=func.now(),
                     nullable=False)
Ejemplo n.º 23
0
class User(BASE):
    '''
    AraoSecret user.
    '''
    __tablename__ = 'user'

    id = Column('id', Integer, primary_key=True)
    alias = Column(String(32), nullable=False, unique=True)
    email = Column(String(128), nullable=False)
    email_validated = Column(Boolean, default=False)
    pass_hash = Column(LargeBinary(64), nullable=False)
    rsa_key = Column(LargeBinary(3310), nullable=False)
    rsa_key_pub = Column(LargeBinary(799), nullable=False)

    def __init__(self, alias, email, password):
        self.alias = alias
        self.email = email
        self.pass_hash = arao_secret.helper.get_pass_hash(password)
        # RSA
        rsa_key = RSA.generate(4096)
        self.rsa_key = rsa_key.exportKey(passphrase=password)
        self.rsa_key_pub = rsa_key.publickey().exportKey()
        # TODO : Clean rsa_key from memory

    def __repr__(self):
        return '{}, {}'.format(self.id, self.alias)

    def decrypt(self, password, text_enc):
        rsa_key = RSA.importKey(self.rsa_key, passphrase=password)
        text = rsa_key.decrypt(text_enc)
        # TODO : Clean rsa_key from memory
        return text

    def encrypt(self, text):
        rsa_key = RSA.importKey(self.rsa_key_pub)
        text_enc = rsa_key.encrypt(text, None)[0]
        SecureString.clearmem(text)
        return text_enc

    def get_group(self, id):
        '''
        Get Group, Group key tuple.
        '''
        for group_key in self.group_keys:
            if group_key.group.id == id:
                return group_key.group, group_key
        return None

    def get_groups(self):
        groups = list()
        for group_key in self.group_keys:
            groups.append(group_key.group)
        # TODO : Sort by name
        return groups
Ejemplo n.º 24
0
class User(base):
    __tablename__ = 'users'
    user_id = Column(Integer(), primary_key=True)
    user_name = Column(String(32), unique=True)
    password_hash = Column(LargeBinary(64))
    password_salt = Column(LargeBinary(64))
    encryption_salt = Column(LargeBinary(64))
    email = Column(
        String(254)
    )  # Apparently the maximum usable email address length, see https://7php.com/the-maximum-length-limit-of-an-email-address-is-254-not-320/#:~:text=there%20is%20a%20length%20limit,total%20length%20of%20320%20characters.

    things = backref("Thing", back_populates="owner")
Ejemplo n.º 25
0
 def test_binary_types(self):
     specs = [
         (LargeBinary(3), mysql.TINYBLOB()),
         (LargeBinary(), mysql.BLOB()),
         (mysql.MSBinary(3), mysql.MSBinary(3)),
         (mysql.MSVarBinary(3), mysql.MSVarBinary(3)),
         (mysql.MSTinyBlob(), mysql.MSTinyBlob()),
         (mysql.MSBlob(), mysql.MSBlob()),
         (mysql.MSBlob(1234), mysql.MSBlob()),
         (mysql.MSMediumBlob(), mysql.MSMediumBlob()),
         (mysql.MSLongBlob(), mysql.MSLongBlob()),
     ]
     self._run_test(specs, [])
Ejemplo n.º 26
0
class Frame(Base):
    __tablename__ = "local_features_frame"
    id = Column('id', Integer, primary_key=True)
    video_id = Column('video_id',
                      Integer,
                      ForeignKey(Video.id),
                      nullable=False)
    frame_number = Column('frame_number', Integer, nullable=False)
    key_points = Column('key_points', LargeBinary((2**32) - 1), nullable=False)
    descriptors = Column('descriptors',
                         LargeBinary((2**32) - 1),
                         nullable=False)
    video = relationship(Video)
Ejemplo n.º 27
0
class LogTopic(Base):
    query = Session.query_property()

    __tablename__ = "logtopic"
    __table_args__ = (
        UniqueConstraint(
            "idx",
            "log_idx",
            "log_transaction_hash",
            "log_block_header_hash",
            name="ix_idx_log_idx_log_transaction_hash_log_block_header_hash",
        ),
        Index(
            "ix_idx_topic_topic_log_idx_log_transaction_hash_log_block_header_hash",
            "idx",
            "topic_topic",
            "log_idx",
            "log_transaction_hash",
            "log_block_header_hash",
        ),
        ForeignKeyConstraint(
            ("log_idx", "log_transaction_hash", "log_block_header_hash"),
            ("log.idx", "log.transaction_hash", "log.block_header_hash"),
        ),
        CheckConstraint("idx >= 0 AND idx <= 3",
                        name="_limit_4_topics_per_log"),
    )
    __mapper_args__ = {"confirm_deleted_rows": False}

    idx = Column(Integer, nullable=False, primary_key=True)

    topic_topic = Column(LargeBinary(32),
                         ForeignKey("topic.topic"),
                         index=True,
                         nullable=False)
    log_idx = Column(Integer, nullable=False, primary_key=True)
    log_transaction_hash = Column(LargeBinary(32),
                                  nullable=False,
                                  index=True,
                                  primary_key=True)
    log_block_header_hash = Column(LargeBinary(32),
                                   nullable=False,
                                   index=True,
                                   primary_key=True)

    topic = relationship("Topic")
    log = relationship(
        "Log",
        foreign_keys=[log_idx, log_transaction_hash, log_block_header_hash])
Ejemplo n.º 28
0
class Variable(Base):
    __tablename__ = "pyri_variables"
    __table_args__ = (UniqueConstraint('name', 'device', name='_unique_var'), )
    id = Column(Integer(), primary_key=True)
    name = Column(String(512), index=True)
    device = Column(String(128))
    datatype = Column(String(128))
    value = Column(LargeBinary())
    reset_value = Column(LargeBinary(), default=None)
    persistence = Column(Integer(), default=VariablePersistence.TEMPORARY)
    default_protection = Column(Integer(),
                                default=VariableProtectionLevel.READ_WRITE)
    doc = Column(Text())
    created_on = Column(LargeBinary())  # com.robotraconteur.datetime.TimeSpec2
    updated_on = Column(LargeBinary())  # com.robotraconteur.datetime.TimeSpec2
Ejemplo n.º 29
0
class TimestampSequencedWithIDRecord(Base):
    __tablename__ = "timestamp_sequenced_items"

    # Record ID.
    id = Column(
        BigInteger().with_variant(Integer, "sqlite"),
        primary_key=True,
        index=True,
        unique=True,
        autoincrement=True,
    )

    # Sequence ID (e.g. an entity or aggregate ID).
    sequence_id = Column(UUIDType(), nullable=False)

    # Position (timestamp) of item in sequence.
    position = Column(DECIMAL(24, 6, 6), nullable=False, unique=False)

    # Topic of the item (e.g. path to domain event class).
    topic = Column(Text(), nullable=False)

    # State of the item (serialized dict, possibly encrypted).
    state = Column(LargeBinary())

    __table_args__ = (
        Index(
            "timestamp_sequenced_items_sequence_id_position_index",
            "sequence_id",
            "position",
            unique=True,
        ),
        Index("timestamp_sequenced_items_position_index", "position", unique=False),
    )
Ejemplo n.º 30
0
class Resource(Base, ColumnPrinterMixin):
    __tablename__ = 'resources'
    resource_id = Column(Integer,
                         Sequence('resource_id_seq'),
                         primary_key=True,
                         unique=True)  # type: ResourceID
    resource_name = Column(String(255), unique=True,
                           nullable=False)  # type: ResourceName
    resource_size = Column(BigInteger)  # type: ResourceSize
    resource_payloadsize = Column(BigInteger)  # type: ResourcePayloadSize
    resource_hash = Column(LargeBinary(64), unique=True)  # type: ResourceHash
    wrapping_type = Column(String(255))  # type: ResourceWrappingType
    compression_type = Column(String(255))  # type: ResourceCompressionType
    __table_args__ = (UniqueConstraint('resource_name', 'resource_hash'), )

    def __init__(self, resource_name, resource_size, resource_payloadsize,
                 resource_hash, wrapping_type, compression_type):
        # type: (ResourceName, ResourceSize, ResourcePayloadSize, ResourceHash, ResourceWrappingType, ResourceCompressionType) -> None
        self.resource_name = resource_name  # name of uploaded file/image/...
        self.resource_size = resource_size  # the size of the uploaded resource
        self.resource_payloadsize = resource_payloadsize  # the size of the uploaded resource, without encapsulation
        self.resource_hash = resource_hash  # the hash of the uploaded resource, for checking correct download
        self.wrapping_type = wrapping_type  # used for extraction of block payload from resource
        self.compression_type = compression_type  # used for extraction of block payload from resource

    @classmethod
    def makeResourceHash(cls, resource_data):
        # type: (bytes) -> ResourceHash
        return ResourceHash(hashlib.sha256(resource_data).digest())