"""Model for history table in label_copy_export database.""" from datetime import datetime from oto import response from oto import status as response_status from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import Enum from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.ext.hybrid import hybrid_property from label_copy_export.connectors import mysql from label_copy_export.constants import error from label_copy_export.constants import lce_history from label_copy_export.models import error_handlers class Job(mysql.BaseModel): """Class representing the label copy export history's job.""" __tablename__ = 'label_copy_export_history' job_id = Column('id', Integer, primary_key=True, autoincrement=True) user_id = Column(String(127)) project_id = Column(Integer, nullable=False) status = Column( Enum(*lce_history.GENERATION_STATUSES), default=lce_history.REQUESTED) _last_change_date = Column( 'last_change_date', DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow) @hybrid_property def last_change_date(self): """Getter for private attribute _last_change_date.""" return self._last_change_date def to_dict(self): """Return object as dict. Returns: dict: Dictionary representation of object """ job_dict = { 'job_id': self.job_id, 'user_id': self.user_id, 'project_id': self.project_id, 'status': self.status, 'last_change_date': self.last_change_date } return job_dict @error_handlers.sqlalchemy_error_handler def change_status(job_id, status): """Change status of job. Args: job_id (int): job id. status (str): Job internal status, must be one of lce_history.GENERATION_STATUSES. Returns: response.Response: empty body on success, .errors on failure. """ with mysql.label_copy_export_history_session_scope() as session: job = (session.query(Job).with_for_update() .filter_by(job_id=job_id).first()) if not job: return response.create_not_found_response( error.JOB_DOES_NOT_EXIST) job.status = status session.add(job) return response.Response(status=response_status.NO_CONTENT)