Intermediate · Data & Files · Packages: standard library only

Project 16: Inventory Manager with SQLite

A command driven inventory tracker that stores products and sales in an SQLite database, with low stock alerts and a totals report.

What you will learn

Prerequisites

Packages and installation

Packages: standard library only.

Project structure

Folder layout
inventory/
  main.py
  inventory.db   (created when the program runs)

Step-by-step build

  1. Plan the tables. We need a products table (name, quantity, price) and a sales table that points to a product. UNIQUE and CHECK rules stop bad data.
  2. Connect and create tables. connect() opens inventory.db and runs CREATE TABLE IF NOT EXISTS, so the program works on the first and the hundredth run.
  3. Add or restock products. add_product looks for the name first. If it exists we add to its quantity, otherwise we insert a new row. Always pass values with ? placeholders.
  4. Sell with a transaction. sell_product checks stock, then updates the quantity and inserts a sale row inside 'with conn:' so both happen together or not at all.
  5. List, low stock and remove. Use SELECT with ORDER BY and WHERE. The low stock limit is a constant, so it is easy to change.
  6. Report with aggregates. COUNT, SUM and COALESCE give the stock value and revenue in single queries.
  7. Read commands. main() loops over sys.stdin, so you can type commands or pipe a file into the program. Save the sample commands as commands.txt and run it.

Complete source code

main.py
"""Inventory Manager with SQLite - a command driven console program."""
import sqlite3
import sys

DB_FILE = "inventory.db"  # created in the current folder
LOW_STOCK = 5             # items at or below this count are "low"

HELP = """Commands:
  add <name> <qty> <price>   add a new product (or restock an existing one)
  sell <name> <qty>          sell units and record the sale
  remove <name>              delete a product
  list                       show all products
  low                        show products with low stock
  report                     show totals and sales
  help                       show this help
  quit                       leave the program"""


def connect():
    """Open the database and create the tables if they do not exist."""
    conn = sqlite3.connect(DB_FILE)
    conn.execute(
        "CREATE TABLE IF NOT EXISTS products ("
        "id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "name TEXT UNIQUE NOT NULL,"
        "qty INTEGER NOT NULL CHECK (qty >= 0),"
        "price REAL NOT NULL CHECK (price >= 0))"
    )
    conn.execute(
        "CREATE TABLE IF NOT EXISTS sales ("
        "id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "product_id INTEGER NOT NULL REFERENCES products(id),"
        "qty INTEGER NOT NULL,"
        "total REAL NOT NULL)"
    )
    conn.commit()
    return conn


def add_product(conn, name, qty, price):
    """Insert a product; if it exists, add to its stock and update the price."""
    row = conn.execute("SELECT id FROM products WHERE name = ?", (name,)).fetchone()
    if row:
        conn.execute("UPDATE products SET qty = qty + ?, price = ? WHERE id = ?",
                     (qty, price, row[0]))
        print(f"Restocked {name}: +{qty} units")
    else:
        conn.execute("INSERT INTO products (name, qty, price) VALUES (?, ?, ?)",
                     (name, qty, price))
        print(f"Added {name}: {qty} units at {price:.2f}")
    conn.commit()


def sell_product(conn, name, qty):
    """Reduce stock and write a row in the sales table (one transaction)."""
    row = conn.execute("SELECT id, qty, price FROM products WHERE name = ?",
                       (name,)).fetchone()
    if row is None:
        print(f"Error: no product called {name}")
        return
    pid, have, price = row
    if qty > have:
        print(f"Error: only {have} of {name} in stock")
        return
    with conn:  # commits on success, rolls back on error
        conn.execute("UPDATE products SET qty = qty - ? WHERE id = ?", (qty, pid))
        conn.execute("INSERT INTO sales (product_id, qty, total) VALUES (?, ?, ?)",
                     (pid, qty, qty * price))
    print(f"Sold {qty} x {name} for {qty * price:.2f}")


def remove_product(conn, name):
    """Delete a product and its sales history."""
    row = conn.execute("SELECT id FROM products WHERE name = ?", (name,)).fetchone()
    if row is None:
        print(f"Error: no product called {name}")
        return
    with conn:
        conn.execute("DELETE FROM sales WHERE product_id = ?", (row[0],))
        conn.execute("DELETE FROM products WHERE id = ?", (row[0],))
    print(f"Removed {name}")


def print_rows(rows):
    """Print products as a simple aligned table."""
    if not rows:
        print("(no products)")
        return
    print(f"{'ID':<4}{'Name':<12}{'Qty':>5}{'Price':>9}")
    for pid, name, qty, price in rows:
        print(f"{pid:<4}{name:<12}{qty:>5}{price:>9.2f}")


def report(conn):
    """Show stock value and total sales using SQL aggregate functions."""
    count, units, value = conn.execute(
        "SELECT COUNT(*), COALESCE(SUM(qty), 0), COALESCE(SUM(qty * price), 0) "
        "FROM products").fetchone()
    sold, revenue = conn.execute(
        "SELECT COALESCE(SUM(qty), 0), COALESCE(SUM(total), 0) FROM sales").fetchone()
    print(f"Products: {count}  Units in stock: {units}  Stock value: {value:.2f}")
    print(f"Units sold: {sold}  Revenue: {revenue:.2f}")


def handle(conn, line):
    """Run one command line. Return False when the user wants to quit."""
    parts = line.split()
    if not parts:
        return True
    cmd, args = parts[0].lower(), parts[1:]
    try:
        if cmd == "add" and len(args) == 3:
            add_product(conn, args[0], int(args[1]), float(args[2]))
        elif cmd == "sell" and len(args) == 2:
            sell_product(conn, args[0], int(args[1]))
        elif cmd == "remove" and len(args) == 1:
            remove_product(conn, args[0])
        elif cmd == "list":
            print_rows(conn.execute(
                "SELECT id, name, qty, price FROM products ORDER BY name").fetchall())
        elif cmd == "low":
            print_rows(conn.execute(
                "SELECT id, name, qty, price FROM products WHERE qty <= ? ORDER BY qty",
                (LOW_STOCK,)).fetchall())
        elif cmd == "report":
            report(conn)
        elif cmd == "help":
            print(HELP)
        elif cmd == "quit":
            return False
        else:
            print("Unknown or incomplete command. Type 'help'.")
    except ValueError:
        print("Error: quantity must be a whole number and price a number")
    except sqlite3.IntegrityError as err:
        print(f"Database error: {err}")
    return True


def main():
    conn = connect()
    print("Inventory Manager (type 'help' for commands)")
    for line in sys.stdin:  # works with typed input and with piped input
        print(f"> {line.strip()}")
        if not handle(conn, line):
            break
    conn.close()
    print("Goodbye!")


if __name__ == "__main__":
    main()

Code explanation

Placeholders (?)

Values are never pasted into the SQL text. This avoids SQL injection and quoting bugs.

Constraints

CHECK (qty >= 0) and UNIQUE make the database itself reject wrong data; we catch sqlite3.IntegrityError and print a friendly message.

Transactions

'with conn:' commits when the block ends normally and rolls back if an exception happens, keeping stock and sales consistent.

Command dispatch

handle() splits the line, picks the command and checks the argument count. ValueError from int() and float() is caught in one place.

Expected output

$ python3 main.py < commands.txt
Inventory Manager (type 'help' for commands)
> add pen 20 1.5
Added pen: 20 units at 1.50
> add notebook 4 3.25
Added notebook: 4 units at 3.25
> add stapler 2 8
Added stapler: 2 units at 8.00
> add pen 10 1.6
Restocked pen: +10 units
> list
ID  Name          Qty    Price
2   notebook        4     3.25
1   pen            30     1.60
3   stapler         2     8.00
> sell pen 12
Sold 12 x pen for 19.20
> sell stapler 5
Error: only 2 of stapler in stock
> sell ghost 1
Error: no product called ghost
> add bad x 2
Error: quantity must be a whole number and price a number
> low
ID  Name          Qty    Price
3   stapler         2     8.00
2   notebook        4     3.25
> remove stapler
Removed stapler
> report
Products: 2  Units in stock: 22  Stock value: 41.80
Units sold: 12  Revenue: 19.20
> quit
Goodbye!

Common errors and solutions

Error: sqlite3.OperationalError: no such table: products
Solution: The tables were not created. Call connect() first, or delete a broken inventory.db and run again.
Error: sqlite3.IntegrityError: UNIQUE constraint failed
Solution: A product with that name exists already. Use add to restock instead of inserting a duplicate.
Error: Error: quantity must be a whole number and price a number
Solution: Type numbers, for example: add pen 20 1.5. Do not use letters or commas.
Error: sqlite3.OperationalError: database is locked
Solution: Another program has the file open. Close it, and always call conn.close() when you finish.

Ideas to improve the project