Exemplo n.º 1
0
class ResyncLogs(db.Model, Timestamp):
    """Harvest Logs."""

    __tablename__ = "resync_logs"

    id = db.Column(db.Integer, primary_key=True)

    resync_indexes_id = db.Column(
        db.Integer,
        db.ForeignKey(ResyncIndexes.id,
                      ondelete='CASCADE'),
        nullable=True
    )
    log_type = db.Column(db.String(10))

    task_id = db.Column(db.String(40), default=None)

    start_time = db.Column(db.DateTime, default=datetime.now())

    end_time = db.Column(db.DateTime, nullable=True)

    status = db.Column(db.String(10), nullable=False, default='Running')

    errmsg = db.Column(db.String(255), nullable=True, default=None)

    counter = db.Column(
        db.JSON().with_variant(
            postgresql.JSONB(none_as_null=True),
            'postgresql',
        ).with_variant(
            JSONType(),
            'sqlite',
        ).with_variant(
            JSONType(),
            'mysql',
        ),
        default=lambda: dict(),
        nullable=True
    )

    resync_index = db.relationship(
        ResyncIndexes,
        backref='resync_indexes_id',
        foreign_keys=[resync_indexes_id])
    """Relation to the Resync Identifier."""
class GitSnapshot(db.Model):
    """Snapshot information for a Git repo."""

    __tablename__ = 'git_snapshot'

    id = db.Column(db.Integer, primary_key=True)

    # webhook payload / event
    payload = db.Column(json_type, default={}, nullable=True)

    # git specifics
    tag = db.Column(db.String(255), nullable=True)
    ref = db.Column(db.String(255), nullable=True)

    # foreign keys (connecting to repo and events)
    webhook_id = db.Column(db.Integer,
                           db.ForeignKey(GitWebhook.id),
                           nullable=False)
    webhook = db.relationship(GitWebhook,
                              backref=db.backref("snapshots",
                                                 cascade="all, delete-orphan"))
    created = db.Column(db.DateTime, server_default=db.func.now())

    @staticmethod
    def create(webhook, data):
        snapshot = GitSnapshot(payload=data,
                               webhook_id=webhook.id,
                               tag=data['commit'].get('tag'),
                               ref=data['commit']['id'])
        db.session.add(snapshot)
        db.session.commit()
Exemplo n.º 3
0
class SIPMetadataType(db.Model):
    """Type of the metadata added to an SIP.

    The type describes the type of file along with an eventual schema used to
    validate the structure of the content.
    """

    __tablename__ = 'sipstore_sipmetadatatype'

    id = db.Column(db.Integer(), primary_key=True)
    """ID of the SIPMetadataType object."""

    title = db.Column(db.String(255), nullable=False)
    """The title of type of metadata (i.e. 'Invenio JSON Record v1.0.0')."""

    name = db.Column(db.String(255), nullable=False, unique=True)
    """The unique name tag of the metadata type."""

    format = db.Column(db.String(255), nullable=False)
    """The format of the metadata (xml, json, txt...).

    This is used as the extension of the created file during an export.
    """

    schema = db.Column(db.String(1024), nullable=True, unique=True)
    """URI to a schema that describes the metadata (json or xml schema)."""
    @classmethod
    def get(cls, id):
        """Return the corresponding SIPMetadataType."""
        return cls.query.filter_by(id=id).one()

    @classmethod
    def get_from_name(cls, name):
        """Return the corresponding SIPMetadataType."""
        return cls.query.filter_by(name=name).one()

    @classmethod
    def get_from_schema(cls, schema):
        """Return the corresponding SIPMetadataType."""
        return cls.query.filter_by(schema=schema).one()
Exemplo n.º 4
0
Arquivo: models.py Projeto: vypha/weko
class WorkFlow(db.Model, TimestampMixin):
    """define WorkFlow"""

    __tablename__ = 'workflow_workflow'

    id = db.Column(db.Integer(), nullable=False,
                   primary_key=True, autoincrement=True)
    """Flows identifier."""

    flows_id = db.Column(
        UUIDType,
        nullable=False,
        unique=True,
        index=True,
        default=uuid.uuid4()
    )
    """the id of flows."""

    flows_name = db.Column(
        db.String(255), nullable=True, unique=False, index=False)
    """the name of flows."""

    itemtype_id = db.Column(
        db.Integer(), db.ForeignKey(ItemType.id), nullable=False, unique=False)
    """the id of itemtype."""

    itemtype = db.relationship(
        ItemType,
        backref=db.backref('workflow', lazy='dynamic',
                           order_by=desc('item_type.tag'))
    )

    flow_id = db.Column(db.Integer(), db.ForeignKey(FlowDefine.id),
                        nullable=False, unique=False)
    """the id of flow."""

    flow_define = db.relationship(
        FlowDefine,
        backref=db.backref('workflow', lazy='dynamic')
    )
Exemplo n.º 5
0
class DataResource(db.Model):
    """
    Details of a data resource, which could be a data table, an image, a
    script, a ROOT file, or a link to an external website or GitHub repo.

    Data resources can be related to submissions in various ways:

    - Resources relating to a submission (HEPSubmission.resources) are linked
      via the `data_resource_link` table
    - Data files belonging to a data table (`DataSubmission.data_file`)
      are linked via the `data_file` field of `datasubmission`
    - Resources relating to a data table (`DataSubmission.resources`) are
      linked via the `datafile_identifier` table
    """
    __tablename__ = "dataresource"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    file_location = db.Column(db.String(256))
    file_type = db.Column(db.String(64), default="json")
    file_description = db.Column(LargeBinaryString)

    file_license = db.Column(db.Integer,
                             db.ForeignKey("hepdata_license.id"),
                             nullable=True)

    created = db.Column(db.DateTime,
                        nullable=False,
                        default=datetime.utcnow,
                        index=True)
Exemplo n.º 6
0
class ApiHarvestConfig(RecordIdentifier):
    """Sequence generator for Document identifiers."""

    __tablename__ = 'apiharvest_config'
    __mapper_args__ = {'concrete': True}

    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(255), nullable=False, server_default='')
    name = db.Column(db.String(255), nullable=False)
    classname = db.Column(db.String(255), nullable=False)
    code = db.Column(db.Text, nullable=True)
    lastrun = db.Column(db.DateTime,
                        default=datetime.datetime(year=1900, month=1, day=1),
                        nullable=True)

    def save(self):
        """Save object to persistent storage."""
        with db.session.begin_nested():
            db.session.merge(self)

    def update_lastrun(self, new_date=None):
        """Update the 'lastrun' attribute of object to now."""
        self.lastrun = new_date or datetime.datetime.now()
        self.save()
        db.session.commit()
Exemplo n.º 7
0
Arquivo: models.py Projeto: vypha/weko
class FlowActionRole(db.Model, TimestampMixin):
    """FlowActionRole list belong to FlowAction

    It relates an allowed action with a role or a user
    """

    __tablename__ = 'workflow_flow_action_role'

    id = db.Column(db.Integer(), nullable=False,
                   primary_key=True, autoincrement=True)
    """FlowAction identifier."""

    flow_action_id = db.Column(
        db.Integer(), db.ForeignKey(FlowAction.id),
        nullable=False, unique=False, index=True)
    """the id of flow_action."""

    action_role = db.Column(db.Integer(), db.ForeignKey(Role.id),
                            nullable=True, unique=False)

    action_role_exclude = db.Column(
        db.Boolean(name='role_exclude'),
        nullable=False, default=False, server_default='0')
    """If set to True, deny the action, otherwise allow it."""

    action_user = db.Column(db.Integer(), db.ForeignKey(User.id),
                            nullable=True, unique=False)

    action_user_exclude = db.Column(
        db.Boolean(name='user_exclude'),
        nullable=False, default=False, server_default='0')
    """If set to True, deny the action, otherwise allow it."""
Exemplo n.º 8
0
class RecordMetadataBase(Timestamp):
    """Represent a base class for record metadata.

    The RecordMetadata object contains a ``created`` and  a ``updated``
    properties that are automatically updated.
    """

    # Enables SQLAlchemy-Continuum versioning
    __versioned__ = {}

    id = db.Column(
        UUIDType,
        primary_key=True,
        default=uuid.uuid4,
    )
    """Record identifier."""

    json = db.Column(db.JSON().with_variant(
        postgresql.JSONB(none_as_null=True),
        'postgresql',
    ).with_variant(
        JSONType(),
        'sqlite',
    ).with_variant(
        JSONType(),
        'mysql',
    ),
                     default=lambda: dict(),
                     nullable=True)
    """Store metadata in JSON format.

    When you create a new ``Record`` the ``json`` field value should never be
    ``NULL``. Default value is an empty dict. ``NULL`` value means that the
    record metadata has been deleted.
    """

    version_id = db.Column(db.Integer, nullable=False)
    """Used by SQLAlchemy for optimistic concurrency control."""

    __mapper_args__ = {'version_id_col': version_id}
Exemplo n.º 9
0
class Comment(db.Model, Timestamp):
    """Comment in a request."""

    __tablename__ = 'requests_comment'

    id = db.Column(
        UUIDType,
        default=uuid.uuid4,
        primary_key=True,
    )

    request_id = db.Column(
        UUIDType,
        db.ForeignKey(Request.id, ondelete="CASCADE"),
        nullable=False,
    )

    created_by = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)

    message = db.Column(db.Text)

    request = db.relationship(
        Request,
        backref=db.backref(
            'comments',
            cascade='all, delete-orphan',
            passive_deletes=True,
        ),
    )

    @classmethod
    def create(cls, request_id, created_by, message):
        with db.session.begin_nested():
            obj = cls(
                request_id=request_id,
                created_by=created_by,
                message=message,
            )
            db.session.add(obj)
        return obj
Exemplo n.º 10
0
class SourceVersion(db.Model):
    """Version de una fuente. Se utiliza para el proceso de inclusion y modificacion de los datos
    de una fuente. Al solicitar la inclusion de una nueva fuente, un usuario crea una version,
    posteriormente un editor valida esta version. En otro momento el usuario puede modificar los
    datos, que deberan ser validados, en todos los casos se crean versiones del source.  Un
    SourceVersion, no se puede modificar."""

    __tablename__ = 'iroko_source_versions'

    id = db.Column(db.Integer, primary_key=True)

    user_id = db.Column(
        db.Integer,
        db.ForeignKey(User.id, name='fk_iroko_source_versions_user_id'))
    """ID of user to whom this inclusion belongs."""

    user = db.relationship(User, backref='iroko_source_versions')

    source_uuid = db.Column(UUIDType, nullable=False)

    #
    # source_id = db.Column(db.Integer, db.ForeignKey(
    #     Source.id, name='fk_iroko_source_versions_source_id'))
    # """ID of Source for this inclusion."""
    #
    # source = db.relationship("Source",
    #                          backref=db.backref("versions",
    #                                             cascade="all, delete-orphan",
    #                                             lazy='dynamic',
    #                                             order_by='SourceVersion.created_at.desc()')
    #                          )
    comment = db.Column(db.String)

    # TODO: Creo que es conveniente que aqui se incluyan las relaciones con los terminos (en
    #  principio usando IDs)asi, al crear una nueva version, se pueden reflejar los cambios en
    #  las bases de datos.
    data = db.Column(JSONType)
    """The data of the Source, dependent on the source type, including the relationships with
    Terms"""

    created_at = db.Column(db.DateTime)

    is_current = db.Column(db.Boolean)
    """If is the current active version of Source"""

    reviewed = db.Column(db.Boolean)
    """the version is reviewed by some gestor"""
    def __str__(self):
        """Representation."""
        return self.source.name + ' : ' + self.created_at + ' : ' + self.is_current
Exemplo n.º 11
0
class Source(db.Model):
    """Source, fuente, es define una fuente primaria de datos, eg: las revistas.
    Aqui se tiene la informacion basica de la fuente,
    su relacion con la taxonomia y la informacion de la fuente en tanto repositorio de documentos
    """

    __tablename__ = 'iroko_sources'

    id = db.Column(db.Integer, primary_key=True)
    uuid = db.Column(UUIDType, default=uuid.uuid4)
    name = db.Column(db.String, nullable=False, unique=True)
    source_type = db.Column(db.Enum(SourceType))
    source_status = db.Column(db.Enum(SourceStatus))

    # TODO: decidir sobre esto:  Aunque este repetido, creo que es conveniente poner aqui (y
    #  manejar en las apps, en consecuencia), las relaciones con los terminos. En las tablas se
    #  pone por facilidad, pero aunque este repetido, a la hora de "editar" un Source, me parece
    #  que es mas facil asi..
    data = db.Column(JSONType)
    """The data of the Source, dependent on the source type, including the relationships with
    Terms"""

    # term_sources = db.relationship("Term_sources", back_populates="sources")

    def __str__(self):
        """Representation."""
        return self.name
Exemplo n.º 12
0
class CommunitySchemaVersion(db.Model):
    """Represent a version of a community's schema in the database.

    Each Community has only one schema, which can have multiple versions. All
    released community schemas are immutable.

    The last released Community schema is used to validate all the new records
    submitted to this Community.
    """

    from b2share.modules.communities.models import Community

    __tablename__ = 'b2share_community_schema_version'

    community = db.Column(
        UUIDType,
        db.ForeignKey(Community.id,
                      name='fk_b2share_community_schema_version_community'),
        primary_key=True)
    """Community accepting this schema."""

    version = db.Column(db.Integer,
                        primary_key=True,
                        default=None,
                        nullable=False,
                        autoincrement=False)
    "Schema version."

    released = sa.Column(sa.DateTime, default=datetime.utcnow, nullable=False)
    """Schema release date."""

    root_schema = db.Column(
        db.Integer,
        db.ForeignKey(RootSchemaVersion.version,
                      name='fk_b2share_community_schema_version_root_schema'),
        nullable=False)
    """Root schema used by this community."""

    community_schema = db.Column(db.String, nullable=False, default="{}")
Exemplo n.º 13
0
class RecordSIP(db.Model, Timestamp):
    """An association table for Records and SIPs."""

    __tablename__ = 'sipstore_recordsip'

    sip_id = db.Column(UUIDType,
                       db.ForeignKey(SIP.id,
                                     name='fk_sipstore_recordsip_sip_id'),
                       primary_key=True)
    """Id of SIP."""

    pid_id = db.Column(db.Integer,
                       db.ForeignKey(PersistentIdentifier.id,
                                     name='fk_sipstore_recordsip_pid_id'),
                       primary_key=True)
    """Id of the PID pointing to the record."""

    #
    # Relations
    #
    sip = db.relationship(SIP, backref='record_sips', foreign_keys=[sip_id])
    """Relation to the SIP associated with the record."""
Exemplo n.º 14
0
class SIPFile(db.Model, Timestamp):
    """Extra SIP info regarding files."""

    __tablename__ = 'sipstore_sipfile'

    sip_id = db.Column(UUIDType,
                       db.ForeignKey(SIP.id,
                                     name='fk_sipstore_sipfile_sip_id'),
                       primary_key=True)
    """Id of SIP."""

    filepath = db.Column(db.Text().with_variant(mysql.VARCHAR(255), 'mysql'),
                         nullable=False,
                         primary_key=True)
    """Filepath of submitted file within the SIP record."""

    file_id = db.Column(UUIDType,
                        db.ForeignKey(FileInstance.id,
                                      name='fk_sipstore_sipfile_file_id',
                                      ondelete='RESTRICT'),
                        nullable=False)
    """Id of the FileInstance."""
    @validates('filepath')
    def validate_key(self, filepath, filepath_):
        """Validate key."""
        if len(filepath_) > current_app.config['SIPSTORE_FILEPATH_MAX_LEN']:
            raise ValueError('Filepath too long ({0}).'.format(len(filepath_)))
        return filepath_

    #
    # Relations
    #
    sip = db.relationship(SIP, backref='sip_files', foreign_keys=[sip_id])
    """Relation to the SIP along which given file was submitted."""

    file = db.relationship(FileInstance,
                           backref='sip_files',
                           foreign_keys=[file_id])
    """Relation to the SIP along which given file was submitted."""
Exemplo n.º 15
0
class SelfcheckTerminal(db.Model):
    """Selfcheck terminal model."""

    __tablename__ = 'selfcheck_terminals'

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String(255), unique=True)
    access_token = db.Column(db.String(255), nullable=False)
    organisation_pid = db.Column(db.String(255), nullable=False)
    library_pid = db.Column(db.String(255), nullable=False)
    location_pid = db.Column(db.String(255), nullable=False)
    active = db.Column(db.Boolean(name='active'), default=True)
    last_login_at = db.Column(db.DateTime)
    last_login_ip = db.Column(IPAddressType, nullable=True)
    comments = db.Column(db.Text, nullable=True)

    @classmethod
    def find_terminal(cls, **kwargs):
        """Find selfcheck terminal within the given arguments."""
        query = cls.query
        return query.filter_by(**kwargs).first()
Exemplo n.º 16
0
class RecordsBuckets(db.Model):
    """Relationship between Records and Buckets."""

    __tablename__ = 'records_buckets'

    record_id = db.Column(
        UUIDType,
        db.ForeignKey(RecordMetadata.id),
        primary_key=True,
        nullable=False,
        # NOTE no unique constrain for better future ...
    )
    """Record related with the bucket."""

    bucket_id = db.Column(
        UUIDType,
        db.ForeignKey(Bucket.id),
        primary_key=True,
        nullable=False,
    )
    """Bucket related with the record."""

    bucket = db.relationship(Bucket)
    """Relationship to the bucket."""

    record = db.relationship(RecordMetadata)
    """It is used by SQLAlchemy for optimistic concurrency control."""
    @classmethod
    def create(cls, record, bucket):
        """Create a new RecordsBuckets and adds it to the session.

        :param record: Record used to relate with the ``Bucket``.
        :param bucket: Bucket used to relate with the ``Record``.
        :returns: The :class:`~invenio_records_files.models.RecordsBuckets`
            object created.
        """
        rb = cls(record=record, bucket=bucket)
        db.session.add(rb)
        return rb
Exemplo n.º 17
0
class BlockSchema(db.Model, Timestamp):
    """Represent one of the community's metadata block schema in the database.

    Every schema is versioned. Previous versions can always be accessible.
    These versions are represented as BlockSchemaVersion.

    Additionally it contains two columns ``created`` and ``updated``
    with automatically managed timestamps.
    """

    from b2share.modules.communities.models import Community

    __tablename__ = 'b2share_block_schema'

    id = db.Column(
        UUIDType,
        default=uuid.uuid4,
        primary_key=True,
    )
    """Schema identifier."""

    name = db.Column(
        db.String(200),
        sa.CheckConstraint('LENGTH(name) > 2 AND '
                           'LENGTH(name) <= 200',
                           name='name_length'),
        nullable=False,
    )
    """Name of the schema."""

    deprecated = db.Column(db.Boolean, default=False, nullable=False)
    """True if the schema is not maintained anymore."""

    community = db.Column(UUIDType,
                          db.ForeignKey(
                              Community.id,
                              name='fk_b2share_block_schema_community'),
                          nullable=False)
    """Community owning and maintaining this schema."""
Exemplo n.º 18
0
class GitWebhookSubscriber(db.Model):
    """Records subscribed to the git repository events."""

    __tablename__ = 'git_subscriber'
    __table_args__ = db.UniqueConstraint(
        'record_id',
        'webhook_id',
        name='uq_git_webhook_subscriber_unique_constraint'),

    id = db.Column(db.Integer, primary_key=True)

    status = db.Column(db.Enum('active', 'deleted', name='git_webhook_status'),
                       nullable=False,
                       default='active')

    record_id = db.Column(UUIDType,
                          db.ForeignKey(RecordMetadata.id),
                          nullable=False)
    record = db.relationship(RecordMetadata,
                             backref=db.backref("webhooks",
                                                cascade="all, delete-orphan"))

    webhook_id = db.Column(db.Integer,
                           db.ForeignKey(GitWebhook.id),
                           nullable=False)
    webhook = db.relationship(GitWebhook,
                              backref=db.backref("subscribers",
                                                 cascade="all, delete-orphan"))

    user_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
    user = db.relationship(User)

    snapshots = db.relationship(GitSnapshot,
                                order_by="desc(GitSnapshot.created)",
                                secondary='git_subscriber_snapshots')

    @property
    def repo(self):
        return self.webhook.repo
Exemplo n.º 19
0
class DataSubmission(db.Model):
    """
    The submission object associated with a data table.
    """
    __tablename__ = "datasubmission"

    # id is a unique id for each datasubmission and version
    id = db.Column(db.Integer,
                   primary_key=True,
                   nullable=False,
                   autoincrement=True)

    publication_recid = db.Column(db.Integer)
    publication_inspire_id = db.Column(db.String(128))

    location_in_publication = db.Column(db.String(256))
    name = db.Column(db.String(64))
    description = db.Column(LargeBinaryString)
    keywords = db.relationship("Keyword",
                               secondary="keyword_submission",
                               cascade="all,delete")

    # the main data file, with the data table
    data_file = db.Column(db.Integer, db.ForeignKey("dataresource.id"))

    # supplementary files, such as code, links out to other resources etc.
    resources = db.relationship("DataResource",
                                secondary="datafile_identifier",
                                cascade="all,delete")

    doi = db.Column(db.String(128), nullable=True)

    # the record ID for the resulting record created on finalisation.
    associated_recid = db.Column(db.Integer)

    # when a new version is loaded, the version is increased and
    # maintained so people can go back in time
    # through a submissions review stages.
    version = db.Column(db.Integer, default=0)
Exemplo n.º 20
0
class SiteLicenseInfo(db.Model, Timestamp):
    """Represent a SiteLicenseInfo data.

    The SiteLicenseInfo object contains a ``created`` and  a ``updated``
    properties that are automatically updated.
    """

    __tablename__ = 'sitelicense_info'

    organization_id = db.Column(db.Integer(),
                                primary_key=True,
                                autoincrement=True)

    organization_name = db.Column(db.Text, nullable=False)

    domain_name = db.Column(db.Text, nullable=True)

    mail_address = db.Column(db.String(255), nullable=True)

    receive_mail_flag = db.Column(db.String(1), default='F', nullable=False)

    # Relationships definitions
    addresses = db.relationship('SiteLicenseIpAddress',
                                backref='SiteLicenseInfo')
    """Relationship to SiteLicenseIpAddress."""
    def __iter__(self):
        """TODO: __iter__."""
        sl = {}
        for name in dir(SiteLicenseInfo):
            if not name.startswith('__') and not name.startswith('_'):
                value = getattr(self, name)
                if isinstance(value, list):
                    ip_lst = []
                    for lst in value:
                        if isinstance(lst, SiteLicenseIpAddress):
                            ip_lst.append(dict(lst))
                    yield (name, ip_lst)
                elif isinstance(value, str):
                    yield (name, value)
Exemplo n.º 21
0
class WorkflowsRecordSources(db.Model):

    __tablename__ = 'workflows_record_sources'
    __table_args__ = (db.PrimaryKeyConstraint('record_id', 'source'), )

    source = db.Column(
        db.Text,
        default='',
        nullable=False,
    )
    record_id = db.Column(
        UUIDType,
        db.ForeignKey('records_metadata.id', ondelete='CASCADE'),
        nullable=False,
    )
    json = db.Column(
        JSONType().with_variant(
            postgresql.JSON(none_as_null=True),
            'postgresql',
        ),
        default=lambda: dict(),
    )
Exemplo n.º 22
0
class Journal_export_processing(db.Model, Timestamp):
    """
    Represent an journal.

    The Journal object contains a ``created``, a ``updated``
    properties that are automatically updated.
    """

    __tablename__ = 'journal_export_processing'

    id = db.Column(db.BigInteger, primary_key=True, unique=True)
    """id of the journal export process."""

    start_time = db.Column(db.DateTime, default=datetime.now)
    """start time to export journal."""

    end_time = db.Column(db.DateTime, default=datetime.now)
    """end time to export journal."""

    status = db.Column(db.Boolean, nullable=True)
    """status of processing when export journal data."""
    @classmethod
    def save_export_info(cls, data):
        """Save export journal info."""
        try:
            with db.session.begin_nested():
                db.session.add(data)
            db.session.commit()
        except BaseException as ex:
            db.session.rollback()
            current_app.logger.debug(ex)
            raise
        return cls

    @classmethod
    def get(cls):
        """Get last process of journal info."""
        return db.session.query(Journal_export_processing).order_by(
            Journal_export_processing.id.desc()).first()
Exemplo n.º 23
0
class Role(db.Model, Timestamp, RoleMixin):
    """Role data model."""

    __tablename__ = "accounts_role"

    id = db.Column(db.Integer(), primary_key=True)

    name = db.Column(db.String(80), unique=True)
    """Role name."""

    description = db.Column(db.String(255))
    """Role description."""

    # Enables SQLAlchemy version counter
    version_id = db.Column(db.Integer, nullable=False)
    """Used by SQLAlchemy for optimistic concurrency control."""

    __mapper_args__ = {"version_id_col": version_id}

    def __str__(self):
        """Return the name and description of the role."""
        return '{0.name} - {0.description}'.format(self)
Exemplo n.º 24
0
class Workflow(db.Model):
    """Represents a workflow instance storing the state of the workflow."""

    __tablename__ = "workflows_workflow"

    uuid = db.Column(UUIDType,
                     primary_key=True,
                     nullable=False,
                     default=uuid.uuid4())
    name = db.Column(db.String(255),
                     default="Default workflow",
                     nullable=False)
    created = db.Column(db.DateTime, default=datetime.now, nullable=False)
    modified = db.Column(db.DateTime,
                         default=datetime.now,
                         onupdate=datetime.now,
                         nullable=False)
    id_user = db.Column(db.Integer, default=0, nullable=False)
    extra_data = db.Column(JSONType().with_variant(
        postgresql.JSON(none_as_null=True),
        'postgresql',
    ),
                           default=lambda: dict(),
                           nullable=False)
    status = db.Column(ChoiceType(WorkflowStatus, impl=db.Integer()),
                       default=WorkflowStatus.NEW,
                       nullable=False)
    objects = db.relationship("WorkflowObjectModel",
                              backref='workflows_workflow',
                              cascade="all, delete-orphan")

    def __repr__(self):
        """Represent a workflow object."""
        return "<Workflow(name: %s, cre: %s, mod: %s," \
               "id_user: %s, status: %s)>" % \
               (str(self.name),  str(self.created), str(self.modified),
                str(self.id_user), str(self.status))

    @classmethod
    def delete(cls, uuid):
        """Delete a workflow."""
        to_delete = Workflow.query.get(uuid)
        db.session.delete(to_delete)

    def save(self, status=None):
        """Save object to persistent storage."""
        with db.session.begin_nested():
            self.modified = datetime.now()
            if status is not None:
                self.status = status
            if self.extra_data is None:
                self.extra_data = dict()
            flag_modified(self, 'extra_data')
            db.session.merge(self)
Exemplo n.º 25
0
class DraftMetadataBase(Timestamp):
    """Represent a base class for draft metadata.

    The DraftMetadata object  contains a `created` and  a `updated`
    properties that are automatically updated.
    """

    # Enables SQLAlchemy-Continuum versioning
    __versioned__ = {}

    id = db.Column(
        UUIDType,
        primary_key=True,
        default=uuid.uuid4,
    )
    """Draft identifier."""

    fork_id = db.Column(UUIDType)
    """Draft identifier, it is the same than the record it is draft of"""

    fork_version_id = db.Column(db.Integer)
    """Version id of the record it is draft of."""

    version_id = db.Column(db.Integer, nullable=False)
    """Used by SQLAlchemy for optimistic concurrency control."""

    status = db.Column(db.String(255), default="draft", nullable=False)
    """Status for workflow management."""

    expiry_date = db.Column(db.DateTime().with_variant(mysql.DATETIME(fsp=6),
                                                       "mysql"),
                            default=datetime.utcnow,
                            nullable=True)
    """Specifies when the it expires. If `NULL` the draft does not expire"""

    json = db.Column(db.JSON().with_variant(
        postgresql.JSONB(none_as_null=True),
        'postgresql',
    ).with_variant(
        JSONType(),
        'sqlite',
    ).with_variant(
        JSONType(),
        'mysql',
    ),
                     default=lambda: dict(),
                     nullable=True)
    """Store metadata in JSON format.
    When you create a new `Record the `json field value should never be
    `NULL`. Default value is an empty dict. `NULL` value means that the
    record metadata has been deleted.
    """

    __mapper_args__ = {'version_id_col': version_id}
Exemplo n.º 26
0
class LOMRecordMetadata(db.Model, RecordMetadataBase, ParentRecordMixin):
    """Flask-SQLAlchemy model for "lom_records_metadata"-SQL-table."""

    __tablename__ = "lom_records_metadata"

    __parent_record_model__ = LOMParentMetadata

    # signals SQLAlchemy-Continuum to record transactions with this table
    # other models keep track of versions with their `version_id`-attribute
    __versioned__ = {}

    bucket_id = db.Column(UUIDType, db.ForeignKey(Bucket.id))
    bucket = db.relationship(Bucket)
Exemplo n.º 27
0
class HarvestMonitoring(db.Model, Timestamp):
    """Harvesting monitoring model."""

    __tablename__ = 'harvest_monitoring'

    id = db.Column(UUIDType, default=uuid.uuid4, primary_key=True)
    identifier = db.Column(db.String, nullable=False)
    scheme = db.Column(db.String)
    harvester = db.Column(db.String)
    status = db.Column(db.Enum(HarvestStatus), nullable=False)

    @classmethod
    def get(cls, id: str = None, **kwargs):
        """Get the event from the database."""
        return cls.query.filter_by(id=id).one_or_none()

    @classmethod
    def isRecentlyAdded(cls, identifier: str, scheme: str, harvester: str,
                        **kwargs) -> Boolean:
        """Check if the same identifier has been queried for during the last week to avoid duplicates"""
        last_week = datetime.datetime.now() - datetime.timedelta(days=7)
        resp = cls.query.filter(cls.identifier == identifier,
                                cls.scheme == scheme,
                                cls.harvester == harvester,
                                cls.updated > str(last_week)).first()
        return resp is not None

    @classmethod
    def getStatsFromLastWeek(cls):
        """Gets the stats from the last 7 days"""
        last_week = datetime.datetime.now() - datetime.timedelta(days=7)
        resp = db.session.query(cls.status, func.count('*')).filter(
            cls.updated > str(last_week)).group_by(cls.status).all()
        return resp

    def __repr__(self):
        """String representation of the event."""
        return f"<{self.id}: {self.created} : {self.identifier}>"
Exemplo n.º 28
0
class FeaturedCommunity(db.Model, Timestamp):
    """Represent a featured community."""

    __tablename__ = 'communities_featured_community'

    id = db.Column(db.Integer, primary_key=True)
    """Id of the featured entry."""

    id_community = db.Column(
        db.String(100), db.ForeignKey(Community.id), nullable=False)
    """Id of the featured community."""

    start_date = db.Column(
        db.DateTime, nullable=False, default=datetime.utcnow)
    """Start date of the community featuring."""

    #
    # Relationships
    #
    community = db.relationship(Community, backref="featuredcommunity")
    """Relation to the community."""

    @classmethod
    def get_featured_or_none(cls, start_date=None):
        """Get the latest featured community.

        :param start_date: Date after which the featuring starts
        :returns: Community object or None
        :rtype: `invenio_communities.models.Community` or None
        """
        start_date = start_date or datetime.utcnow()

        comm = cls.query.filter(
            FeaturedCommunity.start_date <= start_date
        ).order_by(
            cls.start_date.desc()
        ).first()
        return comm if comm is None else comm.community
Exemplo n.º 29
0
class ApiRegistrations(db.Model):
    __tablename__ = 'api_registrations'

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    """Primary key. It allows the other fields to be nullable."""

    creation_date = db.Column(db.DateTime, default=datetime.utcnow)

    partner = db.Column(db.Boolean(name='partner'),
                        nullable=False,
                        default=False,
                        server_default='0')

    name = db.Column(db.String(150), nullable=False)

    email = db.Column(EmailType, index=True, nullable=False, unique=True)

    organization = db.Column(db.String(255), nullable=False)

    role = db.Column(db.String(100), nullable=False)

    country = db.Column(db.String(80), nullable=False)

    description = db.Column(db.String(1000), nullable=True)

    accepted = db.Column(db.Integer, default=0, server_default='0')
    """0 - new, 1 - acceped, -1 - denied"""
    @classmethod
    def accept(cls, id):
        registration = cls.query.filter_by(id=id).one()
        registration.accepted = 1
        return True

    @classmethod
    def reject(cls, id):
        registration = cls.query.filter_by(id=id).one()
        registration.accepted = -1
        return True
Exemplo n.º 30
0
class BlockSchemaVersion(db.Model):
    """Represent one version of a "Block Schema" in the database.

    Every version of a schema MUST be backward compatible with all its previous
    versions, i.e. no previously existing field can have its type changed.
    Fields can be added or removed and the required fields can change.
    This enables to search and analyze records in a consistent way.
    """

    __tablename__ = 'b2share_block_schema_version'

    block_schema = db.Column(UUIDType, db.ForeignKey(BlockSchema.id),
                             primary_key=True)
    """ID of the parent block schema."""

    version = db.Column(db.Integer, primary_key=True, autoincrement=False)
    """Version number of this schema."""

    released = sa.Column(sa.DateTime, default=datetime.utcnow, nullable=False)
    """Schema release date."""

    json_schema = db.Column(db.Text, nullable=True)
    """JSON Schema."""