Skip to content

Commit

Permalink
created database schema for users, organisations, profile, product
Browse files Browse the repository at this point in the history
  • Loading branch information
Armolas committed Jul 18, 2024
1 parent b8befe0 commit 3a1de68
Show file tree
Hide file tree
Showing 11 changed files with 429 additions and 27 deletions.
116 changes: 116 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# 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.
# 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 = os # Use os.pathsep. Default configuration used for new projects.

# 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:///./database.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 = 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
24 changes: 8 additions & 16 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@

import os
from alembic import context
from decouple import config
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from api.db.database import Base
from api.v1.models.auth import User, BlackListToken

#from db.database import DATABASE_URL
DATABASE_URL=config('DB_URL')

from alembic import context
from api.v1.models.user import User
from api.v1.models.org import Organisation
from api.v1.models.profile import Profile
from api.v1.models.product import Product
from api.v1.models.base import Base

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
Expand Down Expand Up @@ -45,7 +41,7 @@ def run_migrations_offline() -> None:
script output.
"""
url = config.get_main_option("sqlalchemy.url", DATABASE_URL)
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
Expand All @@ -64,12 +60,8 @@ def run_migrations_online() -> None:
and associate a connection with the context.
"""

alembic_config = config.get_section(config.config_ini_section)
alembic_config['sqlalchemy.url'] = DATABASE_URL

connectable = engine_from_config(
alembic_config,
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
Expand Down
81 changes: 81 additions & 0 deletions alembic/versions/9670771a11f9_initial_migrations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""Initial migrations
Revision ID: 9670771a11f9
Revises:
Create Date: 2024-07-18 20:08:23.466008
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '9670771a11f9'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('organisations',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('products',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('price', sa.Numeric(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('username', sa.String(length=50), nullable=False),
sa.Column('email', sa.String(length=100), nullable=False),
sa.Column('password', sa.String(length=255), nullable=False),
sa.Column('first_name', sa.String(length=50), nullable=True),
sa.Column('last_name', sa.String(length=50), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email'),
sa.UniqueConstraint('username')
)
op.create_table('profiles',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('bio', sa.Text(), nullable=True),
sa.Column('phone_number', sa.String(length=50), nullable=True),
sa.Column('avatar_url', sa.String(length=100), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user_organisation',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('organisation_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['organisation_id'], ['organisations.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'organisation_id')
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user_organisation')
op.drop_table('profiles')
op.drop_table('users')
op.drop_table('products')
op.drop_table('organisations')
# ### end Alembic commands ###
23 changes: 12 additions & 11 deletions api/db/database.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
# database.py
#!/usr/bin/env python3
""" The database module
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from decouple import config
from contextlib import contextmanager
from api.v1.models.base import Base


def get_db_engine():

DB_TYPE = config("DB_TYPE")
DB_NAME = config("DB_NAME")
DB_USER = config("DB_USER")
DB_PASSWORD = config("DB_PASSWORD")
DB_HOST = config("DB_HOST")
DB_PORT = config("DB_PORT")
MYSQL_DRIVER = config("MYSQL_DRIVER")
DB_TYPE = config("DB_TYPE", "")
DB_NAME = config("DB_NAME", "")
DB_USER = config("DB_USER", "")
DB_PASSWORD = config("DB_PASSWORD", "")
DB_HOST = config("DB_HOST", "")
DB_PORT = config("DB_PORT", "")
MYSQL_DRIVER = config("MYSQL_DRIVER", "")
DATABASE_URL = ""

if DB_TYPE == "mysql":
Expand All @@ -35,13 +39,10 @@ def get_db_engine():

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=db_engine)

Base = declarative_base()


def create_database():
return Base.metadata.create_all(bind=db_engine)


def get_db():
db = SessionLocal()
try:
Expand Down
20 changes: 20 additions & 0 deletions api/v1/models/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
""" Base
"""
from sqlalchemy import (
Column,
Integer,
ForeignKey,
Table
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from datetime import datetime


Base = declarative_base()

user_organisation_association = Table('user_organisation', Base.metadata,
Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
Column('organisation_id', Integer, ForeignKey('organisations.id'), primary_key=True)
)
36 changes: 36 additions & 0 deletions api/v1/models/org.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
""" The Organisation model
"""
from sqlalchemy import (
Column,
Integer,
String,
Text,
Date,
ForeignKey,
Numeric,
DateTime,
func,
)
from sqlalchemy.orm import relationship
from datetime import datetime
from api.v1.models.base import Base, user_organisation_association


class Organisation(Base):
__tablename__ = 'organisations'

id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(50), unique=True, nullable=False)
description = Column(Text, nullable=True)
created_at = Column(DateTime, server_default=func.now())
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())

users = relationship(
"User",
secondary=user_organisation_association,
back_populates="organisations"
)

def __str__(self):
return self.name
24 changes: 24 additions & 0 deletions api/v1/models/product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
""" The Product model
"""
from sqlalchemy import (
Column,
Integer,
String,
Text,
Numeric,
DateTime,
func,
)
from datetime import datetime
from api.v1.models.base import Base


class Product(Base):
__tablename__ = 'products'

id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String, nullable=False)
description = Column(Text, nullable=True)
price = Column(Numeric, nullable=False)
created_at = Column(DateTime, nullable=False, default=func.now())
Loading

0 comments on commit 3a1de68

Please sign in to comment.