From 1eca0b93b00233980befac98aba57237a37d7b89 Mon Sep 17 00:00:00 2001 From: Brian Ratemo Magucha Date: Sun, 15 Sep 2024 19:32:57 +0300 Subject: [PATCH] . --- lib/freebies.db | Bin 20480 -> 28672 bytes .../8cc29a6875d7_create_freebies_table.py | 63 ++++++++++++++++++ lib/models.py | 56 ++++++++++++++-- lib/seed.py | 28 ++++++++ 4 files changed, 142 insertions(+), 5 deletions(-) create mode 100644 lib/migrations/versions/8cc29a6875d7_create_freebies_table.py diff --git a/lib/freebies.db b/lib/freebies.db index 12beb1c963e832db481e7a7493e3029e691ac4dc..3569c6995d1e853d6a14842032b2c0763c47b5d9 100644 GIT binary patch literal 28672 zcmeI)O=}ZD7zgl~yzC}vlPyRIDy2iAkWdwD(bj`#8n-nVQ@crpUR*YtiCvm(YMKOl zY>NlKfH!ab2wuE<@Fob}Jc;Mxp@>Ik^JaJH3zR@h{VyG|`%L!PXMQt#SduiqoV6O9 zm235?(O@%VgiuNzGDZlAiYAK|6pe}&5iKBEZ*yX&ZBcTo^)?#2MuI~JM2RXNhu;ky z#NH3RIPFCALjVF0fB*y_009U<00M&%*dCYU`1m;8i8hR4g`2hNhGAQLv%e#!H8oXG zSs^u_RoO&8KEV=^uvKE2TtQt_HI`c{u-r;EdxJ&7wo&Emc}hz^PPseEwWeLN?3el$ zH|j^8`b^6_O=+v_iMq-XRw)@t?$V$f9~+}@R@xPo>zo%wfxTDBRbMZ9LUG~|r>Y-Y zVaupA`H_{CcuPNKyd9LSrYD??Su<-Mxl!rciv9im9zbx&KxLz$nId)+nKZ2vK${BrP~kM ztH7zvX#v;lPdK47EllqeMUvY|D#xd$=uWtOL8HQ}Ma$G%yuNAGY|o+3Rfeb2S&QA% zbh}yY-580P>7?tfIkY4^8T5^HletPfluz6u_kB`)d5RLtF7el!uPS1R>qfItYai?0 zWVby5znGJdGcV3VK2?4Z@rMlp5P$##AOHafKmY;|fB*y_0D(&)5Tm}yIn$iJXWX5e zy;GWXKGeta|0S7R3;lt1W&gcJ<@|h^Vm3`%> z@?H5V4zNK00uX=z1Rwwb2tWV=5P$##AaEfCLXw}vQx(hPpWae}lUD+2=q2*UvLL>*&MRtCLzSzi7h3@m(74E((OJNfGQq&5o*EaTNk zW?>f>6=iJHEJ;ktNli&DD+Xa!=O9U9Y1z!n|6G8_G|k*7+0-H_&BP*klfoB%A!Gqw TkaGn#Gdld@pA^8t1Z4sMS$H)p diff --git a/lib/migrations/versions/8cc29a6875d7_create_freebies_table.py b/lib/migrations/versions/8cc29a6875d7_create_freebies_table.py new file mode 100644 index 000000000..4066d709a --- /dev/null +++ b/lib/migrations/versions/8cc29a6875d7_create_freebies_table.py @@ -0,0 +1,63 @@ +"""Create freebies table + +Revision ID: 8cc29a6875d7 +Revises: 5f72c58bf48c +Create Date: 2024-09-15 15:48:24.812649 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '8cc29a6875d7' +down_revision = '5f72c58bf48c' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('freebies', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('item_name', sa.String(), nullable=False), + sa.Column('value', sa.Integer(), nullable=False), + sa.Column('dev_id', sa.Integer(), nullable=False), + sa.Column('company_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['company_id'], ['companies.id'], name=op.f('fk_freebies_company_id_companies')), + sa.ForeignKeyConstraint(['dev_id'], ['devs.id'], name=op.f('fk_freebies_dev_id_devs')), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('companies', schema=None) as batch_op: + batch_op.alter_column('name', + existing_type=sa.VARCHAR(), + nullable=False) + batch_op.alter_column('founding_year', + existing_type=sa.INTEGER(), + nullable=False) + + with op.batch_alter_table('devs', schema=None) as batch_op: + batch_op.alter_column('name', + existing_type=sa.VARCHAR(), + nullable=False) + + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('devs', schema=None) as batch_op: + batch_op.alter_column('name', + existing_type=sa.VARCHAR(), + nullable=True) + + with op.batch_alter_table('companies', schema=None) as batch_op: + batch_op.alter_column('founding_year', + existing_type=sa.INTEGER(), + nullable=True) + batch_op.alter_column('name', + existing_type=sa.VARCHAR(), + nullable=True) + + op.drop_table('freebies') + # ### end Alembic commands ### diff --git a/lib/models.py b/lib/models.py index 2681bee5a..94bd07fea 100644 --- a/lib/models.py +++ b/lib/models.py @@ -12,18 +12,64 @@ class Company(Base): __tablename__ = 'companies' - id = Column(Integer(), primary_key=True) - name = Column(String()) - founding_year = Column(Integer()) + id = Column(Integer, primary_key=True) + name = Column(String) + founding_year = Column(Integer) + + # Relationships + freebies = relationship('Freebie', back_populates='company') + devs = relationship('Dev', secondary='freebies', back_populates='companies') def __repr__(self): return f'' + def give_freebie(self, dev, item_name, value): + freebie = Freebie(item_name=item_name, value=value, dev_id=dev.id, company_id=self.id) + session.add(freebie) + session.commit() + + @classmethod + def oldest_company(cls): + return session.query(cls).order_by(cls.founding_year).first() + + class Dev(Base): __tablename__ = 'devs' - id = Column(Integer(), primary_key=True) - name= Column(String()) + id = Column(Integer, primary_key=True) + name = Column(String) + + # Relationships + freebies = relationship('Freebie', back_populates='dev') + companies = relationship('Company', secondary='freebies', back_populates='devs') def __repr__(self): return f'' + + def received_one(self, item_name): + return any(freebie.item_name == item_name for freebie in self.freebies) + + def give_away(self, dev, freebie): + if freebie.dev_id == self.id: + freebie.dev_id = dev.id + session.commit() + + +class Freebie(Base): + __tablename__ = 'freebies' + + id = Column(Integer, primary_key=True) + item_name = Column(String) + value = Column(Integer) + dev_id = Column(Integer, ForeignKey('devs.id')) + company_id = Column(Integer, ForeignKey('companies.id')) + + # Relationships + dev = relationship('Dev', back_populates='freebies') + company = relationship('Company', back_populates='freebies') + + def __repr__(self): + return f'' + + def print_details(self): + return f'{self.dev.name} owns a {self.item_name} from {self.company.name}' diff --git a/lib/seed.py b/lib/seed.py index b16becbbb..db12966ce 100644 --- a/lib/seed.py +++ b/lib/seed.py @@ -1,3 +1,31 @@ #!/usr/bin/env python3 # Script goes here! +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from models import Base, Company, Dev, Freebie + +# Set up the database +DATABASE_URL = "sqlite:///freebies.db" +engine = create_engine(DATABASE_URL, echo=True) +Session = sessionmaker(bind=engine) +session = Session() + +# Create tables +Base.metadata.create_all(engine) + +# Create sample data +company1 = Company(name="TechCorp", founding_year=1999) +dev1 = Dev(name="Alice") + +session.add(company1) +session.add(dev1) +session.commit() + +# Add a freebie +company1.give_freebie(dev1, "T-Shirt", 10) + +# Test methods +print(dev1.received_one("T-Shirt")) # Should print True +print(Freebie.query.first().print_details()) # Should print 'Alice owns a T-Shirt from TechCorp' +print(Company.oldest_company()) # Should print the oldest company