SQL · Module 15 · Lesson 11 min read

Project: BudgetBuddy Production Database

Goal

A production-ready Supabase/PostgreSQL schema for a budgeting app that can go live.

Requirements checklist

  • Tables: profiles, accounts, categories, transactions (income/expense), budgets
  • Ownership: every row has user_id UUID DEFAULT auth.uid()
  • RLS on every table: users only see and change their own data (built-in categories readable by all)
  • Triggers:
    • updated_at on every update
    • keep accounts.balance in sync on insert/update/delete of transactions
  • Constraints: positive amounts, valid types, unique budget per category+month, non-negative cash balances
  • Indexes: (user_id, occurred_on), foreign keys
  • Views (security_invoker): monthly summary, budget vs actual
  • API function for the dashboard (one rpc() call returns everything as JSON)

Steps

  1. Write the schema migration (tables, constraints, indexes)
  2. Add triggers and test them with inserts/updates/deletes
  3. Enable RLS and write policies; test as two different users
  4. Create views and the dashboard function
  5. Seed realistic data and check every report
  6. Run Supabase Advisors (security + performance lints) and fix warnings

What this project proves

Data modelling, constraints, triggers, RLS, aggregation, JSON APIs — the full stack of skills from this course.

Stretch goals

Recurring bills with generate_series, savings goals, loan EMI schedules, CSV export, pg_cron reminders, materialized monthly stats.

Example

SQL
-- ===== Schema =====
CREATE TABLE p_accounts (
  id       BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id  UUID NOT NULL DEFAULT auth.uid(),
  name     TEXT NOT NULL,
  balance  NUMERIC(12,2) NOT NULL DEFAULT 0,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (user_id, name)
);
CREATE TABLE p_transactions (
  id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id     UUID NOT NULL DEFAULT auth.uid(),
  account_id  BIGINT NOT NULL REFERENCES p_accounts(id) ON DELETE CASCADE,
  type        TEXT NOT NULL CHECK (type IN ('income', 'expense')),
  category    TEXT NOT NULL,
  amount      NUMERIC(12,2) NOT NULL CHECK (amount > 0),
  occurred_on DATE NOT NULL DEFAULT CURRENT_DATE
);
CREATE INDEX ON p_transactions (user_id, occurred_on DESC);
CREATE INDEX ON p_transactions (account_id);

-- ===== Trigger: keep the account balance in sync =====
CREATE FUNCTION p_sync_balance() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP IN ('UPDATE', 'DELETE') THEN      -- undo the old row's effect
    UPDATE p_accounts SET balance = balance - CASE WHEN OLD.type = 'income' THEN OLD.amount ELSE -OLD.amount END,
                          updated_at = now()
    WHERE id = OLD.account_id;
  END IF;
  IF TG_OP IN ('INSERT', 'UPDATE') THEN      -- apply the new row's effect
    UPDATE p_accounts SET balance = balance + CASE WHEN NEW.type = 'income' THEN NEW.amount ELSE -NEW.amount END,
                          updated_at = now()
    WHERE id = NEW.account_id;
  END IF;
  RETURN NULL;
END $$;
CREATE TRIGGER p_transactions_balance AFTER INSERT OR UPDATE OR DELETE ON p_transactions
FOR EACH ROW EXECUTE FUNCTION p_sync_balance();

-- ===== Row Level Security =====
ALTER TABLE p_accounts ENABLE ROW LEVEL SECURITY;
ALTER TABLE p_transactions ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_accounts ON p_accounts FOR ALL TO authenticated
  USING (user_id = (SELECT auth.uid())) WITH CHECK (user_id = (SELECT auth.uid()));
CREATE POLICY own_transactions ON p_transactions FOR ALL TO authenticated
  USING (user_id = (SELECT auth.uid())) WITH CHECK (user_id = (SELECT auth.uid()));
GRANT SELECT, INSERT, UPDATE, DELETE ON p_accounts, p_transactions TO authenticated;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO authenticated;

-- ===== Dashboard API function (one rpc call) =====
CREATE FUNCTION p_dashboard(p_month DATE) RETURNS JSONB
LANGUAGE sql STABLE SECURITY INVOKER AS $$
  SELECT jsonb_build_object(
    'income',   COALESCE(sum(amount) FILTER (WHERE type = 'income'), 0),
    'expenses', COALESCE(sum(amount) FILTER (WHERE type = 'expense'), 0),
    'by_category', (SELECT jsonb_object_agg(category, total) FROM (
        SELECT category, sum(amount) AS total FROM p_transactions
        WHERE type = 'expense' AND occurred_on >= p_month AND occurred_on < p_month + INTERVAL '1 month'
        GROUP BY category) c),
    'balances', (SELECT jsonb_object_agg(name, balance) FROM p_accounts)
  )
  FROM p_transactions
  WHERE occurred_on >= p_month AND occurred_on < p_month + INTERVAL '1 month';
$$;
GRANT EXECUTE ON FUNCTION p_dashboard(DATE) TO authenticated;

-- ===== Try it as a logged-in user =====
SET ROLE authenticated;
SET request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';

INSERT INTO p_accounts (name) VALUES ('Bank'), ('Cash');
INSERT INTO p_transactions (account_id, type, category, amount, occurred_on) VALUES
  (1, 'income',  'Salary',    60000, '2026-11-01'),
  (1, 'expense', 'Rent',      15000, '2026-11-02'),
  (2, 'income',  'Gift',       2000, '2026-11-03'),
  (2, 'expense', 'Food',        850, '2026-11-04'),
  (1, 'expense', 'Food',       4200, '2026-11-10');
UPDATE p_transactions SET amount = 900 WHERE category = 'Food' AND account_id = 2;   -- edit

SELECT name, balance FROM p_accounts ORDER BY id;     -- Bank 40800.00 | Cash 1100.00
SELECT jsonb_pretty(p_dashboard('2026-11-01'));

-- Another user sees nothing of this
SET request.jwt.claim.sub = '22222222-2222-2222-2222-222222222222';
SELECT count(*) FROM p_transactions;                  -- 0 ✅
RESET ROLE;