crud for collections

This commit is contained in:
bdrtr 2025-05-14 18:29:46 +03:00
parent bf71979982
commit 250d3f1f15
4 changed files with 195 additions and 13 deletions

View file

@ -1,22 +1,43 @@
from fastapi import HTTPException
from sqlalchemy import Column, Integer, String, Float, Boolean, ForeignKey
from sqlalchemy.dialects.postgresql import ARRAY
from fastapi import HTTPException, Depends
from sqlalchemy import Integer, String, Boolean
from pydantic import BaseModel
from sqlalchemy.orm import Session, relationship, mapped_column, Mapped
from ..config import Base, get_session_db, user_collection, collection_item
from ..auth.models import DBUser
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..auth.models import DBUser
from ..items.models import Items
from ..items.models import Items, Item
###### SCHEMAS #########
class CollectionBase(BaseModel):
collection_name : str | None = None
collection_description : str | None = None
visibility : bool | None = None
class CollectionCreate(CollectionBase):
pass
class CollectionPublic(CollectionBase):
collection_id : int | None = None
class Config:
from_attributes = True #sqlalchemy ile pydantic arasında geçiş yapabilmek için kullanılır
class CollectionUpdate(CollectionBase):
pass
##### veri tabanı modelleri #####
class CollectionsDB(Base):
__tablename__ = "collections_table"
collection_id : Mapped[int] = mapped_column(Integer, primary_key=True)
collection_id : Mapped[int] = mapped_column(Integer, primary_key=True, index=True, autoincrement=True)
#user_id : Mapped[int] = mapped_column(Integer, ForeignKey("users_table.user_id"), nullable=False) # user_id ile ilişki
#item_id : Mapped[list[int]] = mapped_column(Integer, ForeignKey("items_table.item_id"), nullable=False) # item_id ile ilişki
visibility : Mapped[bool] = mapped_column(Boolean, default=True)
@ -24,7 +45,7 @@ class CollectionsDB(Base):
collection_description : Mapped[str] = mapped_column(String, default="No description")
# ilişkiler
users : Mapped['DBUser'] = relationship(
users : Mapped[list['DBUser']] = relationship(
"DBUser",
secondary=user_collection,
back_populates="collections",
@ -39,4 +60,114 @@ class CollectionsDB(Base):
)
#### collection bir item listesi birde kullanıcı listesi tutacak
#### collection bir item listesi birde kullanıcı listesi tutacak
def create_colletion(
collection: CollectionCreate | None = None,
user_id : int | None = None
) -> bool:
"""
Collection oluşturma fonksiyonu
"""
if collection is None:
raise HTTPException(status_code=400, detail="Collection is None returned")
session = next(get_session_db()) # -> get_session_db() fonksiyonu daima generator döndürür next ile çağırmalısın
user = session.query(DBUser).filter(DBUser.user_id == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
try:
new_collection = CollectionsDB(
collection_name=collection.collection_name,
collection_description=collection.collection_description,
visibility=collection.visibility
)
new_collection.users.append(user)
session.add(new_collection)
session.commit()
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error creating collection: {e}")
return True
def get_collections(
user_id : int | None = None
) -> list[CollectionPublic] | None:
"""
Kullanıcının collectionlarını döndürür
"""
if user_id is None:
raise HTTPException(status_code=400, detail="User id is None")
session = next(get_session_db()) # -> get_session_db() fonksiyonu daima generator döndürür next ile çağırmalısın
collections = session.query(CollectionsDB).filter(CollectionsDB.users.any(user_id=user_id)).all()
if collections is None:
raise HTTPException(status_code=404, detail="No collections found")
return collections
def update_collection(
collection: CollectionUpdate | None = None,
user_id : int | None = None,
collection_id : int | None = None
) -> bool:
"""
Collection güncelleme fonksiyonu
"""
if collection is None:
raise HTTPException(status_code=400, detail="Collection is None returned")
session = next(get_session_db()) # -> get_session_db() fonksiyonu daima generator döndürür next ile çağırmalısın
user = session.query(DBUser).filter(DBUser.user_id == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
collection_to_update = session.query(CollectionsDB).filter(CollectionsDB.collection_id == collection_id).first()
if collection_to_update is None:
raise HTTPException(status_code=404, detail="Collection not found")
try:
collection_to_update.collection_name = collection.collection_name
collection_to_update.collection_description = collection.collection_description
collection_to_update.visibility = collection.visibility
session.commit()
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error updating collection: {e}")
return True
def delete_collection(
user_id : int | None = None,
collection_id : int | None = None
) -> bool:
"""
Collection silme fonksiyonu
"""
if user_id is None or collection_id is None:
raise HTTPException(status_code=400, detail="User id or collection id is None")
session = next(get_session_db()) # -> get_session_db() fonksiyonu daima generator döndürür next ile çağırmalısın
user = session.query(DBUser).filter(DBUser.user_id == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
collection_to_delete = session.query(CollectionsDB).filter(CollectionsDB.collection_id == collection_id).first()
if collection_to_delete is None:
raise HTTPException(status_code=404, detail="Collection not found")
try:
session.delete(collection_to_delete)
session.commit()
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error deleting collection: {e}")
return True