Editor

Transaction History Report

Advanced · Fix the bug · from Build an Inventory Management System with SQLite

From the lesson: Step 6: Transaction History Report

Auditing is critical. You need to know exactly what happened to your inventory and when. By joining the transactions table with the products table, we can generate a human-readable history that shows product names instead of just IDs.

Read this part of the lesson

The code below is supposed to generate a transaction history report, but it has bugs. Fix all the bugs so it correctly:

1. Joins transactions with products to show product names.

2. Prints "=== TRANSACTION HISTORY ===" as a header.

3. Prints each transaction as "{type}: {quantity} x {product_name}".

4. Prints the total number of transactions at the end.

import sqlite3
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
cursor.execute('CREATE TABLE products (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, category TEXT, price REAL, quantity INTEGER DEFAULT 0, reorder_level INTEGER DEFAULT 10)')
cursor.execute('CREATE TABLE transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, product_id INTEGER, type TEXT, quantity INTEGER, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('INSERT INTO products (name, category, price, quantity) VALUES (?, ?, ?, ?)', ('Laptop', 'Electronics', 999.99, 0))
cursor.execute('INSERT INTO products (name, category, price, quantity) VALUES (?, ?, ?, ?)', ('Mouse', 'Electronics', 29.99, 0))
# Record some transactions
for pid, ttype, qty in [(1, 'buy', 50), (2, 'buy', 200), (1, 'sell', 10), (2, 'sell', 25)]:
cursor.execute('INSERT INTO transactions (product_id, type, quantity) VALUES (?, ?, ?)', (pid, ttype, qty))
conn.commit()
def transaction_history(cursor):
# BUG 1: Wrong JOIN syntax
cursor.execute('''
SELECT t.type, t.quantity, p.name
FROM transactions t
JOIN products ON t.product_id = products.id
ORDER BY t.id
''')
rows = cursor.fetchall()
# BUG 2: Wrong header
print('=== TRANSACTIONS ===')
for row in rows:
# BUG 3: Wrong index order for type, quantity, name
print(f' {row[2]}: {row[1]} x {row[0]}')
# BUG 4: Wrong count variable
print(f'\nTotal transactions: {len(row)}')
transaction_history(cursor)

More Inventory System exercises

All Python exercises · 50 practice problems · Practical Projects quiz