diff --git a/alembic/versions/20250412_175353_8ea4e5de_update_fruit.py b/alembic/versions/20250412_175353_8ea4e5de_update_fruit.py new file mode 100644 index 0000000..59529a6 --- /dev/null +++ b/alembic/versions/20250412_175353_8ea4e5de_update_fruit.py @@ -0,0 +1,29 @@ +"""create fruits table +Revision ID: 0003 +Revises: 0002 +Create Date: 2024-01-17 10:00:00.000000 +""" +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = '0003' +down_revision = '0002' +branch_labels = None +depends_on = None + +def upgrade(): + op.create_table( + 'fruits', + sa.Column('id', sa.String(36), primary_key=True), + sa.Column('name', sa.String(255), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()), + sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()) + ) + + op.create_index(op.f('ix_fruits_name'), 'fruits', ['name'], unique=True) + +def downgrade(): + op.drop_index(op.f('ix_fruits_name'), table_name='fruits') + op.drop_table('fruits') \ No newline at end of file diff --git a/endpoints/names.post.py b/endpoints/names.post.py index ea5a512..f6ad1c8 100644 --- a/endpoints/names.post.py +++ b/endpoints/names.post.py @@ -1,20 +1,17 @@ -from fastapi import APIRouter, status -from typing import List +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session +from core.database import get_db +from schemas.fruit import FruitCreate, FruitSchema +from helpers.fruit_helpers import create_fruit router = APIRouter() -@router.post("/names", status_code=status.HTTP_200_OK) -async def get_fruit_names() -> List[str]: - fruits = [ - "Apple", - "Banana", - "Orange", - "Mango", - "Pineapple", - "Grape", - "Strawberry", - "Blueberry", - "Peach", - "Pear" - ] - return fruits \ No newline at end of file +@router.post("/names", status_code=status.HTTP_201_CREATED, response_model=FruitSchema) +async def create_name( + fruit: FruitCreate, + db: Session = Depends(get_db) +): + new_fruit = create_fruit(db=db, fruit=fruit) + if not new_fruit: + raise HTTPException(status_code=400, detail="Fruit could not be created") + return new_fruit \ No newline at end of file diff --git a/helpers/fruit_helpers.py b/helpers/fruit_helpers.py index f967108..db11d2f 100644 --- a/helpers/fruit_helpers.py +++ b/helpers/fruit_helpers.py @@ -17,7 +17,7 @@ def get_all_fruits(db: Session) -> List[Fruit]: Returns: List[Fruit]: A list of all fruit objects. """ - return db.query(Fruit).all() + return db.query(Fruit).order_by(Fruit.name).all() def get_fruit_by_id(db: Session, fruit_id: UUID) -> Optional[Fruit]: @@ -45,7 +45,7 @@ def get_fruit_by_name(db: Session, name: str) -> Optional[Fruit]: Returns: Optional[Fruit]: The fruit object if found, otherwise None. """ - return db.query(Fruit).filter(Fruit.name == name).first() + return db.query(Fruit).filter(Fruit.name.ilike(f"%{name}%")).first() def create_fruit(db: Session, fruit_data: FruitCreate) -> Optional[Fruit]: @@ -60,7 +60,7 @@ def create_fruit(db: Session, fruit_data: FruitCreate) -> Optional[Fruit]: Optional[Fruit]: The newly created fruit object, or None if creation fails. """ try: - db_fruit = Fruit(**fruit_data.dict()) + db_fruit = Fruit(**fruit_data.dict(exclude_unset=True)) db.add(db_fruit) db.commit() db.refresh(db_fruit) @@ -131,7 +131,7 @@ def validate_fruit_data(data: Dict[str, Any]) -> bool: """ if not data: return False - if "name" not in data or not isinstance(data["name"], str) or len(data["name"]) < 1: + if "name" not in data or not isinstance(data["name"], str) or len(data["name"]) > 255: return False if "description" in data and not isinstance(data["description"], (str, type(None))): return False diff --git a/models/fruit.py b/models/fruit.py index b1fa632..36af7d4 100644 --- a/models/fruit.py +++ b/models/fruit.py @@ -1,4 +1,4 @@ -from sqlalchemy import Column, String, DateTime +from sqlalchemy import Column, String, DateTime, Text from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.sql import func from core.database import Base @@ -8,8 +8,8 @@ class Fruit(Base): __tablename__ = "fruits" id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) - name = Column(String, unique=True, nullable=False, index=True) - description = Column(String, nullable=True) + name = Column(String(255), unique=True, nullable=False, index=True) + description = Column(Text, nullable=True) created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) \ No newline at end of file diff --git a/schemas/fruit.py b/schemas/fruit.py index cbe46ea..f5f2535 100644 --- a/schemas/fruit.py +++ b/schemas/fruit.py @@ -4,14 +4,14 @@ from datetime import datetime from uuid import UUID class FruitBase(BaseModel): - name: str = Field(..., description="Name of the fruit") + name: str = Field(..., description="Name of the fruit", max_length=255) description: Optional[str] = Field(None, description="Description of the fruit") class FruitCreate(FruitBase): pass class FruitUpdate(BaseModel): - name: Optional[str] = Field(None, description="Name of the fruit") + name: Optional[str] = Field(None, description="Name of the fruit", max_length=255) description: Optional[str] = Field(None, description="Description of the fruit") class FruitSchema(FruitBase):