diff --git a/lib/__init__.py b/lib/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/lib/__pycache__/__init__.cpython-38.pyc b/lib/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 000000000..b75b39c7d Binary files /dev/null and b/lib/__pycache__/__init__.cpython-38.pyc differ diff --git a/lib/__pycache__/database.cpython-38.pyc b/lib/__pycache__/database.cpython-38.pyc new file mode 100644 index 000000000..414fb61f2 Binary files /dev/null and b/lib/__pycache__/database.cpython-38.pyc differ diff --git a/lib/__pycache__/models.cpython-38.pyc b/lib/__pycache__/models.cpython-38.pyc new file mode 100644 index 000000000..2c09ec257 Binary files /dev/null and b/lib/__pycache__/models.cpython-38.pyc differ diff --git a/lib/alembic.ini b/lib/alembic.ini index 953863ddd..c2ecb61b5 100644 --- a/lib/alembic.ini +++ b/lib/alembic.ini @@ -1,75 +1,36 @@ -# A generic, single database configuration. +# A generic, single-database configuration. [alembic] -# path to migration scripts -script_location = migrations +# Path to migration scripts +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 +# Ensure the SQLAlchemy database URL is absolute +sqlalchemy.url = sqlite:///lib/freebies.db + +# Uncomment to prepend date and time to migration filenames # 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 with the current 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-dateutil library that can be -# installed by adding `alembic[tz]` to the pip requirements -# string value is passed to dateutil.tz.gettz() -# leave blank for localtime +# Timezone for rendering timestamps # 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 +# Set to 'true' to run the environment during the 'revision' command # 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 migrations/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:migrations/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 = os # Use os.pathsep. Default configuration used for new projects. - -# the output encoding used when revision files -# are written from script.py.mako -# output_encoding = utf-8 - -sqlalchemy.url = sqlite:///freebies.db +# Max length of characters for migration "slug" +# truncate_slug_length = 40 +# Specify version locations if needed +# version_locations = alembic/versions -[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 +# Version path separator (default uses OS-specific separator) +version_path_separator = / -# 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 +# Output encoding when writing migration files +# output_encoding = utf-8 -# Logging configuration [loggers] keys = root,sqlalchemy,alembic @@ -103,3 +64,12 @@ formatter = generic [formatter_generic] format = %(levelname)-5.5s [%(name)s] %(message)s datefmt = %H:%M:%S + +[post_write_hooks] +# Formatting with "black" +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + + diff --git a/lib/app.py b/lib/app.py new file mode 100644 index 000000000..0c220e30e --- /dev/null +++ b/lib/app.py @@ -0,0 +1,72 @@ +from flask import Flask, jsonify, request +from database import SessionLocal +from models import Company, Dev, Freebie + +app = Flask(__name__) + +# Homepage route +@app.route("/", methods=["GET"]) +def home(): + return jsonify({"message": "Welcome to the Freebie Tracker API!"}) + +# Prevent favicon 404 error +@app.route("/favicon.ico") +def favicon(): + return "", 204 # Returns an empty response with status code 204 (No Content) + +@app.route("/companies", methods=["GET"]) +def get_companies(): + session = SessionLocal() + try: + companies = session.query(Company).all() + response = [{"id": c.id, "name": c.name, "founding_year": c.founding_year} for c in companies] + return jsonify(response) + finally: + session.close() + +@app.route("/devs", methods=["GET"]) +def get_devs(): + session = SessionLocal() + try: + devs = session.query(Dev).all() + response = [{"id": d.id, "name": d.name} for d in devs] + return jsonify(response) + finally: + session.close() + +@app.route("/freebies", methods=["GET"]) +def get_freebies(): + session = SessionLocal() + try: + freebies = session.query(Freebie).all() + response = [{"id": f.id, "item_name": f.item_name, "value": f.value, "dev": f.dev.name, "company": f.company.name} for f in freebies] + return jsonify(response) + finally: + session.close() + +@app.route("/give_freebie", methods=["POST"]) +def give_freebie(): + data = request.json + + # Validate request body + if "dev_id" not in data or "company_id" not in data: + return jsonify({"error": "Missing dev_id or company_id"}), 400 + + session = SessionLocal() + try: + dev = session.query(Dev).filter_by(id=data["dev_id"]).first() + company = session.query(Company).filter_by(id=data["company_id"]).first() + + if not dev or not company: + return jsonify({"error": "Dev or Company not found"}), 404 + + new_freebie = Freebie(item_name=data["item_name"], value=data["value"], dev=dev, company=company) + session.add(new_freebie) + session.commit() + + return jsonify({"message": "Freebie given successfully!"}), 201 + finally: + session.close() + +if __name__ == "__main__": + app.run(debug=True) diff --git a/lib/database.py b/lib/database.py new file mode 100644 index 000000000..e1e4a700a --- /dev/null +++ b/lib/database.py @@ -0,0 +1,9 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker, declarative_base + +DATABASE_URL = "sqlite:///freebies.db" # Adjust this if using a different database + +engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) +SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) + +Base = declarative_base() diff --git a/lib/debug.py b/lib/debug.py index 4f922eb69..0c99b1dee 100644 --- a/lib/debug.py +++ b/lib/debug.py @@ -1,9 +1,26 @@ -#!/usr/bin/env python3 +from database import SessionLocal +from models import Company, Dev, Freebie -from sqlalchemy import create_engine +session = SessionLocal() -from models import Company, Dev +# Fetch instances to test relationships +dev = session.query(Dev).first() +company = session.query(Company).first() +freebie = session.query(Freebie).first() -if __name__ == '__main__': - engine = create_engine('sqlite:///freebies.db') - import ipdb; ipdb.set_trace() +if dev: + print(f"Dev: {dev.name}") +else: + print("No developers found in the database.") + +if company: + print(f"Company: {company.name}") +else: + print("No companies found in the database.") + +if freebie: + print(f"Freebie: {freebie.print_details()}") +else: + print("No freebies found in the database.") + +session.close() diff --git a/lib/freebies.db b/lib/freebies.db index 12beb1c96..ee1b6532a 100644 Binary files a/lib/freebies.db and b/lib/freebies.db differ diff --git a/lib/migrations/README b/lib/migrations/README deleted file mode 100644 index 98e4f9c44..000000000 --- a/lib/migrations/README +++ /dev/null @@ -1 +0,0 @@ -Generic single-database configuration. \ No newline at end of file diff --git a/lib/migrations/env.py b/lib/migrations/env.py deleted file mode 100644 index c7aab9656..000000000 --- a/lib/migrations/env.py +++ /dev/null @@ -1,79 +0,0 @@ -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 -from models import Base -target_metadata = Base.metadata - -# 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, render_as_batch=True, - ) - - with context.begin_transaction(): - context.run_migrations() - - -if context.is_offline_mode(): - run_migrations_offline() -else: - run_migrations_online() diff --git a/lib/migrations/script.py.mako b/lib/migrations/script.py.mako deleted file mode 100644 index 55df2863d..000000000 --- a/lib/migrations/script.py.mako +++ /dev/null @@ -1,24 +0,0 @@ -"""${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/migrations/versions/5f72c58bf48c_create_companies_devs.py b/lib/migrations/versions/5f72c58bf48c_create_companies_devs.py deleted file mode 100644 index c191bb2f9..000000000 --- a/lib/migrations/versions/5f72c58bf48c_create_companies_devs.py +++ /dev/null @@ -1,39 +0,0 @@ -"""create companies, devs - -Revision ID: 5f72c58bf48c -Revises: 7a71dbf71c64 -Create Date: 2023-03-15 15:06:20.944586 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '5f72c58bf48c' -down_revision = '7a71dbf71c64' -branch_labels = None -depends_on = None - - -def upgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('companies', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('name', sa.String(), nullable=True), - sa.Column('founding_year', sa.Integer(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - op.create_table('devs', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('name', sa.String(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - # ### end Alembic commands ### - - -def downgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('devs') - op.drop_table('companies') - # ### end Alembic commands ### diff --git a/lib/migrations/versions/7a71dbf71c64_create_db.py b/lib/migrations/versions/7a71dbf71c64_create_db.py deleted file mode 100644 index 23e0a655b..000000000 --- a/lib/migrations/versions/7a71dbf71c64_create_db.py +++ /dev/null @@ -1,24 +0,0 @@ -"""create db - -Revision ID: 7a71dbf71c64 -Revises: -Create Date: 2023-03-15 15:05:55.516631 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '7a71dbf71c64' -down_revision = None -branch_labels = None -depends_on = None - - -def upgrade() -> None: - pass - - -def downgrade() -> None: - pass diff --git a/lib/models.py b/lib/models.py index 2681bee5a..fb078ce2d 100644 --- a/lib/models.py +++ b/lib/models.py @@ -1,29 +1,74 @@ -from sqlalchemy import ForeignKey, Column, Integer, String, MetaData -from sqlalchemy.orm import relationship, backref -from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy import ForeignKey, Column, Integer, String, MetaData, create_engine, Table +from sqlalchemy.orm import relationship, sessionmaker, declarative_base +# Define naming convention for foreign keys and constraints convention = { "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", } metadata = MetaData(naming_convention=convention) +# Use the updated Base with metadata Base = declarative_base(metadata=metadata) +# Define an explicit association table for many-to-many relationship +dev_company_association = Table( + "dev_company_association", + Base.metadata, + Column("dev_id", Integer, ForeignKey("devs.id"), primary_key=True), + Column("company_id", Integer, ForeignKey("companies.id"), primary_key=True), +) + +# Freebie Model (Entity Table, not a pure association table) +class Freebie(Base): + __tablename__ = 'freebies' + + id = Column(Integer, primary_key=True) + item_name = Column(String, nullable=False) + value = Column(Integer, nullable=False) + dev_id = Column(Integer, ForeignKey('devs.id')) + company_id = Column(Integer, ForeignKey('companies.id')) + + # Define relationships + dev = relationship("Dev", back_populates="freebies") + company = relationship("Company", back_populates="freebies") + +# Company Model 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, nullable=False) + founding_year = Column(Integer, nullable=False) - def __repr__(self): - return f'' + freebies = relationship("Freebie", back_populates="company") + + # Corrected many-to-many relationship + devs = relationship( + "Dev", + secondary=dev_company_association, + back_populates="companies" + ) +# Developer Model class Dev(Base): __tablename__ = 'devs' - id = Column(Integer(), primary_key=True) - name= Column(String()) + id = Column(Integer, primary_key=True) + name = Column(String, nullable=False) + + freebies = relationship("Freebie", back_populates="dev") + + # Corrected many-to-many relationship + companies = relationship( + "Company", + secondary=dev_company_association, + back_populates="devs" + ) + +# Set up database connection +engine = create_engine('sqlite:///freebies.db') +Session = sessionmaker(bind=engine) +session = Session() # Create a session instance - def __repr__(self): - return f'' +# Ensure `session` is available for import +__all__ = ["Company", "Dev", "Freebie", "session"] diff --git a/lib/seed.py b/lib/seed.py index b16becbbb..d1e438641 100644 --- a/lib/seed.py +++ b/lib/seed.py @@ -1,3 +1,43 @@ -#!/usr/bin/env python3 - -# Script goes here! +from models import Dev, Company, Freebie +from sqlalchemy.orm import sessionmaker +from sqlalchemy import create_engine + +engine = create_engine('sqlite:///freebies.db') +Session = sessionmaker(bind=engine) +session = Session() + +# Sample data +company1 = Company(name="TechCorp", founding_year=2000) +company2 = Company(name="GadgetInc", founding_year=2010) +company3 = Company(name="Google-corp", founding_year=1992) +company4 = Company(name="AWS", founding_year=2007) +company5 = Company(name="AI-solution", founding_year=2015) + + +dev1 = Dev(name="Lucas") +dev2 = Dev(name="Allie") +dev3 = Dev(name="Damien") +dev4 = Dev(name="Robert") +dev5 = Dev(name="Caleb") + + +freebie1 = Freebie(item_name="T-Shirt", value=10, company=company1, dev=dev1) +freebie2 = Freebie(item_name="A Hat", value=5, company=company2, dev=dev2) +freebie3 = Freebie(item_name="USB-Drive", value=20, company=company3, dev=dev3) +freebie4 = Freebie(item_name="A Cup", value=12, company=company4, dev=dev4) +freebie5 = Freebie(item_name="T-Shirt", value=15, company=company5, dev=dev5) + +# Add to session and commit +try: + session.bulk_save_objects([ + company1, company2, company3, company4, company5, + dev1, dev2, dev3, dev4, dev5, + freebie1, freebie2, freebie3, freebie4, freebie5 + ]) + session.commit() + print("Database seeded successfully!") +except Exception as e: + session.rollback() + print(f"Error seeding database: {e}") +finally: + session.close()