Pybites Logo

Implement the Repository Pattern for a Book Library

Level: Intermediate (score: 3)

The Repository Pattern helps separate business logic from data storage, making code flexible and testable.

Your Task

You are provided with a Repository Interface (IBookRepository) that defines two methods:

  • add(book: Book): Saves a book.
  • get_by_title(title: str) -> Book | None: Retrieves a book by title.

Implement three repository subclasses that store and retrieve books in different ways:

  • SQLBookRepository: Uses sqlmodel and SQLite.
  • CsvBookRepository: Stores books in a CSV file.
  • MemoryBookRepository: Keeps books in memory

Write each repository so they all follow the same interface (IBookRepository) by implementing the add and get_by_title methods.

Each implementation will be tested like this:

repo = SQLBookRepository()  # or CsvBookRepository or MemoryBookRepository
book = Book(title="The Pragmatic Programmer", author="Andrew Hunt")
repo.add(book)

retrieved = repo.get_by_title("The Pragmatic Programmer")
assert retrieved is not None
assert retrieved.title == "The Pragmatic Programmer"
assert retrieved.author == "Andrew Hunt"