Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @router.post("/", response_model=UserBook)
- async def add_book(book: Book, user: User = Depends(active_user)) -> UserBook:
- async def validate(con, user_id: int, book: Book) -> None:
- count = await con.fetchval(
- "SELECT count(*) FROM user_book WHERE user_id=$1", user_id
- )
- if count > 1000:
- raise HTTPException(
- 400,
- "You already have too many books added, "
- "please contact our support",
- )
- if book.google_id and (
- await con.fetchrow(
- "SELECT 1 FROM user_book WHERE user_id=$1 AND google_id=$2",
- user_id,
- book.google_id,
- )
- ):
- raise HTTPException(400, "You have already added this book")
- async def insert_book(con, user_id: int, book: Book) -> UserBook:
- data = book.dict()
- data["user_id"] = user_id
- sql, params = insert_sql("user_book", data)
- data["id"] = await con.fetchval(sql, *params)
- return UserBook(**data)
- async def update_head(con, user_id: int, book_id: int) -> None:
- sql = """
- UPDATE user_book
- SET prev_id = $1
- WHERE id != $1
- AND user_id = $2
- AND prev_id is NULL
- """
- await con.execute(sql, book_id, user_id)
- user_id = user["id"]
- async with db.acquire() as con:
- await validate(con, user_id, book)
- async with con.transaction():
- user_book = await insert_book(con, user_id, book)
- await update_head(con, user_id, user_book.id)
- return user_book
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement