smartyfy.mrindigi.com

Python Master Course V2 — 089. Database Application Architecture

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — DATABASES AND SQLITE · LESSON 089 / 200

Database Application Architecture

Estimated study: 80–110 minutes · Prerequisite: preceding lesson, functions, exceptions and structured data.

Course hub

Video lesson

Video not yet available; this area is reserved for a verified video link or player.

Learning outcomes

Separate repository, service and presentation layers. Explain the technical mechanism, interpret outputs, diagnose failures, test edge cases and apply the skill in a realistic system.

Detailed explanation and architecture

Repository code manages persistence; service code enforces business rules; presentation handles HTTP or CLI. Explicit boundaries improve tests and migrations.

Implementation sequence: define a contract; model inputs and outputs; apply explicit validation; use standard-library tools where possible; handle expected failures; write tests; document assumptions. Keep persistence or networking separate from business decisions and output formatting.

Professional concerns: predictable error handling, security boundaries, data integrity, performance under realistic load, logging without secrets, and reproducible environments. An example that works once is not automatically a production-ready service.

Understand and apply: Database Application Architecture

Separate responsibilities at boundaries that actually vary

A repository knows how to retrieve and store data. A service applies a business decision using that data. Presentation translates input and output for a person or protocol, such as a command-line message or HTTP response. These layers need not be large frameworks: a few named functions with explicit dependencies can establish the separation.

Suppose the question is whether a product needs reordering. SQL should retrieve the product’s current quantity. A service should compare that quantity with a validated threshold. Presentation should choose the words shown to a person. Putting all three tasks in one input-and-print function makes it difficult to test the rule without also opening a database and capturing terminal output.

Python example

import sqlite3
from contextlib import closing

def find_product(db, sku):
    row = db.execute("SELECT sku, qty FROM products WHERE sku = ?", (sku,)).fetchone()
    return None if row is None else {"sku": row[0], "qty": row[1]}

def needs_reorder(find, sku, minimum):
    if type(minimum) is not int or minimum < 0:
        raise ValueError("minimum must be a nonnegative integer")
    product = find(sku)
    if product is None:
        raise LookupError("product not found")
    return product["qty"] < minimum

def render_reorder(sku, required):
    return f"{sku}: {'reorder' if required else 'enough stock'}"

products = {"PEN": {"sku": "PEN", "qty": 3}}
def fake_find(sku):
    return products.get(sku)

result = needs_reorder(fake_find, "PEN", 5)
print(render_reorder("PEN", result))
assert needs_reorder(fake_find, "PEN", 3) is False
try:
    needs_reorder(fake_find, "MISSING", 5)
except LookupError as error:
    print(error)

# Exercise the actual repository, including a quote in the SKU.
with closing(sqlite3.connect(":memory:")) as db:
    db.execute("CREATE TABLE products(sku TEXT NOT NULL PRIMARY KEY, qty INTEGER NOT NULL CHECK(qty >= 0))")
    with db:
        db.execute("INSERT INTO products VALUES (?, ?)", ("PEN'S", 3))
    assert find_product(db, "PEN'S") == {"sku": "PEN'S", "qty": 3}
    assert find_product(db, "MISSING") is None
    assert needs_reorder(lambda sku: find_product(db, sku), "PEN'S", 5) is True
print("repository integration passed")

Expected output

PEN: reorder
product not found
repository integration passed

The service receives a callable rather than opening a database itself. The fake returns the same shape as the real repository and makes the rule test deterministic. At the exact threshold, three is not less than three, so reordering is false. The missing-product contract uses None at the repository boundary and LookupError at the service boundary; it never substitutes a fabricated zero-stock product.

Use both unit and integration tests

A unit test supplies fake_find to verify the business rule in isolation. The integration test creates a small in-memory SQLite table and calls find_product to verify the SQL, parameters and row mapping. Neither test replaces the other: a perfect fake cannot reveal a misspelled table name, while a database-only test may miss the threshold policy.

The composition point owns resources. It opens a connection, supplies a function such as lambda sku: find_product(db, sku), calls the service and closes the connection. For writes that must be atomic across several repository operations, the service or a dedicated transaction boundary coordinates one shared transaction. Individual repository helpers should not each commit independently when the use case requires all-or-nothing behavior.

Keep database tuples from leaking into presentation code by converting them into a documented product shape. Do not catch all database exceptions and return None; that would confuse “product absent” with “database unavailable.” As the program grows, use modules such as repository.py, service.py and cli.py, but split only when the boundary is useful. A three-file layout alone does not make a program well designed.

For the project, require tests for present stock, exact threshold, missing product and invalid threshold, plus a repository integration test that checks a quoted SKU is safely parameterized. Document the returned shape and error behavior so a future API layer can reuse the same service without parsing printed messages.

Runnable Python example

Requires Python 3.10+. Save as lesson89.py and run using python or python3. The example uses local or in-memory data and makes no external network request.

import sqlite3
from contextlib import closing
with closing(sqlite3.connect(':memory:')) as c:
    c.execute('CREATE TABLE products(id INTEGER PRIMARY KEY,name TEXT NOT NULL)')
    def get_product(db, pid):
        return db.execute('SELECT name FROM products WHERE id=?',(pid,)).fetchone()
    c.execute('INSERT INTO products VALUES (?,?)',(1,'Pen'))
    print(get_product(c,1))

Expected output:

('Pen',)

Reasoning walkthrough

Read the imports and setup, identify the data model, then follow each operation until the final result. Change one input and predict the effect before running it. Consider the behavior with empty data, invalid types and missing resources.

Independent validation example

def positive_count(value):
    if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
        raise ValueError("positive integer required")
    return value
assert positive_count(3) == 3
print("Input validated")

Expected: Input validated. Validation belongs at an explicit application boundary.

Guided real-world project

Build a layered inventory service with repository tests.

  1. Write a specification with data schema, required operations and failure conditions.
  2. Implement a minimal solution using small named functions.
  3. Add input validation and deliberate error responses.
  4. Test typical, boundary and invalid inputs.
  5. Verify the result against an independently calculated expectation.
  6. Document setup, limitations and recovery steps.

Acceptance: deterministic tests, correct handling of rejected data, no undocumented destructive behavior, and a clear explanation of architecture. This project is an assignment; its full implementation has not been independently executed.

Common mistakes and debugging

  • Concatenating untrusted input into SQL or URLs without proper encoding and parameterization.
  • Assuming remote services or databases always succeed.
  • Omitting transaction or timeout boundaries.
  • Confusing transport status with validated application data.
  • Testing only success paths and ignoring empty or malformed responses.

To debug, reproduce the failure, inspect the smallest failing input, check types and constraints, and add a regression test.

Practice with explained answers

Make a prediction before opening each answer. Then trace the example and explain the result in your own words.

Which layer should decide whether qty < minimum?

The service, because it is the business rule. The repository retrieves stock and presentation formats the result.

Why pass a find callable into the service?

It makes the dependency explicit and replaceable. A test can use an in-memory fake without opening SQLite, while production passes the real repository operation.

Why is a missing product not equivalent to zero stock?

Zero stock describes an existing product. Missing means no such product is known. Substituting zero would trigger a misleading reorder decision.

Can fake-repository tests prove the SQL is correct?

No. They test service behavior against the repository contract. An integration test must exercise actual SQL and result mapping.

Who should own a multi-step transaction?

The use-case boundary that knows which changes must succeed together. If each repository method commits independently, a later failure cannot undo earlier committed work.

Mastery checkpoint

Reproduce the sample, explain the design, complete the guided project, document three test cases and identify a realistic failure mode. No video, certificate or account-synced completion is claimed.

Course hub · Previous lesson 88 in hub · Continue with the next published lesson using the lesson navigation.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.