class Recipes(db.Model): """This is Recipes class for table structure.""" __tablename__ = 'recipes' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(40), nullable=False) ingredients = db.Column(db.Text, nullable=False) description = db.Column(db.Text, nullable=False) image_file = db.Column(db.String(20), nullable=False, default='default.jpg') date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) date_updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) category_id = db.Column(db.Integer, db.ForeignKey('categories.id'), nullable=False) category = db.relationship('Categories', foreign_keys=[category_id]) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) user = db.relationship('Users', foreign_keys=[user_id]) def __rerp__(self): """Representation string of an Recipes object.""" return f"Recipes('{self.name}', " \ f"'{self.category_id}', " \ f"'{self.user_id}', " \ f"'{self.date_posted}', " \ f"'{self.date_updated}', " \ f"'{self.image_file}')"
class TicketRecords(db.Model): __tablename__ = 'TICKET_RECORDS' id_ticket = db.Column(db.Integer, primary_key=True) id_ticket_hash = db.Column(db.String(255), unique=True, default='') id_creator = db.Column( db.Integer, db.ForeignKey('USERS.id_user', ondelete='RESTRICT', onupdate='RESTRICT')) id_admin = db.Column(db.Integer, db.ForeignKey('USERS.id_user', ondelete='RESTRICT', onupdate='RESTRICT'), nullable=True) id_channel = db.Column(db.String(255), unique=True, default='') # status: -1 => No admin has taken the ticket # status: 0 => Ticket is assigned to an admin # status: 1 => Ticket is marked as closed status = db.Column(TINYINT(1), default=-1) title = db.Column(db.String(255), default='') category = db.Column(db.String(100), default='') create_timestamp = db.Column( TIMESTAMP, default=datetime.utcnow().replace(microsecond=0)) last_activity_timestamp = db.Column( TIMESTAMP, default=datetime.utcnow().replace(microsecond=0))
class Note(db.Model): __tablename__ = 'notes' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(250)) body = db.Column(db.String()) creation_date = db.Column(db.DateTime, server_default=db.func.current_timestamp(), nullable=False) modified_date = db.Column(db.DateTime, server_default=db.func.current_timestamp(), nullable=False) notebook_id = db.Column(db.Integer, db.ForeignKey('notebooks.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE')) @classmethod def filter_by_user_id(cls, user_id): return cls.query.filter_by(user_id=user_id).all() @classmethod def filter_by_notebook_id(cls, notebook_id): return cls.query.filter_by(notebook_id=notebook_id).all()
class Req(Base): __tablename__ = 'req' req_id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=True) game_id = db.Column(db.Integer, db.ForeignKey('game.game_id'), nullable=True) def __repr__(self): return '<Req $d (id:$d)>' % self.req_id
class Prediction(db.Model): """Prediction model Used to store document predictions for users """ __tablename__ = 'predictions' id = db.Column(db.Integer, primary_key=True) created_on = db.Column(db.DateTime, server_default=db.func.now()) updated_on = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now()) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) document_id = db.Column(db.Integer, db.ForeignKey('documents.id')) onboard = db.Column(db.Boolean, default=False) viewed_on = db.Column(db.DateTime) random_pred = db.Column(db.Boolean, default=False) def __init__(self, user_id, document_id, onboard=False, random_pred=False): """Prediction object Initialization inputs ------------ user_id : int_type ForeignKey to user.id document_id : int_type ForeignKey to document.id onboard : Boolean (optional) """ self.user_id = user_id self.document_id = document_id self.onboard = onboard self.random_pred = random_pred def save(self): """Saves Predictions to Database""" try: db.session.add(self) db.session.commit() except IntegrityError as e: db.session.rollback() raise ValueError('Data invalid. \ Cannot create document at this time.') def to_dict(self): return { 'id': self.id, 'created_on': str(self.created_on), 'user_id': self.user_id, 'document_id': self.document_id, 'onboard': self.onboard, 'viewed_on': str(self.viewed_on), 'random_pred': int(self.random_pred) }
class Classification(db.Model): """Classification model Stores all items that were classified by User or by other entity """ __tablename__ = 'classifications' id = db.Column(db.Integer, primary_key=True) created_on = db.Column(db.DateTime, server_default=db.func.now()) updated_on = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now()) document_id = db.Column(db.Integer, db.ForeignKey('documents.id')) prediction_id = db.Column(db.Integer, db.ForeignKey('predictions.id')) prediction_type = db.Column(types.Enum('document'), default='document') class_label = db.Column(db.Integer) def __init__(self, document_id, prediction_id, class_label): """Prediction object Initialization inputs ------------ document_id : int_type ForeignKey to document.id prediction_id : int_type ForeignKey to predictions.id class_label : int_type Class label """ self.document_id = document_id self.prediction_id = prediction_id self.class_label = class_label def save(self): """Saves Classifcation to Database""" try: db.session.add(self) db.session.commit() except IntegrityError as e: db.session.rollback() raise ValueError('Data invalid. \ Cannot create document at this time.') def to_dict(self): return { 'id': self.id, 'created_on': str(self.created_on), 'document_id': self.prediction_id, 'prediction_id': self.prediction_id, 'prediction_type': self.prediction_type, 'class_label': self.class_label, }
class MaterialType(db.Model): __tablename__ = 'MaterialTypes' Id = db.Column(db.Integer, primary_key=True) Name = db.Column(db.String(255)) GUID = db.Column(db.String(255)) Unit = db.Column(db.String(255)) Formula_Id = db.Column(db.ForeignKey('Formulae.Id'), index=True) WorkType_Id = db.Column(db.ForeignKey('WorkTypes.Id'), index=True) Formula = relationship('Formula') WorkType = relationship('WorkType')
class Vocabularys(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) topic_id = db.Column(db.Integer, db.ForeignKey('topics.id')) type = db.Column(db.String, nullable=False) origin = db.Column(db.String, nullable=False) translate = db.Column(db.String, nullable=False) progress = db.relationship('Progress') # Create function to return String def __repr__(self): return self.id
class Passport(db.Model): __tablename__ = "db_passport" id = db.Column(db.Integer, autoincrement=True, primary_key=True) stamps = db.Column(db.Float, default=0.0, nullable=False) donations = db.Column(db.Float, default=0.0, nullable=False) activated = db.Column(db.Boolean, default=False, nullable=False) recharged = db.Column(db.Boolean, default=False, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('db_user.id')) event_id = db.Column(db.Integer, db.ForeignKey('db_event.id')) amount_recharged = db.Column(db.Float, default=0.0, nullable=True) recharged_by = db.Column(db.Integer, db.ForeignKey('db_user.id'), nullable=True) user = db.relation(User, foreign_keys=[user_id] ,backref='passports') event = db.relation(Event, backref='passports') recharger = db.relation(User, foreign_keys=[recharged_by], backref='recharged_passports')
class Progress(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) topic_id = db.Column(db.Integer, db.ForeignKey('topics.id')) vocabulary_id = db.Column(db.Integer, db.ForeignKey('vocabularys.id')) last_repeat = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) attempts = db.Column(db.Integer, nullable=False, default=0) success = db.Column(db.Integer, nullable=False, default=0) # Create function to return String def __repr__(self): return self.id
class Application(ModelBase): user_id = db.Column( db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False, ) company_name = db.Column(db.String(255), nullable=False, index=True) application_date = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) application_notes = db.Column(db.Text, nullable=True) position = db.Column(db.String(255), nullable=False, index=True) user = db.relationship( 'User', backref=db.backref('applications', lazy='dynamic'), ) events = db.relationship( 'ApplicationEvent', backref='application', lazy='dynamic', ) contacts = db.relationship( 'ApplicationContact', backref='application', lazy='dynamic', ) keywords = db.relationship('Keyword', secondary=application_keyword, backref=db.backref('applications', lazy='dynamic'), lazy='dynamic')
class Document(db.Model): __tablename__ = "Documents" id = db.Column(db.Integer, primary_key=True, name="Id", nullable=False) name = db.Column(db.String(255), name="Name", nullable=False) type = db.Column(db.Integer, name="DocumentType", nullable=False) date_created = db.Column(db.DateTime, name="DateCreated", nullable=False, default=datetime.now()) date_modified = db.Column(db.DateTime, name="DateModified", nullable=False, default=datetime.now()) project_id = db.Column(db.ForeignKey('MultiProjects.Id'), name='MultiProject_Id', index=True) rooms = db.relationship(Room, back_populates='document', cascade="all, delete-orphan") project = relationship('MultiProject') def to_view_json(self): return { 'id': self.id, 'name': self.name, 'dateCreated': str(self.date_created), 'dateModified': str(self.date_modified), 'documentType': self.type } def to_json(self): return { 'id': self.id, 'name': self.name, 'documentType': self.type, 'dateCreated': str(self.date_created), 'dateModified': str(self.date_modified), 'rooms': self.rooms } def update_from_json(self, data): self.name = data['name'] self.type = data['documentType'] self.date_modified = datetime.now() self.rooms = Room.array_from_json(data['rooms'], self.rooms) @classmethod def from_json(cls, data): return cls(name=data['name'], type=data['documentType'], rooms=list(map(Room.from_json, data['rooms'])))
class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), nullable=False) comment = db.Column(db.String(255), nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) updated_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, onupdate=datetime.now()) post = db.relationship("Post", backref=db.backref("posts", lazy=True)) def __init__(self, username, comment, post_id): self.username = username self.comment = comment self.post_id = post_id def json(self): return { "id": self.id, "username": self.username, "comment": self.comment, "post_id": self.post_id, "created_at": str(self.created_at), "updated_at": str(self.updated_at) } def create(self): db.session.add(self) db.session.commit() return self @classmethod def find_all(cls): comments = Comment.query.all() return [comment.json() for comment in comments] @classmethod def find_by_id(cls, id): return Comment.query.filter_by(id=id).first() @classmethod def delete(cls, id): comment = Comment.find_by_id(id) db.session.delete(comment) db.session.commit() return comment.json() @classmethod def update(cls, id, fields): comment = Comment.find_by_id(id) for key in field: setattr(comment, key, fields[key]) db.session.commit() return comment.json()
class WorkType(db.Model): __tablename__ = 'WorkTypes' id = db.Column(db.Integer, name='Id', primary_key=True) guid = db.Column(db.String(255), name='GUID') name = db.Column(db.String(255), name='Name') price_value = db.Column(db.Float, name='PriceValue', nullable=False) salary = db.Column(db.Float, name='Salary', nullable=False) time = db.Column(db.Float, name='Time', nullable=False) order = db.Column(db.Integer, name='Order', nullable=False) description = db.Column(db.Text, name='Description') materials_count = db.Column(db.Text, name='MaterialsCount') formula_id = db.Column(db.ForeignKey('Formulae.Id'), name='Formula_Id', index=True) formula = db.relationship('Formula') categories = db.relationship('Category', secondary='WorkTypeCategories') def to_json(self): return { 'id': self.id, 'name': self.name, 'GUID': self.guid, 'priceValue': self.price_value, 'salary': self.salary, 'time': self.time, 'order': self.order, 'descriptions': self.description, 'materialsCount': self.materials_count, 'formula': self.formula, 'categories': list(map(lambda c: {'id': c.id}, self.categories)) } @classmethod def from_json(cls, data): return WorkType(id=data.get('id', None), name=data['name'], guid=data['GUID'], price_value=data['priceValue'], salary=data['salary'], time=data['time'], order=data['order'], description=data['description'], materials_count=data['materialsCount'], formula=Formula.from_json(data['formula']))
class News(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) title = db.Column(db.String, nullable=False, unique=True) text = db.Column(db.String, nullable=False) # Create function to return String def __repr__(self): return self.id
class TemplateBlock(db.Model): __tablename__ = 'TemplateBlocks' Id = db.Column(db.Integer, primary_key=True) Name = db.Column(db.String(255)) Content = db.Column(db.Text) Order = db.Column(db.Integer, nullable=False) TemplateBlockType = db.Column(db.Integer, nullable=False) Template_Id = db.Column(db.ForeignKey('Templates.Id'), index=True) Template = relationship('Template')
class Hat(db.Model): __tablename__ = "hat" id = db.Column(db.Integer, primary_key=True) colour = db.Column(db.Enum(Colour)) char_id = db.Column(db.Integer, db.ForeignKey('character.id')) # Creates the one to one relationship character = db.relationship("Character", backref=db.backref("children", cascade="all,delete", passive_deletes=True)) def __init__(self, id, colour): self.id = id self.colour = colour
class Player(Base): __tablename__ = 'player' player_id = db.Column(db.Integer, primary_key=True) player_name = db.Column(db.String(PLAYER_NAME_SIZE), unique=True, nullable=False) user_id = db.Column(db.Integer, nullable=True) game_id = db.Column(db.Integer, db.ForeignKey('game.game_id'), nullable=True) char_id = db.Column(db.Integer, db.ForeignKey('game_char.char_id'), nullable=True) status = db.Column(db.String(1), nullable=False, default='A') faction = db.Column(db.String(1), nullable=True) current_life = db.Column(db.Integer, nullable=False) maximum_life = db.Column(db.Integer, nullable=True) traits = db.Column(utils.TextPickleType(), nullable=False) def __repr__(self): return '<Player %r (id:$d)>' % self.player_name, player_id
class ApplicationContact(ModelBase): application_id = db.Column( db.Integer, db.ForeignKey('application.id', ondelete='CASCADE'), nullable=False, ) first_name = db.Column(db.String(255), nullable=True) last_name = db.Column(db.String(255), nullable=True) email = db.Column(db.String(255), nullable=True) phone_number = db.Column(db.String(255), nullable=True) position = db.Column(db.String(255), nullable=True) contact_notes = db.Column(db.Text, nullable=True)
class FollowerCountDataPoint(db.Model): id = db.Column(db.Integer, primary_key=True) num_followers = db.Column(db.String(256), nullable=False) timestamp = db.Column(db.DateTime, nullable=True) contestant_id = db.Column( db.Integer, db.ForeignKey('contestant.id'), nullable=False ) def __unicode__(self): return '<User %r>' % self.id def __repr__(self): return '<User %r>' % self.id
class Product(db.Model): __tablename__ = "db_product" id = db.Column(db.Integer, autoincrement=True, primary_key=True) vendor_id = db.Column(db.Integer, db.ForeignKey('db_vendor.id')) name = db.Column(db.String(42), nullable=False) price = db.Column(db.Float, nullable=False) vendor = db.relation(Vendor, backref='products') purchases = db.relationship('Purchase', secondary=product_purchase_table, back_populates="products") def __repr__(self): return self.name
class Vendor(db.Model): __tablename__ = "db_vendor" id = db.Column(db.Integer, autoincrement=True, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('db_user.id'), nullable=False) user = db.relation(User, backref='vendor') name = db.Column(db.String(42), nullable=False) isFoundation = db.Column(db.Boolean, default=False, nullable=False) events = db.relationship(Event, secondary=vendor_event_table) def __repr__(self): return self.name
class ItemModel(db.Model): __tablename__ = "items" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) # precision=2, stands for the number of numbers after the decimal point. price = db.Column(db.Float(precision=2)) # stores is the table name of the store .id - column # foreign key reference is sort of "subsidiary" key, which has limited credentials. # basically now we give ID additional parameter, what store do we belong to? store_id = db.Column(db.Integer, db.ForeignKey("stores.id")) # Creates relationship between store id and every item in our database. store = db.relationship("StoreModel") def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def json(self): return { "id": self.id, "name": self.name, "price": self.price, "store_id": self.store_id } @classmethod def find_by_name(cls, name): # query is not something we have defined, it something that comes from db.Model # We have class. Then we say we want to query the model. And then we say filter by. # In other words SELECT * FROM items WHERE name=name(second name is our arg inside of find_by_name method) # Translates this code onto SQLCode, this data is also being converted to an item model object. return cls.query.filter_by(name=name).first() # SELECT * FROM items WHERE name=name LIMIT 1, basically returns only @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): # it is saving the model to the data base, SQLAlchemy can directly transform object to a row. # we are adding the collection of objects # this method is useful for both update and insert db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) username = db.Column(db.String(255), nullable=False) image = db.Column(db.String(255), nullable=False) description = db.Column(db.Text, nullable=False) bid = db.Column(db.Float, nullable=False) created_at = db.Column(db.DateTime, default=str(datetime.utcnow()), nullable=False) updated_at = db.Column(db.DateTime, default=datetime.utcnow(), nullable=False, onupdate=datetime.now()) user = db.relationship('User', backref=db.backref('users', lazy=True)) def __init__(self, user_id, username, image, bid, description): self.user_id = user_id self.username = username self.image = image self.bid = bid self.description = description def json(self): return { "id": self.id, "user_id": self.user_id, "username": self.username, "image": self.image, "bid": self.bid, "description": self.description, "created_at": str(self.created_at), "updated_at": str(self.updated_at) } def create(self): db.session.add(self) db.session.commit() return self @classmethod def find_all(cls): return Post.query.order_by(Post.bid.desc()).all() @classmethod def find_by_id(cls, post_id): post = Post.query.filter_by(id=post_id).first() return post
class Formula(db.Model): __tablename__ = 'Formulae' id = db.Column(db.Integer, name='Id', primary_key=True) expression = db.Column(db.String(1024), name='Expression') type = db.Column(IntEnum(FormulaType), name='Type', nullable=False) element_type_id = db.Column(db.ForeignKey('ElementTypes.Id'), name='ElementType_Id', index=True) room_type_id = db.Column(db.ForeignKey('RoomTypes.Id'), name='RoomType_Id', index=True) element_type = relationship('ElementType') room_type = relationship('RoomType', back_populates='formulas') parameters = relationship('Parameter', secondary='ParameterFormulas') def to_json(self): return { 'id': self.id, 'expression': self.expression, 'type': str(self.type.name), 'parameters': self.parameters } @classmethod def from_json(cls, data): return cls(id=data.get('id', None), expression=data['expression'], type=FormulaType[data['type']], parameters=list(map(Parameter.from_json, data['parameters'])))
class Purchase(db.Model): __tablename__ = "db_purchase" id = db.Column(db.Integer, autoincrement=True, primary_key=True) donation = db.Column(db.Boolean, default=False, nullable=False) passport_id = db.Column(db.Integer, db.ForeignKey('db_passport.id'), nullable=False) passport = db.relation(Passport, backref='purchases') id_client = db.Column(db.Integer, nullable=True) price = db.Column(db.Float, nullable=False) datetime = db.Column(db.DateTime, default=datetime.datetime.now()) products = db.relationship('Product', secondary=product_purchase_table) vendor_id = db.Column(db.Integer, db.ForeignKey('db_vendor.id'), nullable=False) vendor = db.relation(Vendor, backref='purchases') def __repr__(self): return str(self.products) # La clave primaria de esta clase es compuesta #participateIn
class Keyword(ModelBase): __table_args__ = (db.UniqueConstraint('user_id', 'keyword', name='keyword_user_unique'), ) user_id = db.Column( db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False, ) keyword = db.Column(db.String(50), nullable=False, index=True) user = db.relationship( 'User', backref=db.backref('keywords', lazy='dynamic'), )
class Category(db.Model): __tablename__ = 'Categories' id = db.Column( db.Integer, name='Id', primary_key=True ) order = db.Column( db.Integer, name='Order', nullable=False ) name = db.Column( db.String(255), name='Name' ) parent_id = db.Column( db.ForeignKey('Categories.Id'), name='Parent_Id', index=True ) parent = db.relationship('Category', remote_side=[id]) work_types = db.relationship('WorkType', secondary='WorkTypeCategories') def to_json(self): return { 'id': self.id, 'order': self.order, 'name': self.name, 'parent': {'id': self.parent_id} if self.parent_id is not None else None, 'workTypes': list(map(lambda wt: wt.id, self.work_types)) } @classmethod def from_json(cls, data): return cls( id=data.get('id', None), order=data['order'], name=data['name'], parent_id=data['parent'], work_types=WorkType.query.filter(WorkType.id in data['workTypes']) )
class ApplicationEvent(ModelBase): application_id = db.Column( db.Integer, db.ForeignKey('application.id', ondelete='CASCADE'), nullable=False, ) event_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) event_type = db.Column(db.String(255), nullable=False, index=True) event_description = db.Column(db.String(255), nullable=False, index=True) application_notes = db.Column(db.Text, nullable=True) contacts = db.relationship('ApplicationContact', secondary=event_contacts, backref=db.backref('events', lazy='dynamic'), lazy='dynamic')
class PositionAccomplishment(ModelBase): position_id = db.Column( db.Integer, db.ForeignKey('resume_position.id', ondelete='CASCADE'), nullable=False, ) description = db.Column(db.Text, nullable=False) resume_position = db.relationship('ResumePosition', backref=db.backref('accomplishments', lazy='dynamic')) keywords = db.relationship('Keyword', secondary=accomplishment_keyword, backref=db.backref('accomplishments', lazy='dynamic'), lazy='dynamic')