diff --git a/lib/alembic.ini b/lib/alembic.ini deleted file mode 100644 index 953863ddd..000000000 --- a/lib/alembic.ini +++ /dev/null @@ -1,105 +0,0 @@ -# A generic, single database configuration. - -[alembic] -# path to migration scripts -script_location = migrations - -# 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-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 = - -# 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 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 - - -[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 - -# Logging configuration -[loggers] -keys = root,sqlalchemy,alembic - -[handlers] -keys = console - -[formatters] -keys = generic - -[logger_root] -level = WARN -handlers = console -qualname = - -[logger_sqlalchemy] -level = WARN -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/lib/company.py b/lib/company.py new file mode 100644 index 000000000..566341799 --- /dev/null +++ b/lib/company.py @@ -0,0 +1,116 @@ +import sqlite3 +from freebie import Freebie + +CONN = sqlite3.connect("./lib/freebies.db") +CURSOR = CONN.cursor() + +class Company(): + def __init__(self, name, founding_year, id=None): + self.set_name(name) + self.founding_year = founding_year + self.id = id + + #!Validate the properties + def get_name(self): + return self._name + + def set_name(self, new_name): + if type(new_name) == str and len(new_name) > 0: + self._name = new_name + else: + print("name is not a string") + raise Exception() + + name = property(get_name, set_name) + + #!Another way to make a property + @property + def founding_year(self): + return self._founding_year + + @founding_year.setter + def founding_year(self, new_year): + if type(new_year) == int and new_year > 0: + self._founding_year = new_year + else: + raise Exception("Incorrect Year") + + #!new from db + @classmethod + def new_from_db(cls, row): + company_row = cls(name=row[1], founding_year=row[2], id = row[0]) + return company_row + + + + # Create a table that companies get saved into: + @classmethod + def create_table(cls): + sql = """ + CREATE TABLE IF NOT EXISTS companies ( + id INTEGER PRIMARY KEY, + name TEXT, + founding_year INTEGER + ) + """ + CURSOR.execute(sql) + + # Create a drop table to refresh every time code is ran + @classmethod + def drop_table(cls): + sql = "DROP TABLE IF EXISTS companies" + CURSOR.execute(sql) + + # Create option to save information to Table once created: + def save(self): + sql = """ + INSERT INTO companies (name, founding_year) + VALUES (?, ?) + """ + CURSOR.execute(sql, (self.name, self.founding_year)) + CONN.commit() + self.id = CURSOR.lastrowid + + #! Create a freebies property for company + def get_freebies(self): + sql = """ + SELECT * FROM freebies + WHERE comp_id = ? + """ + found_freebies = CURSOR.execute(sql, (self.id,)).fetchall() + return found_freebies + + freebies = property(get_freebies) + + #! Create a devs property for company + def get_devs(self): + sql = """ + SELECT devs.id, devs.name + FROM devs + INNER JOIN freebies + ON devs.id = freebies.dev_id + WHERE freebies.comp_id = ? + """ + found_devs = CURSOR.execute(sql, (self.id,)).fetchall() + return found_devs + + devs = property(get_devs) + + + #*Aggregate Methods + def give_freebie(self,Dev,item_name,value): + item_name = Freebie.create(item_name,value,self.id,Dev.id) + return item_name + + @classmethod + def oldest_company(cls): + sql = """ + SELECT * + FROM companies + ORDER BY founding_year + ASC LIMIT 1 + """ + oldest_comp = CURSOR.execute(sql).fetchone() + return oldest_comp + + \ No newline at end of file diff --git a/lib/debug.py b/lib/debug.py index 4f922eb69..83b6b77f8 100644 --- a/lib/debug.py +++ b/lib/debug.py @@ -1,9 +1,54 @@ #!/usr/bin/env python3 -from sqlalchemy import create_engine +# from sqlalchemy import create_engine + +# from models import Company, Dev, Freebies + +from freebie import Freebie +from company import Company +from dev import Dev + +#! Drop all tables when first started to see if it works: +Company.drop_table() +Dev.drop_table() +Freebie.drop_table() + +# #! Create all (3) tables to exist in the database: +Company.create_table() +Dev.create_table() +Freebie.create_table() + + + +#! Create some dev instances +ollie = Dev("ollie") +ollie.save() +wally = Dev("Wally") +wally.save() +bill = Dev("Bill") +bill.save() + +#! Create some company instances + +docusign = Company("DocuSign", 1999) +docusign.save() +gitHub = Company("GitHub", 2002) +gitHub.save() +walmart = Company("Walmart", 1804) +walmart.save() + +#! Create some Freebie instances +koozie = Freebie("Koozie", 10, gitHub.id, bill.id) +koozie.save() +hat = Freebie("Hat", 20, gitHub.id, wally.id) +hat.save() +pen = Freebie("Pen", 1, docusign.id, bill.id) +pen.save() + + + + -from models import Company, Dev if __name__ == '__main__': - engine = create_engine('sqlite:///freebies.db') import ipdb; ipdb.set_trace() diff --git a/lib/dev.py b/lib/dev.py new file mode 100644 index 000000000..6392ae877 --- /dev/null +++ b/lib/dev.py @@ -0,0 +1,93 @@ +import sqlite3 + +CONN = sqlite3.connect("./lib/freebies.db") +CURSOR = CONN.cursor() + +from freebie import Freebie + +#* All Dev Table in this color +class Dev(): + def __init__(self, name, id=None): + self.name = name + self.id = id + + @property + def name(self): + return self._name + + @name.setter + def name(self,new_name): + if type(new_name) == str: + self._name = new_name + else: + print("Name entered is not a string") + + + #* Create a table that devs get saved into: + @classmethod + def create_table(cls): + sql = """ + CREATE TABLE IF NOT EXISTS devs ( + id INTEGER PRIMARY KEY, + name TEXT + ) + """ + CURSOR.execute(sql) + + #* Create a drop table to refresh every time code is ran + @classmethod + def drop_table(cls): + sql = "DROP TABLE IF EXISTS devs" + CURSOR.execute(sql) + + #* Create option to save information to Table once created: + def save(self): + sql = """ + INSERT INTO devs (name) + VALUES (?) + """ + CURSOR.execute(sql, (self.name,)) #* leave comma in when one item + CONN.commit() + self.id = CURSOR.lastrowid + + #! Create a freebies property for devs + def get_freebies(self): + sql = """ + SELECT * FROM freebies + WHERE dev_id = ? + """ + found_freebies = CURSOR.execute(sql, (self.id,)).fetchall() + return found_freebies + + freebies = property(get_freebies) + + #! Create a devs property for company + def get_companies(self): + sql = """ + SELECT companies.id, companies.name + FROM companies + INNER JOIN freebies + ON companies.id = freebies.comp_id + WHERE freebies.dev_id = ? + """ + found_companies = CURSOR.execute(sql, (self.id,)).fetchall() + return found_companies + + companies = property(get_companies) + + #* Aggregate Methods + def received_one(self, item_name): + all_freebies = [freebie[1].lower() for freebie in self.freebies] + if item_name.lower() in all_freebies: + return True + else: + return False + + def give_away(self, Dev, Freebie): + if self.id == Freebie.dev_id: + Freebie.update_dev_id(Dev.id) + return (f"{Freebie.item_name} now belongs to {Dev.name}") + else: + return "Freebie Doesn't Belong to you" + + \ No newline at end of file diff --git a/lib/freebie.py b/lib/freebie.py new file mode 100644 index 000000000..38632e9fa --- /dev/null +++ b/lib/freebie.py @@ -0,0 +1,120 @@ +import sqlite3 + +CONN = sqlite3.connect("./lib/freebies.db") +CURSOR = CONN.cursor() + +#! Create Freebies Class +class Freebie(): + def __init__(self, item_name, value, comp_id=None, dev_id=None, id=None): + self.id = id + self.item_name = item_name + self.value = value + self.comp_id = comp_id + self.dev_id = dev_id + + @property + def item_name(self): + return self._item_name + @item_name.setter + def item_name(self,new_item_name): + if type(new_item_name)==str: + self._item_name = new_item_name + else: + raise Exception("Bad Item Name...") + + @property + def dev_id(self): + return self._dev_id + @dev_id.setter + def dev_id(self, dev_id): + all_devs = CURSOR.execute("SELECT id from devs").fetchall() + all_ids = [row[0] for row in all_devs] + if dev_id in all_ids: + self._dev_id = dev_id + else: + raise Exception("No Dev with id provided") + + + #! Create a table that freebies get saved into: + @classmethod + def create_table(cls): + sql = """ + CREATE TABLE IF NOT EXISTS freebies ( + id INTEGER PRIMARY KEY, + item_name TEXT, + value INTEGER, + comp_id INTEGER, + dev_id INTEGER + ) + """ + + CURSOR.execute(sql) + + #! Create a drop table to refresh every time code is ran + @classmethod + def drop_table(cls): + sql = "DROP TABLE IF EXISTS freebies" + CURSOR.execute(sql) + + #! Create option to save information to Table once created: + def save(self): + sql = """ + INSERT INTO freebies (item_name, value, comp_id, dev_id) + VALUES (?, ?, ?, ?) + """ + CURSOR.execute(sql, (self.item_name, self.value, self.comp_id, self.dev_id)) + CONN.commit() + self.id = CURSOR.lastrowid + #! Create function that makes instance and saves to database + @classmethod + def create(cls,item_name, value, comp_id, dev_id): + item_name = cls(item_name, value, comp_id, dev_id) + item_name.save() + return item_name + + + #! Create a dev property for frisby. + def get_dev(self): + sql = """ + SELECT * FROM devs + WHERE id = ? + LIMIT 1 + """ + found_dev = CURSOR.execute(sql, (self.dev_id,)).fetchone() + return found_dev + + dev = property(get_dev) + + #! Create a company property for frisby + def get_company(self): + sql = """ + SELECT * FROM companies + WHERE id = ? + LIMIT 1 + """ + found_company = CURSOR.execute(sql, (self.comp_id,)).fetchone() + from company import Company + return Company.new_from_db(found_company) + + company = property(get_company) + + + #! Create an update freebie + def update_dev_id(self,new_dev_id): + sql = """ + UPDATE freebies + SET dev_id = ? + WHERE id = ? + """ + CURSOR.execute(sql, (new_dev_id, self.id)) + CONN.commit() + + + + #*Aggregate Methods + def print_details(self): + print(f"{self.dev[1]} owns a {self.item_name} from {self.company[1]}") + + + + \ No newline at end of file diff --git a/lib/freebies.db b/lib/freebies.db index 12beb1c96..5c61b51f1 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 deleted file mode 100644 index 2681bee5a..000000000 --- a/lib/models.py +++ /dev/null @@ -1,29 +0,0 @@ -from sqlalchemy import ForeignKey, Column, Integer, String, MetaData -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) - -class Company(Base): - __tablename__ = 'companies' - - id = Column(Integer(), primary_key=True) - name = Column(String()) - founding_year = Column(Integer()) - - def __repr__(self): - return f'' - -class Dev(Base): - __tablename__ = 'devs' - - id = Column(Integer(), primary_key=True) - name= Column(String()) - - def __repr__(self): - return f'' diff --git a/lib/seed.py b/lib/seed.py deleted file mode 100644 index b16becbbb..000000000 --- a/lib/seed.py +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env python3 - -# Script goes here!