...

/

The Application: The Database Module

The Application: The Database Module

Learn about the database module and take a look at the complete running code of the application.

To understand the database module, we’ll look at it in four parts. These four parts are:

  1. The queries
  2. Loading the queries
  3. Running the queries
  4. Reformatting the results

The queries

Let’s get started with the first which contains the queries.

Press + to interact
@doc """
Create the database table required for the bookstore
"""
def setup do
run_query(:setup_table_books, [])
end
@doc """
Delete the database table required for the bookstore
"""
def teardown() do
run_query(:teardown_table_books, [])
end
@doc """
Add a new book to the inventory, with no copies of it
"""
def add_book(isbn, title, author) do
add_book(isbn, title, author, 0, 0)
end
@doc """
Add a new book to the inventory, with a pre-set number of
owned and available copies
"""
def add_book(isbn, title, author, owned, avail) do
bin_title = :erlang.iolist_to_binary(title)
bin_author = :erlang.iolist_to_binary(author)
case run_query(:add_book, [isbn, bin_title, bin_author, owned, avail]) do
{{:insert, 0, 1}, []} -> :ok
{:error, reason} -> {:error, reason}
other -> {:error, other}
end
end
@doc """
Add a copy of the book to the bookstore's inventory
"""
def add_copy(isbn) do
handle_single_update(run_query(:add_copy, [isbn]))
end
@doc """
Borrow a copy of a book; reduces the count of available copies by one. Who borrowed the book is not tracked at this moment and is left as an exercise to the reader.
"""
def borrow_copy(isbn) do
handle_single_update(run_query(:borrow_copy, [isbn]))
end
@doc """
Return a copy of a book, making it available again
"""
def return_copy(isbn) do
handle_single_update(run_query(:return_copy, [isbn]))
end
@doc """
Search all books written by a given author. The matching is loose and so
searching for `Hawk' will return copies of books written by `Stephen
Hawking' (if such copies are in the system)
"""
def find_book_by_author(author) do
handle_select(
run_query(
:find_by_author,
[:erlang.iolist_to_binary(['%', author, '%'])] )
)
)
end
@doc """
Find books under a given ISBN
"""
def find_book_by_isbn(isbn) do
handle_select(run_query(:find_by_isbn, [isbn]))
end
@doc """
Find books with a given title. The matching us loose and searching
for `Test' may return `PropEr Testing'.
"""
def find_book_by_title(title) do
handle_select(
run_query(
:find_by_title,
[:erlang.iolist_to_binary(['%', title, '%'])]
)
)
end

Note: All the functions have a doc line explaining what it does.

This module acts as a model ...