Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions db.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ DROP TABLE IF EXISTS books;

CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(50) UNIQUE NOT NULL,
author VARCHAR(100) UNIQUE NOT NULL
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
publisher VARCHAR(255)
);
4 changes: 4 additions & 0 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String
from pydantic import BaseModel, ConfigDict
from typing import Optional


# SQLAlchemy models
Expand All @@ -18,13 +19,15 @@ class Book(Base):
id: Mapped[int] = mapped_column(primary_key=True, index=True)
title: Mapped[str] = mapped_column(String(255), index=True)
author: Mapped[str] = mapped_column(String(255))
publisher: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)

# Pydantic models
class BookIn(BaseModel):
"""Pydantic model for book input"""

title: str
author: str
publisher: Optional[str] = None


class BookOut(BaseModel):
Expand All @@ -33,5 +36,6 @@ class BookOut(BaseModel):
id: int
title: str
author: str
publisher: Optional[str] = None

model_config = ConfigDict(from_attributes=True)
7 changes: 6 additions & 1 deletion repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@

# Create a new book
def create_book(db: Session, book: models.BookIn):
db_book = models.Book(title=book.title, author=book.author)
db_book = models.Book(
title=book.title,
author=book.author,
publisher=book.publisher
)
db.add(db_book)
db.commit()
db.refresh(db_book)
Expand All @@ -27,6 +31,7 @@ def update_book(db: Session, book_id: int, book: models.BookIn):
if db_book:
db_book.title = book.title
db_book.author = book.author
db_book.publisher = book.publisher
db.commit()
db.refresh(db_book)
return db_book
Expand Down
Loading