Add db & pydantic models + set up alembic

This commit is contained in:
2025-06-02 08:18:12 +02:00
parent fa0530e18c
commit aa64491313
33 changed files with 648 additions and 16 deletions
View File
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+85
View File
@@ -0,0 +1,85 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
import os
from dotenv import load_dotenv
from sqlmodel import SQLModel
from app.models import Client, Supplier, Product, Payment, Credit
load_dotenv()
# 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 = SQLModel.metadata
url = os.getenv("DATABASE_URL")
# 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.",
url=url,
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()
+28
View File
@@ -0,0 +1,28 @@
"""${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:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
@@ -0,0 +1,90 @@
"""Rebuild
Revision ID: 5840d2b52dd8
Revises:
Create Date: 2025-06-01 14:27:25.657473
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
import sqlmodel
# revision identifiers, used by Alembic.
revision: str = '5840d2b52dd8'
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:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('client',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('tin_number', sa.Integer(), nullable=False),
sa.Column('names', sqlmodel.sql.sqltypes.AutoString(length=100), nullable=False),
sa.Column('phone_number', sqlmodel.sql.sqltypes.AutoString(length=10), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('tin_number')
)
op.create_table('product',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('product_code', sqlmodel.sql.sqltypes.AutoString(length=10), nullable=False),
sa.Column('product_name', sqlmodel.sql.sqltypes.AutoString(length=20), nullable=False),
sa.Column('purchase_price', sa.Integer(), nullable=False),
sa.Column('date_modified', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('product_code'),
sa.UniqueConstraint('product_name')
)
op.create_table('supplier',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('tin_number', sa.Integer(), nullable=False),
sa.Column('names', sqlmodel.sql.sqltypes.AutoString(length=100), nullable=False),
sa.Column('phone_number', sqlmodel.sql.sqltypes.AutoString(length=10), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('tin_number')
)
op.create_table('credit',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('transcation_type', sa.Enum('BUY', 'SELL', name='tradetype'), nullable=False),
sa.Column('product_code', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('client_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('supplier_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('qty', sa.Integer(), nullable=False),
sa.Column('amount', sa.Integer(), nullable=False),
sa.Column('date', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
sa.ForeignKeyConstraint(['client_id'], ['client.id'], ),
sa.ForeignKeyConstraint(['product_code'], ['product.product_code'], ),
sa.ForeignKeyConstraint(['supplier_id'], ['supplier.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('payment',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('payment_type', sa.Enum('BUY', 'SELL', name='tradetype'), nullable=False),
sa.Column('product_code', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('client_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('supplier_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('amount', sa.Integer(), nullable=False),
sa.Column('payment_method', sqlmodel.sql.sqltypes.AutoString(length=24), nullable=False),
sa.Column('date', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
sa.ForeignKeyConstraint(['client_id'], ['client.id'], ),
sa.ForeignKeyConstraint(['product_code'], ['product.product_code'], ),
sa.ForeignKeyConstraint(['supplier_id'], ['supplier.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('payment')
op.drop_table('credit')
op.drop_table('supplier')
op.drop_table('product')
op.drop_table('client')
# ### end Alembic commands ###
@@ -0,0 +1,60 @@
"""Fix client_id in Credit type to int
Revision ID: bfb086d8d500
Revises: 5840d2b52dd8
Create Date: 2025-06-01 14:53:57.095181
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
import sqlmodel
# revision identifiers, used by Alembic.
revision: str = 'bfb086d8d500'
down_revision: Union[str, None] = '5840d2b52dd8'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('credit',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('transcation_type', sa.Enum('BUY', 'SELL', name='tradetype'), nullable=False),
sa.Column('product_code', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('client_id', sa.Integer(), nullable=False),
sa.Column('supplier_id', sa.Integer(), nullable=False),
sa.Column('qty', sa.Integer(), nullable=False),
sa.Column('amount', sa.Integer(), nullable=False),
sa.Column('date', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
sa.ForeignKeyConstraint(['client_id'], ['client.id'], ),
sa.ForeignKeyConstraint(['product_code'], ['product.product_code'], ),
sa.ForeignKeyConstraint(['supplier_id'], ['supplier.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('payment',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('payment_type', sa.Enum('BUY', 'SELL', name='tradetype'), nullable=False),
sa.Column('product_code', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('client_id', sa.Integer(), nullable=False),
sa.Column('supplier_id', sa.Integer(), nullable=False),
sa.Column('amount', sa.Integer(), nullable=False),
sa.Column('payment_method', sqlmodel.sql.sqltypes.AutoString(length=24), nullable=False),
sa.Column('date', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
sa.ForeignKeyConstraint(['client_id'], ['client.id'], ),
sa.ForeignKeyConstraint(['product_code'], ['product.product_code'], ),
sa.ForeignKeyConstraint(['supplier_id'], ['supplier.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('payment')
op.drop_table('credit')
# ### end Alembic commands ###
View File
+7
View File
@@ -0,0 +1,7 @@
"""
API Home
"""
from fastapi import APIRouter
api_router = APIRouter()
View File
+41
View File
@@ -0,0 +1,41 @@
import secrets
import warnings
from typing import Annotated, Any, Literal
from pydantic import (
MySQLDsn
)
from pydantic_core import MultiHostUrl
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""
"""
model_config = SettingsConfigDict(
# One level above ./backend
env_file='../.env',
env_ignore_empty=True,
extra='ignore'
)
SECRET_KEY: str = secrets.token_urlsafe(32)
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 # 8 days
MYSQL_SERVER: str
MYSQL_PORT: int = 3306
MYSQL_USER: str
MYSQL_PASSWORD: str = ""
MYSQL_DB: str = ""
@computed_field # type: ignore[prop-decorator]
@property
def SQLALCHEMY_DATABASE_URI(self) -> MySQLDsn:
return MultiHostUrl.build(
scheme="mysql+mysqldb",
username=self.MYSQL_USER,
password=self.MYSQL_PASSWORD,
host=self.MYSQL_SERVER,
port=self.MYSQL_PORT,
path=self.MYSQL_DB
) # type: ignore
settings = Settings() # type: ignore
View File
View File
+15
View File
@@ -0,0 +1,15 @@
"""
The Client table
"""
from fastapi import APIRouter, HTTPException
from sqlmodel import func, select
from app.models import Client, Supplier, Product, Payment, Credit
from typing import Any
router = APIRouter(prefix="/client", tags=["items"])
@router.get("/", response_model=Client)
def read_clients(
session: SessionDep,
)
View File
View File
View File
+3
View File
@@ -0,0 +1,3 @@
"""
TODO: when Credit.purchase_price is updated, update Product.purchase_price
"""
View File
+9
View File
@@ -0,0 +1,9 @@
from sqlmodel import Session, create_engine, select
from app.config import settings
from app.models import Client, Supplier
engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
def init_db(session: Session) -> None:
""""""
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Entry point for fastapi app
NOTE:
-
"""
from app.config import settings
from typing import Union
from fastapi import FastAPI
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json"
)
@app.get("/")
def read_root():
"""
"""
return {"Hello": "World"}
+100
View File
@@ -0,0 +1,100 @@
"""
This module contains Pydantic/Database Models that map database tables validate
and serialize api responses.
If the logic is identical -> SQLModel is used to do both.
Otherwise pydantic - for api responses
And SQLAlchemy is used for db data validation.
TODO:
Mapping & validation for:
- Clients, Suppliers, Products, payments
Done:
* Table mappings
"""
from sqlmodel import SQLModel, Field, UniqueConstraint
from datetime import datetime
from sqlalchemy import Column, DateTime, func, Enum as SQLEnum
from enum import Enum
from typing import Optional
class TradeType(str, Enum):
BUY = "Buy"
SELL = "Sell"
class Client(SQLModel, table=True):
"""Clients table mapping, api response validation and serialisation"""
id: Optional[int] = Field(default=None, primary_key=True)
tin_number: int = Field(nullable=False, unique=True)
names: str = Field(max_length=100, nullable=False)
phone_number: str = Field(max_length=10, nullable=False)
class Supplier(SQLModel, table=True):
"""Supplier table mapping, api response validation and serialisation"""
id: Optional[int] = Field(default=None, primary_key=True)
tin_number: int = Field(nullable=False, unique=True)
names: str = Field(max_length=100, nullable=False)
phone_number: str = Field(max_length=10, nullable=False)
class Product(SQLModel, table=True):
"""Products table mapping, api response validation and serialisation
NOTE: purchase price should update every time a supplier credits us goods
and price has changed
"""
__table_args__ = (UniqueConstraint("product_code"),)
id: Optional[int] = Field(nullable=False, primary_key=True)
product_code: str = Field(max_length=10, nullable=False)
product_name: str = Field(max_length=20, nullable=False, unique=True)
purchase_price: int = Field(nullable=False)
date_modified: datetime = Field(
sa_column=Column(DateTime,
server_default=func.now(),
server_onupdate=func.now())
)
class Payment(SQLModel, table=True):
"""
Payments table mapping, api response validation and serialisation
Include both payments to suppliers and from clients
"""
id: Optional[int] = Field(default=None, primary_key=True)
payment_type: TradeType = Field(
sa_column=Column(SQLEnum(TradeType), nullable=False)
)
product_code: str = Field(nullable=False, foreign_key="product.product_code")
client_id: Optional[int] = Field(nullable=False, foreign_key="client.id")
supplier_id: Optional[int] = Field(nullable=False, foreign_key="supplier.id")
amount: int = Field(nullable=False)
payment_method: str = Field(max_length=24, nullable=False)
date: datetime = Field(
sa_column=Column(DateTime, server_default=func.now())
)
class Credit(SQLModel, table=True):
"""Credit table mapping, api response validation and serialisation
Include both credit from suppliers and to clients
"""
id: Optional[int] = Field(default=None, primary_key=True)
transcation_type: TradeType = Field(
sa_column=Column(SQLEnum(TradeType), nullable=False)
)
product_code: str = Field(nullable=False, foreign_key="product.product_code")
client_id: Optional[int] = Field(nullable=False, foreign_key="client.id")
supplier_id: Optional[int] = Field(nullable=False, foreign_key="supplier.id")
qty: int = Field(nullable=False)
amount: int = Field(nullable=False)
date: datetime = Field(
sa_column=Column(DateTime, server_default=func.now())
)