diff --git a/alembic/versions/20250414_142725_5ee7b7f6_update_country.py b/alembic/versions/20250414_142725_5ee7b7f6_update_country.py new file mode 100644 index 0000000..dbcd65b --- /dev/null +++ b/alembic/versions/20250414_142725_5ee7b7f6_update_country.py @@ -0,0 +1,33 @@ +"""create table for Country +Revision ID: 2b7a3c5d1e6a +Revises: 0001 +Create Date: 2023-05-25 12:32:42.096379 +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.sql import func +import uuid + +# revision identifiers, used by Alembic. +revision = '2b7a3c5d1e6a' +down_revision = '0001' +branch_labels = None +depends_on = None + +def upgrade(): + table_name = "countries" + + op.create_table( + table_name, + sa.Column('id', sa.String(36), primary_key=True, default=lambda: str(uuid.uuid4())), + sa.Column('name', sa.String(), nullable=False, unique=True), + sa.Column('latitude', sa.Float(), nullable=False), + sa.Column('longitude', sa.Float(), nullable=False), + sa.Column('created_at', sa.Float(), server_default=func.now()), + sa.Column('updated_at', sa.Float(), server_default=func.now(), onupdate=func.now()), + sa.Index('ix_countries_name', 'name') + ) + +def downgrade(): + table_name = "countries" + op.drop_table(table_name) \ No newline at end of file diff --git a/endpoints/countries.post.py b/endpoints/countries.post.py index e69de29..5945d33 100644 --- a/endpoints/countries.post.py +++ b/endpoints/countries.post.py @@ -0,0 +1,19 @@ +from fastapi import APIRouter, Depends, status +from sqlalchemy.orm import Session +from core.database import get_db +from schemas.country import CountryCreate, CountrySchema +from helpers.country_helpers import get_country_by_name, create_country + +router = APIRouter() + +@router.post("/countries", status_code=status.HTTP_201_CREATED, response_model=CountrySchema) +async def create_new_country( + country_data: CountryCreate, + db: Session = Depends(get_db) +): + existing_country = get_country_by_name(db, name=country_data.name) + if existing_country: + return existing_country + + new_country = create_country(db, country_data) + return new_country \ No newline at end of file diff --git a/helpers/country_helpers.py b/helpers/country_helpers.py new file mode 100644 index 0000000..7370c0a --- /dev/null +++ b/helpers/country_helpers.py @@ -0,0 +1,89 @@ +from typing import Optional, List +from sqlalchemy.orm import Session +from models.country import Country +from schemas.country import CountryCreate, CountryUpdate, CountrySchema + +def get_country_by_name(db: Session, name: str) -> Optional[Country]: + """ + Retrieves a country from the database by its name. + + Args: + db (Session): The database session. + name (str): The name of the country to retrieve. + + Returns: + Optional[Country]: The country object if found, otherwise None. + """ + return db.query(Country).filter(Country.name == name).first() + +def create_country(db: Session, country_data: CountryCreate) -> Country: + """ + Creates a new country in the database. + + Args: + db (Session): The database session. + country_data (CountryCreate): The data for the country to create. + + Returns: + Country: The newly created country object. + """ + db_country = Country(**country_data.dict()) + db.add(db_country) + db.commit() + db.refresh(db_country) + return db_country + +def get_all_countries(db: Session) -> List[CountrySchema]: + """ + Retrieves all countries from the database. + + Args: + db (Session): The database session. + + Returns: + List[CountrySchema]: A list of all country objects. + """ + countries = db.query(Country).all() + return [CountrySchema.from_orm(country) for country in countries] + +def update_country(db: Session, country_id: str, country_data: CountryUpdate) -> Optional[CountrySchema]: + """ + Updates an existing country in the database. + + Args: + db (Session): The database session. + country_id (str): The ID of the country to update. + country_data (CountryUpdate): The updated data for the country. + + Returns: + Optional[CountrySchema]: The updated country object if found, otherwise None. + """ + country = db.query(Country).filter(Country.id == country_id).first() + if not country: + return None + + for field, value in country_data.dict(exclude_unset=True).items(): + setattr(country, field, value) + + db.commit() + db.refresh(country) + return CountrySchema.from_orm(country) + +def delete_country(db: Session, country_id: str) -> bool: + """ + Deletes a country from the database. + + Args: + db (Session): The database session. + country_id (str): The ID of the country to delete. + + Returns: + bool: True if the country was deleted, False otherwise. + """ + country = db.query(Country).filter(Country.id == country_id).first() + if not country: + return False + + db.delete(country) + db.commit() + return True \ No newline at end of file diff --git a/models/country.py b/models/country.py new file mode 100644 index 0000000..6ea489b --- /dev/null +++ b/models/country.py @@ -0,0 +1,15 @@ +from sqlalchemy import Column, String, Float +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.sql import func +from core.database import Base +import uuid + +class Country(Base): + __tablename__ = "countries" + + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + name = Column(String, nullable=False, unique=True, index=True) + latitude = Column(Float, nullable=False) + longitude = Column(Float, nullable=False) + created_at = Column(Float, default=func.now()) + updated_at = Column(Float, default=func.now(), onupdate=func.now()) \ No newline at end of file diff --git a/schemas/country.py b/schemas/country.py new file mode 100644 index 0000000..1523b19 --- /dev/null +++ b/schemas/country.py @@ -0,0 +1,25 @@ +from pydantic import BaseModel, Field +from typing import Optional +from datetime import datetime +import uuid + +class CountryBase(BaseModel): + name: str = Field(..., description="Country name") + latitude: float = Field(..., description="Country latitude") + longitude: float = Field(..., description="Country longitude") + +class CountryCreate(CountryBase): + pass + +class CountryUpdate(CountryBase): + name: Optional[str] = Field(None, description="Country name") + latitude: Optional[float] = Field(None, description="Country latitude") + longitude: Optional[float] = Field(None, description="Country longitude") + +class CountrySchema(CountryBase): + id: uuid.UUID + created_at: datetime + updated_at: datetime + + class Config: + orm_mode = True \ No newline at end of file