Filaments can now be created
This commit is contained in:
@@ -1,7 +1,54 @@
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
"""SQLAlchemy database setup."""
|
||||
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
|
||||
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Optional
|
||||
|
||||
engine = create_async_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
|
||||
SessionLocal = async_sessionmaker(engine, autocommit=False, autoflush=False)
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
from spoolson.database.models import Base
|
||||
|
||||
|
||||
class Database:
|
||||
connection_url: str
|
||||
engine: AsyncEngine
|
||||
session_maker: async_sessionmaker[AsyncSession]
|
||||
|
||||
def __init__(self: "Database", connection_url: str) -> None:
|
||||
"""Construct the Database wrapper and set config parameters."""
|
||||
self.connection_url = connection_url
|
||||
|
||||
def connect(self: "Database") -> None:
|
||||
"""Connect to the database."""
|
||||
self.engine = create_async_engine(self.connection_url, connect_args={"check_same_thread": False})
|
||||
self.session_maker = async_sessionmaker(self.engine, autocommit=False, autoflush=True)
|
||||
|
||||
async def create_tables(self: "Database") -> None:
|
||||
"""Create tables for all defined models."""
|
||||
async with self.engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
|
||||
__db: Optional[Database] = None
|
||||
|
||||
|
||||
async def setup_db(connection_url: str) -> None:
|
||||
"""Connect the singleton DB object."""
|
||||
global __db # noqa: PLW0603
|
||||
__db = Database(connection_url)
|
||||
__db.connect()
|
||||
await __db.create_tables()
|
||||
|
||||
|
||||
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Get a DB session to be used with FastAPI's dependency system."""
|
||||
if __db is None:
|
||||
raise RuntimeError("DB is not setup.")
|
||||
async with __db.session_maker() as session:
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception as exc:
|
||||
await session.rollback()
|
||||
raise exc
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
43
spoolson/database/filament.py
Normal file
43
spoolson/database/filament.py
Normal file
@@ -0,0 +1,43 @@
|
||||
"""Helper functions for interacting with filament database objects."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from spoolson.database import models, vendor
|
||||
|
||||
|
||||
async def create_filament(
|
||||
*,
|
||||
db: AsyncSession,
|
||||
density: float,
|
||||
diameter: float,
|
||||
name: Optional[str] = None,
|
||||
vendor_id: Optional[int] = None,
|
||||
material: Optional[str] = None,
|
||||
price: Optional[float] = None,
|
||||
weight: Optional[float] = None,
|
||||
spool_weight: Optional[float] = None,
|
||||
article_number: Optional[str] = None,
|
||||
comment: Optional[str] = None,
|
||||
) -> models.Filament:
|
||||
"""Add a new filament to the database."""
|
||||
vendor_item: Optional[models.Vendor] = None
|
||||
if vendor_id is not None:
|
||||
vendor_item = await vendor.get_by_id(db, vendor_id)
|
||||
|
||||
db_item = models.Filament(
|
||||
name=name,
|
||||
vendor=vendor_item,
|
||||
material=material,
|
||||
price=price,
|
||||
density=density,
|
||||
diameter=diameter,
|
||||
weight=weight,
|
||||
spool_weight=spool_weight,
|
||||
article_number=article_number,
|
||||
comment=comment,
|
||||
)
|
||||
db.add(db_item)
|
||||
await db.flush()
|
||||
return db_item
|
||||
@@ -3,8 +3,9 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Integer, String
|
||||
from sqlalchemy import ForeignKey, Integer, String
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
@@ -17,14 +18,17 @@ class Vendor(Base):
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||
name: Mapped[str] = mapped_column(String(64))
|
||||
comment: Mapped[Optional[str]] = mapped_column(String(1024))
|
||||
filaments: Mapped[list["Filament"]] = relationship(back_populates="vendor")
|
||||
|
||||
|
||||
class Filament(Base):
|
||||
__tablename__ = "material"
|
||||
__tablename__ = "filament"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, index=True)
|
||||
name: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
vendor: Mapped[Optional["Vendor"]] = relationship()
|
||||
vendor_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendor.id"))
|
||||
vendor: Mapped[Optional["Vendor"]] = relationship(back_populates="filaments")
|
||||
spools: Mapped[list["Spool"]] = relationship(back_populates="filament")
|
||||
material: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
price: Mapped[Optional[float]] = mapped_column()
|
||||
density: Mapped[float] = mapped_column()
|
||||
@@ -41,10 +45,11 @@ class Spool(Base):
|
||||
__tablename__ = "spool"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, index=True)
|
||||
registered: Mapped[datetime] = mapped_column()
|
||||
registered: Mapped[datetime] = mapped_column(default=func.now())
|
||||
first_used: Mapped[Optional[datetime]] = mapped_column()
|
||||
last_used: Mapped[Optional[datetime]] = mapped_column()
|
||||
filament: Mapped["Filament"] = mapped_column(index=True)
|
||||
filament_id: Mapped[int] = mapped_column(ForeignKey("filament.id"))
|
||||
filament: Mapped["Filament"] = relationship(back_populates="spools")
|
||||
weight: Mapped[float] = mapped_column()
|
||||
location: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
lot_nr: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
|
||||
14
spoolson/database/vendor.py
Normal file
14
spoolson/database/vendor.py
Normal file
@@ -0,0 +1,14 @@
|
||||
"""Helper functions for interacting with vendor database objects."""
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from spoolson.database import models
|
||||
from spoolson.exceptions import ItemNotFoundError
|
||||
|
||||
|
||||
async def get_by_id(db: AsyncSession, vendor_id: int) -> models.Vendor:
|
||||
"""Get a vendor object from the database by the unique ID."""
|
||||
vendor = await db.get(models.Vendor, vendor_id)
|
||||
if vendor is None:
|
||||
raise ItemNotFoundError(f"No vendor with ID {vendor_id} found.")
|
||||
return vendor
|
||||
Reference in New Issue
Block a user