12
Practice
1. Create a function onhand_qty to calculate books in stock.
The function takes a parameter of a composite type (books)
and returns an integer number.
Use this function in the catalog_v view as a computed field.
Check that the application can now display the number of books.
2. Create a set-returning function get_catalog for book search.
The function takes values from the search fields
(“author”, “book title”, “in stock”) and returns matching books
in the catalog_v format.
Check that you can now browse and search for books in “Store.”
Task 1.
FUNCTION onhand_qty(book books) RETURNS integer
Task 2.
FUNCTION get_catalog(
author_name text, book_title text, in_stock boolean
)
RETURNS TABLE(
book_id integer, display_name text, onhand_qty integer
)
To solve this problem, it is tempting to use the already available catalog_v
view and simply filter out some rows. But this view displays book titles and
authors in the same field, and authors’ middle names are abbreviated. It is
clear that the search for “Klapka” in the “Jerome K. Jerome” field will not
return any results.
The get_catalog function could repeat the query from the catalog_v
view, but it is code duplication, which is bad practice. So you should extend
the catalog_v view by adding the following fields: the book title and the full
list of authors.
Check that the empty fields in the form are handled correctly. When calling
the get_catalog function, does the client pass empty strings or null
values?