Requirements and schema
Overview
Build a small multi-tenant ordering system. A tenant owns its products and orders; a line represents one product in one order. Product stock cannot be negative, quantity must be positive, and unit price is stored in integer cents. IDs are local to each tenant. Decide the grain and invariants before creating tables.
First example
SELECT tenant,id,stock FROM cp_product ORDER BY tenant,id;Observed SQLite result (rows in JSON):
[ [ 1, 1, 8 ], [ 1, 2, 5 ], [ 2, 1, 7 ]]How it works
Composite primary and foreign keys include tenant, so an order line cannot reference another tenant’s product. The price on the line is a historical sale price, not a lookup of today’s price. The fixture starts with stock already representing available inventory. The first query lists each product; the second joins using the full order identity and produces one total per paid order. Cancelled orders are excluded.
SQLite ordinary INTEGER affinity alone does not enforce integer quantities or cents. The V90 fixture adds CHECK constraints with typeof(...) = 'integer' for stock, quantity and cents. These check the stored representation, not the original input type; validate inputs before binding. This is SQLite-specific, not portable DDL.
Practical example
SELECT o.tenant,o.id,SUM(l.qty*l.cents) AS total FROM cp_order o JOIN cp_line l ON l.tenant=o.tenant AND l.order_id=o.id WHERE o.status='paid' GROUP BY o.tenant,o.id ORDER BY o.tenant,o.id;Observed SQLite result (rows in JSON):
[ [ 1, 1, 400 ], [ 2, 1, 900 ]]Practice and mistakes
Practice: diagram the three relations, document the line grain, and add an optional customer relation with a tenant-aware key. Hint 1: list each invariant. Hint 2: include tenant in both sides of each FK. Mistake: joining on order ID alone; ID 1 occurs in both tenants.
PostgreSQL 17 example — NOT RUN
SELECT o.tenant,o.id,SUM(l.qty*l.cents) AS total FROM cp_order o JOIN cp_line l ON l.tenant=o.tenant AND l.order_id=o.id WHERE o.status='paid' GROUP BY o.tenant,o.id ORDER BY o.tenant,o.id;Expected result, not executed: "Rows (1,1,400),(2,1,900)."