From 4f5da6f1ce8002a271d7b3ce9943ae437531be3a Mon Sep 17 00:00:00 2001 From: christopherchege Date: Wed, 28 May 2025 23:24:15 +0300 Subject: [PATCH 1/2] first commit --- lib/models.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/models.py b/lib/models.py index 2681bee5a..af565dc7e 100644 --- a/lib/models.py +++ b/lib/models.py @@ -22,6 +22,7 @@ def __repr__(self): class Dev(Base): __tablename__ = 'devs' + id = Column(Integer(), primary_key=True) name= Column(String()) From 579e6308bfaed9198a6d0cfa0f9aa39e16721047 Mon Sep 17 00:00:00 2001 From: christopherchege Date: Wed, 4 Jun 2025 00:17:58 +0300 Subject: [PATCH 2/2] defined models,configure alembic,create migrations andimplement core methods --- alembic.ini | 119 +++++++++++++++++++++++++ alembic/README | 1 + alembic/__pycache__/env.cpython-38.pyc | Bin 0 -> 1791 bytes alembic/env.py | 75 ++++++++++++++++ alembic/script.py.mako | 26 ++++++ lib/debug.py | 12 +-- lib/models.py | 59 ++++++++---- lib/seed.py | 23 +++++ 8 files changed, 294 insertions(+), 21 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/README create mode 100644 alembic/__pycache__/env.cpython-38.pyc create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 000000000..b0295b0b3 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,119 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +# Use forward slashes (/) also on windows to provide an os agnostic path +script_location = alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to alembic/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +# version_path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +version_path_separator = os + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = sqlite:///freebies.db + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S 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/__pycache__/env.cpython-38.pyc b/alembic/__pycache__/env.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b99251facf15928ea3a8ac0f4f9f640e8d6e99fc GIT binary patch literal 1791 zcmZux&5j&35VpH}x_f$NXMd7iA`Zy6%}8iKNZb&F4Im<+RS1bdBcztM?Va(&?H+7T zb~j2cgbRl#FTi2u$Xjsc5q#yuD%jQ7{89_z#Efal9MR!INC_g^54RLT$h%%ZQ*aO-zC4;o@uoC?YBHtJMN zj$ygS)kG*>p6aG9s~`qxGH)6Qa|RO2&+XG_H1gsjYBSPCg;^fPe! zV4+AYCYoB&C_{uIht27!gq#ma-7r2X3IgNdR2b6cztG$eJLP`qlP71wPRVRxETQDl zgD-+TRg9^|rG$V-T2*{*>51fF*OY5cs3B)u$`K()7sNak^SMxy z5U}+`D$PT-VapjOtWk%S@F!dm#W{m4J~{gM{ykzFasuw2P$7MU^-1nhDIx!6lm3XG z^J-!F?I8)_c`a;+HWA*Vu{wlryevdCl@@bLnuVP&?Aqzmf%#5SSxtF;FII<5u;h zWAz^t-&4>R->-sBSNpJ?j;?hrO+VQZjW2llI0C7FvXVZppdu@A5p~Oa}6K|CtFQmK= zPQxqWvkG|7JKm2+g5LGScMKx-))D 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..fbc4b07dc --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${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..478393341 100644 --- a/lib/debug.py +++ b/lib/debug.py @@ -1,9 +1,11 @@ #!/usr/bin/env python3 - +from models import Company, Dev, Freebie +from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine -from models import Company, Dev +engine = create_engine('sqlite:///freebies.db') +Session = sessionmaker(bind=engine) +session = Session() + +import ipdb; ipdb.set_trace() -if __name__ == '__main__': - engine = create_engine('sqlite:///freebies.db') - import ipdb; ipdb.set_trace() diff --git a/lib/models.py b/lib/models.py index af565dc7e..54200cc94 100644 --- a/lib/models.py +++ b/lib/models.py @@ -1,30 +1,57 @@ -from sqlalchemy import ForeignKey, Column, Integer, String, MetaData + +from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base -convention = { - "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", -} -metadata = MetaData(naming_convention=convention) - -Base = declarative_base(metadata=metadata) +Base = declarative_base() 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) + + freebies = relationship('Freebie', backref='company') + + @property + def devs(self): + return list({freebie.dev for freebie in self.freebies}) + + def give_freebie(self, dev, item_name, value): + return Freebie(item_name=item_name, value=value, dev=dev, company=self) - def __repr__(self): - return f'' + @classmethod + def oldest_company(cls, session): + return session.query(cls).order_by(cls.founding_year).first() class Dev(Base): __tablename__ = 'devs' + id = Column(Integer, primary_key=True) + name = Column(String) + + freebies = relationship('Freebie', backref='dev') + + @property + def companies(self): + return list({freebie.company for freebie in self.freebies}) + + def received_one(self, item_name): + return any(f.item_name == item_name for f in self.freebies) + + def give_away(self, dev, freebie): + if freebie in self.freebies: + freebie.dev = dev + +class Freebie(Base): + __tablename__ = 'freebies' - id = Column(Integer(), primary_key=True) - name= Column(String()) + 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')) - 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..67897443c 100644 --- a/lib/seed.py +++ b/lib/seed.py @@ -1,3 +1,26 @@ #!/usr/bin/env python3 +from models import Company, Dev, Freebie +from sqlalchemy.orm import sessionmaker +from sqlalchemy import create_engine + +engine = create_engine('sqlite:///freebies.db') +Session = sessionmaker(bind=engine) +session = Session() + +c1 = Company(name="Apple", founding_year=1976) +c2 = Company(name="Google", founding_year=1998) + +d1 = Dev(name="Alice") +d2 = Dev(name="Bob") + +session.add_all([c1, c2, d1, d2]) +session.commit() + +f1 = c1.give_freebie(d1, "Sticker", 1) +f2 = c2.give_freebie(d1, "T-shirt", 10) +f3 = c2.give_freebie(d2, "Water Bottle", 5) + +session.add_all([f1, f2, f3]) +session.commit() # Script goes here!