-- Statement-based replication is nondeterministic, DDIA 2e Ch. 6.
-- If a leader shipped SQL TEXT to followers (statement-based replication), a
-- statement calling now() or random() would be re-evaluated on each node and
-- produce DIFFERENT rows -- the replica diverges from the leader. This is why
-- real systems ship the already-computed row (logical/row-based) or the WAL
-- (physical), not the statement.
--
--   docker exec ddia-ch6-stmt psql -U postgres -d study -f /tmp/statement_replication.sql

DROP TABLE IF EXISTS events;
CREATE TABLE events (who text, t timestamptz, r double precision);

-- The LEADER executes the statement and computes now()/random() locally:
INSERT INTO events SELECT 'leader', now(), random();

-- A FOLLOWER replays the IDENTICAL statement text -- now()/random() are
-- re-evaluated on the follower, at a different instant, with a different seed:
INSERT INTO events SELECT 'follower', now(), random();

-- The two rows disagree -> the replica has diverged from the leader:
SELECT who, to_char(t, 'HH24:MI:SS.US') AS t, round(r::numeric, 6) AS random
FROM events ORDER BY t;
