Implemented find queries

This commit is contained in:
Donkie
2023-04-05 21:29:39 +02:00
parent 6a58caa2ec
commit b51d0a3183
6 changed files with 199 additions and 25 deletions

View File

@@ -2,8 +2,10 @@
from typing import Optional
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import contains_eager, joinedload
from spoolman.database import models, vendor
from spoolman.exceptions import ItemDeleteError, ItemNotFoundError
@@ -47,12 +49,42 @@ async def create(
async def get_by_id(db: AsyncSession, filament_id: int) -> models.Filament:
"""Get a filament object from the database by the unique ID."""
filament = await db.get(models.Filament, filament_id)
filament = await db.get(
models.Filament,
filament_id,
options=[joinedload("*")], # Load all nested objects as well
)
if filament is None:
raise ItemNotFoundError(f"No filament with ID {filament_id} found.")
return filament
async def find(
*,
db: AsyncSession,
vendor_name: Optional[str] = None,
vendor_id: Optional[int] = None,
name: Optional[str] = None,
material: Optional[str] = None,
article_number: Optional[str] = None,
) -> list[models.Filament]:
"""Find a list of filament objects by search criteria."""
stmt = select(models.Filament).options(contains_eager(models.Filament.vendor)).join(models.Filament.vendor)
if vendor_name is not None:
stmt = stmt.where(models.Vendor.name.ilike(f"%{vendor_name}%"))
if vendor_id is not None:
stmt = stmt.where(models.Filament.vendor_id == vendor_id)
if name is not None:
stmt = stmt.where(models.Filament.name.ilike(f"%{name}%"))
if material is not None:
stmt = stmt.where(models.Filament.material.ilike(f"%{material}%"))
if article_number is not None:
stmt = stmt.where(models.Filament.article_number.ilike(f"%{article_number}%"))
rows = await db.execute(stmt)
return list(rows.scalars().all())
async def update(
*,
db: AsyncSession,