From 066d3a4364f2cb724989f9f01e1fcfc0ae6c84ea Mon Sep 17 00:00:00 2001 From: oysteini Date: Sun, 9 Oct 2011 13:45:15 +0000 Subject: [PATCH] Improved list book command. Wrote a better query, so I could remove much ugliness from the Python code. Added trimming of book titles that are too long. --- cli/worblehat.py | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/cli/worblehat.py b/cli/worblehat.py index 715ec9b..cb0ef3f 100755 --- a/cli/worblehat.py +++ b/cli/worblehat.py @@ -17,11 +17,12 @@ from util import * # print fetchall_dict(c) q_list_books = \ - 'SELECT isbn, book.id AS id, title, category, person.id AS person_id, ' \ - ' lastname, firstname ' \ + 'SELECT isbn, book.id AS id, title, category, ' \ + 'array_to_string(array_agg(person.lastname || \' (\' || person.id || \')\'), \', \') AS persons ' \ 'FROM book ' \ 'LEFT JOIN bookperson ON book.isbn=bookperson.book ' \ - 'LEFT JOIN person ON bookperson.person=person.id' + 'LEFT JOIN person ON bookperson.person=person.id ' \ + 'GROUP BY isbn, book.id, title, category' q_list_persons = \ 'SELECT person.id, person.firstname, person.lastname, ' \ ' COUNT(bookperson.id) AS num_books ' \ @@ -223,20 +224,11 @@ def list_books(connection): c = connection.cursor() c.execute(q_list_books) #print fetchall_dict(c) - s = '' - last_isbn = None for i in xrange(c.rowcount): - d = fetchone_dict(c) - if d['isbn'] != last_isbn: - if last_isbn != None: - s += '\n' - s += '%-13s %-10s %-40s' % (d['isbn'], str_or_empty(d['id']), d['title']) - if d['person_id']: - s += ' ' + d['person_id'] - else: - s += ', ' + d['person_id'] - last_isbn = d['isbn'] - print s + book = fetchone_dict(c) + print('%-13s %-10s %-60s %s' % + (book['isbn'], str_or_empty(book['id']), + cut_str(book['title'], 60), book['persons'])) def list_persons(connection): c = connection.cursor()