One function to convert query result to a book.
authorJohn Ladan <jladan@uwaterloo.ca>
Wed, 23 Oct 2013 22:29:06 +0000 (18:29 -0400)
committerJohn Ladan <jladan@uwaterloo.ca>
Wed, 23 Oct 2013 22:29:06 +0000 (18:29 -0400)
db_layer.py
librarian.py

index e0e940c..e055bc9 100644 (file)
@@ -92,15 +92,7 @@ def getBooks():
     c = conn.cursor()
     query = "SELECT * FROM "+bookTable+" WHERE deleted=0;"
     c.execute(query)
-    books = []
-    for b in c:
-        book = {}
-        i = 0
-        for k in columns:
-            if b[i]!=None:
-                book[k]=b[i]
-            i+=1
-        books.append(book)
+    books = [_query_to_book(b) for b in c]
     c.close()
     return books
 
@@ -109,15 +101,7 @@ def getBooksByCategory(cat):
     c = conn.cursor()
     query = "SELECT "+",".join(map(colify,columns))+" FROM "+bookTable+" JOIN "+bookCategoryTable+" USING (id) WHERE cat_id = :id AND deleted=0;"
     c.execute(query,cat)
-    books = []
-    for b in c:
-        book = {}
-        i = 0
-        for k in columns:
-            if b[i]!=None:
-                book[k]=b[i]
-            i+=1
-        books.append(book)
+    books = [_query_to_book(b) for b in c]
     c.close()
     return books
 
@@ -126,15 +110,7 @@ def getRemovedBooks():
     c = conn.cursor()
     query = "SELECT * FROM "+bookTable+" WHERE DELETED=1;"
     c.execute(query)
-    books = []
-    for b in c:
-        book = {}
-        i = 0
-        for k in columns:
-            if b[i]!=None:
-                book[k]=b[i]
-            i+=1
-        books.append(book)
+    books = [_query_to_book(b) for b in c]
     c.close()
     return books
 
@@ -143,17 +119,10 @@ def getBookByID(bookid):
     c = conn.cursor()
     query = "SELECT * FROM "+bookTable+" WHERE id = "+str(bookid)+";"
     c.execute(query)
-    b = c.fetchone()
-    book = {}
-    i=0
-    for k in columns:
-        if b[i]!=None:
-            book[k]=b[i]
-        i+=1
+    book = _query_to_book(c.fetchone())
     c.close()
     return book
 
-
 # removes book from catalogue
 def removeBook(bookid):
     conn = sqlite3.connect(dbFile)
@@ -200,6 +169,11 @@ def deleteBooks(books):
     conn.commit()
     c.close()
 
+def _query_to_book(book_query):
+    # Make a dict out of column name and query results.
+    # Empty entries return None, which are removed from the dict.
+    return dict(filter(lambda t:t[1], zip(columns,book_query)))
+
 #########################################
 # Category related functions
 ########################################
index 387b692..4677065 100755 (executable)
@@ -85,8 +85,8 @@ def addForm():
     bf = form.bookForm(w,hb)
     (r,c)=w.getmaxyx()
     w.mvwin((my-r)//2,(mx-c)//2)
-    bf.lookup_isbn=bookData.openLibrary_isbn
-    bf.lookup_lccn=bookData.openLibrary_lccn
+    bf.lookup_isbn=book_data.openLibrary_isbn
+    bf.lookup_lccn=book_data.openLibrary_lccn
     bf.caption='Add a Book'
     bf.blabel = 'Add'
     book = bf.eventLoop()