The Application: The Database Module
Learn about the database module and take a look at the complete running code of the application.
We'll cover the following...
To understand the database module, we’ll look at it in four parts. These four parts are:
- The queries
- Loading the queries
- Running the queries
- 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 dorun_query(:setup_table_books, [])end@doc """Delete the database table required for the bookstore"""def teardown() dorun_query(:teardown_table_books, [])end@doc """Add a new book to the inventory, with no copies of it"""def add_book(isbn, title, author) doadd_book(isbn, title, author, 0, 0)end@doc """Add a new book to the inventory, with a pre-set number ofowned and available copies"""def add_book(isbn, title, author, owned, avail) dobin_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}endend@doc """Add a copy of the book to the bookstore's inventory"""def add_copy(isbn) dohandle_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) dohandle_single_update(run_query(:borrow_copy, [isbn]))end@doc """Return a copy of a book, making it available again"""def return_copy(isbn) dohandle_single_update(run_query(:return_copy, [isbn]))end@doc """Search all books written by a given author. The matching is loose and sosearching for `Hawk' will return copies of books written by `StephenHawking' (if such copies are in the system)"""def find_book_by_author(author) dohandle_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) dohandle_select(run_query(:find_by_isbn, [isbn]))end@doc """Find books with a given title. The matching us loose and searchingfor `Test' may return `PropEr Testing'."""def find_book_by_title(title) dohandle_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 ...