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 bookstoresetup() ->run_query(setup_table_books, []).%% @doc Delete the database table required for the bookstoreteardown() ->run_query(teardown_table_books, []).%% @doc Add a new book to the inventory, with no copies of it.add_book(ISBN, Title, Author) ->add_book(ISBN, Title, Author, 0, 0).%% @doc Add a new book to the inventory, with a pre-set number of owned%% and available copies.add_book(ISBN, Title, Author, Owned, Avail) ->BinTitle = iolist_to_binary(Title),BinAuthor = iolist_to_binary(Author),case run_query(add_book, [ISBN, BinTitle, BinAuthor, Owned, Avail) of{{insert,0,1},[]} -> ok;{error, Reason} -> {error, Reason};Other -> {error, Other}end.%% @doc Add a copy of a book to the bookstore's inventoryadd_copy(ISBN) ->handle_single_update(run_query(add_copy, [ISBN])).%% @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.borrow_copy(ISBN) ->handle_single_update(run_query(borrow_copy, [ISBN])).%% @doc Return a book copy, making it available again.return_copy(ISBN) ->handle_single_update(run_query(return_copy, [ISBN])).%% @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)find_book_by_author(Author) ->handle_select(run_query(find_by_author, [iolist_to_binary(["%",Author,"%"])])).%% @doc Find books under a given ISBN.find_book_by_isbn(ISBN) ->handle_select(run_query(find_by_isbn, [ISBN])).%% @doc Find books with a given title. The matching us loose and searching%% for `Test' may return `PropEr Testing'.find_book_by_title(Title) ->handle_select(run_query(find_by_title, [iolist_to_binary(["%",Title,"%"])])).
Note: All the functions have a doc line explaining what it does.
This module acts as a ...
Access this course and 1400+ top-rated courses and projects.