#!/bin/bash # Reproduces every factual claim in # https://www.heatware.net/postgresql/materialized-views/ # # Creates a throwaway PostgreSQL cluster in a temp directory on port 55443, # loads 2,000,000 synthetic orders, runs each claim, prints PASS/FAIL, # then stops the cluster and deletes it. # It does not touch any existing PostgreSQL installation or data. # # Timings printed below are from YOUR machine and will differ from the article's. # The PASS/FAIL assertions are on behaviour (locks, errors), not on absolute times. # # Requires: initdb, pg_ctl, psql on PATH (PostgreSQL 9.4+ for REFRESH CONCURRENTLY). # Runtime: roughly one minute, most of it generating the rows. # Usage: bash verify-materialized-views.sh set -u PORT=55443 PGDATA_TMP="$(mktemp -d -t hwmatview)" trap 'pg_ctl -D "$PGDATA_TMP" stop -m immediate >/dev/null 2>&1; rm -rf "$PGDATA_TMP"' EXIT PASSES=0 FAILS=0 q() { psql -h 127.0.0.1 -p $PORT -U postgres -X -At -c "SET TimeZone='UTC';" "$@" 2>&1 | grep -v '^SET$'; } hdr(){ printf '\n\033[1m%s\033[0m\n' "$*"; } check() { local claim="$1" want="$2" got="$3" if [ "$want" = "$got" ]; then PASSES=$((PASSES+1)); printf ' \033[32mPASS\033[0m %s\n' "$claim" else FAILS=$((FAILS+1)); printf ' \033[31mFAIL\033[0m %s\n' "$claim" printf ' expected: %s\n actual: %s\n' "$want" "$got" fi } # check_num (integer-ish comparison on ms) check_num() { local claim="$1" op="$2" thr="$3" got="$4" local gi=${got%%.*} if [ -n "$gi" ] && awk "BEGIN{exit !($gi $op $thr)}"; then PASSES=$((PASSES+1)); printf ' \033[32mPASS\033[0m %s (measured %s ms)\n' "$claim" "$got" else FAILS=$((FAILS+1)); printf ' \033[31mFAIL\033[0m %s (measured %s ms, wanted %s %s)\n' "$claim" "$got" "$op" "$thr" fi } # time_query -> prints milliseconds as reported by psql \timing time_query() { psql -h 127.0.0.1 -p $PORT -U postgres -X -At \ -c "\timing on" -c "SET search_path=public;" -c "$1" 2>&1 \ | grep '^Time:' | tail -1 | awk '{print $2}' } command -v initdb >/dev/null || { echo "initdb not on PATH"; exit 1; } hdr "Environment" initdb --version initdb -D "$PGDATA_TMP" -U postgres --auth=trust -E UTF8 --locale=C >/dev/null 2>&1 \ || { echo "initdb failed"; exit 1; } pg_ctl -D "$PGDATA_TMP" -o "-p $PORT" -l "$PGDATA_TMP/server.log" start >/dev/null 2>&1 for _ in $(seq 1 30); do q -c "SELECT 1" >/dev/null 2>&1 && break; sleep 1; done q -c "SELECT version();" hdr "Fixture: 2,000,000 orders spread over a year (this is the slow part)" q -c "CREATE TABLE orders ( id bigserial PRIMARY KEY, customer_id int, amount numeric(10,2), created_at timestamptz ); INSERT INTO orders (customer_id, amount, created_at) SELECT (random()*5000)::int, (random()*500)::numeric(10,2), now() - (random()*365) * interval '1 day' FROM generate_series(1,2000000); ANALYZE orders;" >/dev/null echo " rows: $(q -c 'SELECT count(*) FROM orders;')" echo " size: $(q -c "SELECT pg_size_pretty(pg_total_relation_size('orders'));")" q -c "CREATE MATERIALIZED VIEW daily_sales AS SELECT date_trunc('day', created_at) AS day, count(*) AS orders, sum(amount) AS revenue FROM orders GROUP BY 1;" >/dev/null echo " matview rows: $(q -c 'SELECT count(*) FROM daily_sales;')" hdr "Claim group 1: there is NO incremental refresh in PostgreSQL" check "REFRESH ... INCREMENTALLY is not valid syntax" \ "yes" \ "$(q -c 'REFRESH MATERIALIZED VIEW INCREMENTALLY daily_sales;' | grep -qi '^ERROR: syntax error' && echo yes || echo no)" q -c 'REFRESH MATERIALIZED VIEW INCREMENTALLY daily_sales;' | head -1 | sed 's/^/ server said: /' check "only CONCURRENTLY is accepted between VIEW and the name" \ "REFRESH MATERIALIZED VIEW" \ "$(psql -h 127.0.0.1 -p $PORT -U postgres -X -c 'REFRESH MATERIALIZED VIEW daily_sales;' 2>&1 | tail -1)" hdr "Claim group 2: plain REFRESH takes an AccessExclusiveLock and blocks readers" # Session A holds the refresh lock open for 3 seconds inside a transaction. psql -h 127.0.0.1 -p $PORT -U postgres -X -q >/dev/null 2>&1 <<'SQL' & BEGIN; REFRESH MATERIALIZED VIEW daily_sales; SELECT pg_sleep(3); COMMIT; SQL APID=$! sleep 2 LOCKS=$(q -c "SELECT mode FROM pg_locks WHERE relation='daily_sales'::regclass ORDER BY mode;") echo " locks held during plain REFRESH:"; echo "$LOCKS" | sed 's/^/ /' check "plain REFRESH holds AccessExclusiveLock" "yes" \ "$(echo "$LOCKS" | grep -q '^AccessExclusiveLock$' && echo yes || echo no)" BLOCKED_MS=$(time_query "SELECT count(*) FROM daily_sales;") check_num "a reader BLOCKS behind it" ">" 500 "$BLOCKED_MS" wait $APID hdr "Claim group 3: CONCURRENTLY requires a UNIQUE index" CONC_ERR=$(q -c 'REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;') echo "$CONC_ERR" | sed 's/^/ /' check "CONCURRENTLY without a unique index is refused" "yes" \ "$(echo "$CONC_ERR" | grep -q 'cannot refresh materialized view .* concurrently' && echo yes || echo no)" check "...and the hint names the fix" "yes" \ "$(echo "$CONC_ERR" | grep -q 'Create a unique index with no WHERE clause' && echo yes || echo no)" q -c "CREATE UNIQUE INDEX daily_sales_day_idx ON daily_sales (day);" >/dev/null check "with a unique index it succeeds" "REFRESH MATERIALIZED VIEW" \ "$(psql -h 127.0.0.1 -p $PORT -U postgres -X -c 'REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;' 2>&1 | tail -1)" hdr "Claim group 4: CONCURRENTLY does NOT block readers" psql -h 127.0.0.1 -p $PORT -U postgres -X -q >/dev/null 2>&1 <<'SQL' & BEGIN; REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales; SELECT pg_sleep(3); COMMIT; SQL BPID=$! sleep 2 LOCKS2=$(q -c "SELECT mode FROM pg_locks WHERE relation='daily_sales'::regclass ORDER BY mode;") echo " locks held during CONCURRENTLY refresh:"; echo "$LOCKS2" | sed 's/^/ /' check "CONCURRENTLY does NOT take AccessExclusiveLock" "no" \ "$(echo "$LOCKS2" | grep -q '^AccessExclusiveLock$' && echo yes || echo no)" FREE_MS=$(time_query "SELECT count(*) FROM daily_sales;") check_num "a reader is NOT blocked" "<" 500 "$FREE_MS" wait $BPID hdr "Claim group 5: WITH NO DATA leaves the view unreadable" q -c "CREATE MATERIALIZED VIEW customer_totals AS SELECT customer_id, sum(amount) AS lifetime FROM orders GROUP BY 1 WITH NO DATA;" >/dev/null check "pg_matviews.ispopulated reports false" "f" \ "$(q -c "SELECT ispopulated FROM pg_matviews WHERE matviewname='customer_totals';")" check "SELECT from an unpopulated matview errors" "yes" \ "$(q -c 'SELECT * FROM customer_totals LIMIT 1;' | grep -q 'has not been populated' && echo yes || echo no)" q -c "CREATE UNIQUE INDEX ct_idx ON customer_totals (customer_id);" >/dev/null check "CONCURRENTLY is refused on an unpopulated matview" "yes" \ "$(q -c 'REFRESH MATERIALIZED VIEW CONCURRENTLY customer_totals;' \ | grep -q 'CONCURRENTLY cannot be used when the materialized view is not populated' && echo yes || echo no)" hdr "Claim group 6: what the matview actually buys you (measured, this machine)" echo " Aggregate over the 2,000,000-row base table:" q -c "EXPLAIN ANALYZE SELECT date_trunc('day', created_at) AS day, count(*), sum(amount) FROM orders GROUP BY 1;" | sed 's/^/ /' echo " Same result read from the materialized view:" q -c "EXPLAIN ANALYZE SELECT day, orders, revenue FROM daily_sales;" | sed 's/^/ /' BASE_MS=$(time_query "SELECT date_trunc('day', created_at) AS day, count(*), sum(amount) FROM orders GROUP BY 1 OFFSET 100000;") MV_MS=$(time_query "SELECT day, orders, revenue FROM daily_sales OFFSET 100000;") echo " wall clock, output discarded via OFFSET: base=${BASE_MS} ms matview=${MV_MS} ms" check_num "reading the matview is faster than re-aggregating" "<" "${BASE_MS%%.*}" "$MV_MS" echo " Refresh cost (the price you pay for that speed):" echo " plain REFRESH: $(time_query 'REFRESH MATERIALIZED VIEW daily_sales;') ms" echo " REFRESH CONCURRENTLY: $(time_query 'REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;') ms" check "an index on the matview is usable" "yes" \ "$(q -c "EXPLAIN SELECT * FROM daily_sales WHERE day = date_trunc('day', now());" \ | grep -q 'Index Scan using daily_sales_day_idx' && echo yes || echo no)" hdr "Result" printf ' %d passed, %d failed\n' "$PASSES" "$FAILS" echo " cluster $PGDATA_TMP will be stopped and deleted on exit" [ "$FAILS" -eq 0 ] || exit 1