diff --git a/alembic/README b/alembic/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 000000000..6626bfd0c --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,78 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = None + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 000000000..55df2863d --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/lib/debug.py b/lib/debug.py index 4f922eb69..9f85f7b32 100644 --- a/lib/debug.py +++ b/lib/debug.py @@ -1,9 +1,12 @@ #!/usr/bin/env python3 from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker -from models import Company, Dev +from models import Company, Dev, Freebie if __name__ == '__main__': engine = create_engine('sqlite:///freebies.db') + Session = sessionmaker(bind=engine) + session = Session() import ipdb; ipdb.set_trace() diff --git a/lib/freebies.db b/lib/freebies.db index 12beb1c96..4f6bb3d5d 100644 Binary files a/lib/freebies.db and b/lib/freebies.db differ diff --git a/lib/migrations/versions/5f72c58bf48c_create_companies_devs.py b/lib/migrations/versions/5f72c58bf48c_create_companies_devs.py index c191bb2f9..e821bbca5 100644 --- a/lib/migrations/versions/5f72c58bf48c_create_companies_devs.py +++ b/lib/migrations/versions/5f72c58bf48c_create_companies_devs.py @@ -29,6 +29,13 @@ def upgrade() -> None: sa.Column('name', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id') ) + op.create_table('freebies', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('item_name', sa.String()), + sa.Column('value', sa.Integer()), + sa.Column('company_id', sa.Integer(), sa.ForeignKey('companies.id')), + sa.Column('dev_id', sa.Integer(), sa.ForeignKey('devs.id')) + ) # ### end Alembic commands ### @@ -36,4 +43,5 @@ def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_table('devs') op.drop_table('companies') + op.drop_table('freebies') # ### end Alembic commands ### diff --git a/lib/models.py b/lib/models.py index 2681bee5a..79ef06d08 100644 --- a/lib/models.py +++ b/lib/models.py @@ -16,14 +16,49 @@ class Company(Base): name = Column(String()) founding_year = Column(Integer()) + freebies = relationship("Freebie", back_populates="company") + def __repr__(self): return f'' + + def give_freebie(self, dev, item_name, value): + freebie = Freebie(item_name=item_name, value=value, dev=dev, company=self) + return freebie + class Dev(Base): __tablename__ = 'devs' id = Column(Integer(), primary_key=True) name= Column(String()) + freebies = relationship("Freebie", back_populates="dev") + 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, other_dev, freebie): + if freebie in self.freebies: + freebie.dev = other_dev + else: + raise ValueError(f"{self.name} does not own this freebie.") + + +class Freebie(Base): + __tablename__ = 'freebies' + + id = Column(Integer, primary_key=True) + item_name = Column(String) + value = Column(Integer) + company_id = Column(Integer, ForeignKey('companies.id')) + dev_id = Column(Integer, ForeignKey('devs.id')) + + company = relationship("Company", back_populates="freebies") + dev = relationship("Dev", back_populates="freebies") + + 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..fb87bdbae 100644 --- a/lib/seed.py +++ b/lib/seed.py @@ -1,3 +1,27 @@ #!/usr/bin/env python3 +from sqlalchemy.orm import sessionmaker +from models import Company, Dev, Freebie +from sqlalchemy import create_engine # Script goes here! +engine = create_engine('sqlite:///freebies.db') +Session = sessionmaker(bind=engine) +session = Session() + +session.query(Freebie).delete() +session.query(Company).delete() +session.query(Dev).delete() + +dev1 = Dev(name="Alice") +dev2 = Dev(name="Bob") +dev3 = Dev(name="John") + +company1 = Company(name="Centrino", founding_year=2012) +company2 = Company(name="Google", founding_year=1998) + +freebie1 = Freebie(item_name="T-shirt", value=10, company=company1, dev=dev1) +freebie2 = Freebie(item_name="Sticker", value=1, company=company1, dev=dev2) +freebie3 = Freebie(item_name="Mug", value=15, company=company2, dev=dev1) + +session.add_all([dev1, dev2, dev3, company1, company2, freebie1, freebie2, freebie3]) +session.commit() \ No newline at end of file