An exercise needs a known starting state and a safe way back to it. Build a small, inspectable Harbor Supply fixture, check it through a restricted role, and deliberately test a refused reset before relying on it in later queries.
Start with the new owned empty container database from the
connection lesson. Return to its same host
workspace and load your inspected session.sh. Recheck its local context,
container/volume labels, database asql_lab, server 18.6 and bootstrap identity.
Do not run these scripts against an existing unrelated database or native
instance. No new service or account is needed.
The earlier readiness tables were separate paper datasets. This executable fixture extends the scenario: order 101 now has a third line and two refunds. Use the contract below, not a remembered total from the diagnostic.
Understand the stored facts first
A schema is a namespace inside a database. harbor.orders means the
orders table in schema harbor. Schema qualification makes the intended
object explicit instead of depending on an implicit search order.
| Table | One row represents | Key and relationship | Baseline rows |
|---|---|---|---|
| harbor.organizations | One fictional organization | org_id identifies it | 2 |
| harbor.orders | One order | order_id; org_id references an organization | 4 |
| harbor.line_items | One charge line | line_id; order_id references an order | 6 |
| harbor.refunds | One refund amount | refund_id; order_id references an order | 3 |
| harbor.fulfilment_events | One observed fulfilment event | event_id; order_id references an order | 5 |
Amounts are exact stored decimal totals in one fictional currency unit, not
unit prices. Both line and refund amounts are non-negative; refunds are stored
as non-negative amounts to subtract from gross. Equal amounts on different keys
remain separate facts. Order 103 has no line or event; 102 has a missing channel.
The timestamps include explicit +00 UTC offsets; timestamptz is PostgreSQL's
short name for timestamp with time zone. Time interpretation is developed in
later lessons, rather than relying on your machine's current zone.
The baseline arithmetic is small enough to check independently:
| Order | Line amounts | Gross | Refund amounts | Refunded |
|---|---|---|---|---|
| 101 | 40 + 60 + 20 | 120.00 | 5 + 15 | 20.00 |
| 102 | 30 | 30.00 | none | no refund group |
| 103 | none | no line group | none | no refund group |
| 104 | 25 + 25 | 50.00 | 5 | 5.00 |
All line amounts total 200.00; refunds total 25.00. “No group” describes absence from a grouped child-table query. It is not an observed zero-valued row. The reporting lesson will state when a business report deliberately displays zero for a missing child aggregate.
Why the setup has three roles and a marker
The bootstrap administrator creates the owned schema and roles.
asql_owner cannot log in; it owns the ordinary fixture objects.
asql_student can log in and has only the stated schema/table permissions for
routine practice. It is neither a superuser nor a member of the owner role.
The setup administrator creates the schema before switching to its owner;
owning an object is different from permission to create a schema in a database.
asql_control.lab records the course ID, your non-secret generated lab ID and
the fixture identifier harbor-small. Only the bootstrap role can alter that
marker. The student can read it for target checks. A marker adds a guard after
initialization; it does not replace the local engine/storage ownership proof.
The student has no password in this fixture. Its demonstrated route is the image's trusted in-container Unix socket, reached through your own Docker engine. Do not expose a passwordless/trusted route over a network or claim this tests application authentication. Restricted TCP logins require their own authentication setup and are not silently enabled by this lesson.
The narrow transaction and client bridge
Normally, psql sends statements separately and successful statements can commit
individually. BEGIN starts an explicit transaction; COMMIT makes its grouped
changes permanent. If a failed non-interactive script stops and disconnects
with that transaction still open, its uncommitted changes are rolled back.
That is why the fixture's table/role creation and inserts are grouped, rather
than leaving half a fixture behind.
ON_ERROR_STOP tells the client to stop on an SQL error. It does not undo an
earlier committed transaction. A later lesson covers savepoints and error
state more deeply. These scripts use explicit numeric keys, not sequences;
do not generalize rollback into a promise to reverse sequence advancement or
every possible external effect.
The script's backslash lines are psql instructions. \gset executes a
single-row check and stores its named result as a client variable. \if chooses
the allowed branch. :{?lab_id} checks that the input exists; :'lab_id'
inserts it as an SQL-quoted text value, not an object name or application-driver
binding. A rejected check prints a reason and intentionally evaluates 1 / 0.
That harmless failing SELECT makes stop-on-error terminate the input before
the mutation section. Do not remove the failure to bypass a rejected guard.
The version check expects the server's machine-readable value 180006 for
18.6. Timeouts bound lock waiting and statement work for this client session
only. They do not modify global configuration or another session.
Create the complete bootstrap input
Save the following complete file as bootstrap.sql in your owned host lab
folder. Nothing is omitted; it has no external SQL-file include.
\set ON_ERROR_STOP on
\if :{?lab_id}
\else
\echo 'Stop: supply the non-secret lab_id from connection.txt.'
SELECT 1 / 0 AS guard_rejected;
\endif
SELECT current_database() = 'asql_lab'
AND current_user = 'asql_bootstrap'
AND current_setting('server_version_num') = '180006' AS target_ok
\gset
\if :target_ok
\else
\echo 'Stop: wrong database, execution role or server release.'
SELECT 1 / 0 AS guard_rejected;
\endif
SET lock_timeout = '3s';
SET statement_timeout = '15s';
SELECT COUNT(*) = 0 AS empty_ok
FROM information_schema.tables
WHERE table_schema <> 'pg_catalog' AND table_schema <> 'information_schema'
\gset
\if :empty_ok
\else
\echo 'Stop: bootstrap requires the new owned empty database.'
SELECT 1 / 0 AS guard_rejected;
\endif
SELECT COUNT(*) = 0 AS roles_clear
FROM pg_roles WHERE rolname IN ('asql_owner', 'asql_student')
\gset
\if :roles_clear
\else
\echo 'Stop: the proposed lab roles already exist.'
SELECT 1 / 0 AS guard_rejected;
\endif
BEGIN;
CREATE ROLE asql_owner NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS;
CREATE ROLE asql_student LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS;
CREATE SCHEMA asql_control AUTHORIZATION asql_bootstrap;
CREATE TABLE asql_control.lab (
singleton boolean PRIMARY KEY CHECK (singleton),
course_id text NOT NULL CHECK (course_id = 'advanced-sql'),
lab_id text NOT NULL,
fixture_id text NOT NULL
);
INSERT INTO asql_control.lab VALUES (true, 'advanced-sql', :'lab_id', 'harbor-small');
REVOKE ALL ON SCHEMA asql_control FROM PUBLIC;
GRANT USAGE ON SCHEMA asql_control TO asql_student;
GRANT SELECT ON asql_control.lab TO asql_student;
CREATE SCHEMA harbor AUTHORIZATION asql_owner;
SET ROLE asql_owner;
CREATE TABLE harbor.organizations (
org_id bigint PRIMARY KEY, name text NOT NULL
);
CREATE TABLE harbor.orders (
order_id bigint PRIMARY KEY,
org_id bigint NOT NULL REFERENCES harbor.organizations,
status text NOT NULL,
sales_channel text,
placed_at timestamptz NOT NULL
);
CREATE TABLE harbor.line_items (
line_id bigint PRIMARY KEY,
order_id bigint NOT NULL REFERENCES harbor.orders,
amount numeric(10,2) NOT NULL CHECK (amount >= 0)
);
CREATE TABLE harbor.refunds (
refund_id bigint PRIMARY KEY,
order_id bigint NOT NULL REFERENCES harbor.orders,
amount numeric(10,2) NOT NULL CHECK (amount >= 0)
);
CREATE TABLE harbor.fulfilment_events (
event_id bigint PRIMARY KEY,
order_id bigint NOT NULL REFERENCES harbor.orders,
event_type text NOT NULL,
observed_at timestamptz NOT NULL
);
INSERT INTO harbor.organizations VALUES (1, 'North'), (2, 'South');
INSERT INTO harbor.orders VALUES
(101, 1, 'paid', 'web', '2026-01-10 09:00:00+00'),
(102, 1, 'open', NULL, '2026-01-10 09:00:00+00'),
(103, 2, 'open', 'store', '2026-01-11 10:00:00+00'),
(104, 2, 'paid', 'partner', '2026-01-12 10:00:00+00');
INSERT INTO harbor.line_items VALUES
(11, 101, 40.00), (12, 101, 60.00), (13, 101, 20.00),
(14, 102, 30.00), (15, 104, 25.00), (16, 104, 25.00);
INSERT INTO harbor.refunds VALUES
(21, 101, 5.00), (22, 101, 15.00), (23, 104, 5.00);
INSERT INTO harbor.fulfilment_events VALUES
(31, 101, 'packed', '2026-01-10 10:00:00+00'),
(32, 101, 'shipped', '2026-01-10 11:00:00+00'),
(33, 101, 'delivered', '2026-01-11 11:00:00+00'),
(34, 102, 'packed', '2026-01-10 12:00:00+00'),
(35, 104, 'packed', '2026-01-12 12:00:00+00');
REVOKE ALL ON SCHEMA harbor FROM PUBLIC;
GRANT USAGE ON SCHEMA harbor TO asql_student;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA harbor TO asql_student;
RESET ROLE;
COMMIT;
Before BEGIN, the script refuses a different database, role/release, existing
application tables or colliding role names. Inside the transaction it creates
the protected marker, schema, tables and fixed rows. Primary/foreign keys tie
the facts together; NOT NULL prevents missing required stored values. Each
amount CHECK rejects a negative amount. The owner's privileges do not flow to
the student: grants explicitly allow schema use, table reads and ordinary
INSERT/UPDATE/DELETE, while marker access is read-only. No TRUNCATE or object
ownership is granted to the student. Later lessons examine these mechanisms
in more depth before asking for independent privilege or invariant designs.
From the host terminal in this same lab directory:
asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id="$asql_run" \
-U asql_bootstrap -d asql_lab < bootstrap.sql
The < redirection reads the local file and sends its text to psql inside the
container. The client does not need to find a host filename inside its own
filesystem. lab_id comes from the checked session record; it is not a password.
The supplied database/role arguments are fixed course targets, not placeholders.
A successful run ends with COMMIT. If it fails, inspect the first error and actual persisted state; do not keep pasting later lines or grant broader access. The bootstrap intentionally refuses a second initialization after the fixture exists. Use the bounded reset below instead of rerunning CREATE statements.
Check as the routine student role
Save this complete file as check-small.sql:
\set ON_ERROR_STOP on
\if :{?lab_id}
\else
\echo 'Stop: supply the non-secret lab_id from connection.txt.'
SELECT 1 / 0 AS guard_rejected;
\endif
SELECT current_database() = 'asql_lab'
AND current_user IN ('asql_bootstrap', 'asql_student')
AND current_setting('server_version_num') = '180006' AS target_ok
\gset
\if :target_ok
\else
\echo 'Stop: wrong database, execution role or server release.'
SELECT 1 / 0 AS guard_rejected;
\endif
SET lock_timeout = '3s';
SET statement_timeout = '15s';
SELECT COUNT(*) = 1 AS marker_ok
FROM asql_control.lab
WHERE course_id = 'advanced-sql'
AND lab_id = :'lab_id'
AND fixture_id = 'harbor-small'
\gset
\if :marker_ok
\else
\echo 'Stop: the course marker does not match this lab.'
SELECT 1 / 0 AS guard_rejected;
\endif
SELECT current_database(), session_user, current_user;
SELECT 'organizations' AS object_name, COUNT(*) AS rows FROM harbor.organizations;
SELECT 'orders' AS object_name, COUNT(*) AS rows FROM harbor.orders;
SELECT 'line_items' AS object_name, COUNT(*) AS rows FROM harbor.line_items;
SELECT 'refunds' AS object_name, COUNT(*) AS rows FROM harbor.refunds;
SELECT 'fulfilment_events' AS object_name, COUNT(*) AS rows FROM harbor.fulfilment_events;
SELECT SUM(amount) AS gross FROM harbor.line_items;
SELECT SUM(amount) AS refunded FROM harbor.refunds;
SELECT order_id, SUM(amount) AS gross FROM harbor.line_items
GROUP BY order_id ORDER BY order_id;
SELECT order_id, SUM(amount) AS refunded FROM harbor.refunds
GROUP BY order_id ORDER BY order_id;
The first checks match the marker before reading the fixture. Each subsequent statement asks one small question: actual identity, table count, overall amount or ordered per-order aggregate. Counts alone could miss wrong amounts, so inspect both. This is a baseline comparison, not an automatic proof that any future modified data is correct.
Run it from the host terminal:
asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id="$asql_run" \
-U asql_student -d asql_lab < check-small.sql
Illustrative result fields to inspect:
database / login / execution: asql_lab / asql_student / asql_student
organizations: 2 orders: 4 line_items: 6 refunds: 3 events: 5
gross: 200.00 refunded: 25.00
gross groups: 101 → 120.00; 102 → 30.00; 104 → 50.00
refund groups: 101 → 20.00; 104 → 5.00
Your lab ID varies. Explain each result against the stored inputs, including why 103 is absent from the two child-table grouping outputs. Success as the student proves these particular granted reads, not broad security or tenant isolation. A numeric constraint on stored rows does not stop an outer join from producing nulls for an absent child later.
Reset only this small baseline
Save this complete file as reset-small.sql. It deletes and recreates all rows
in the five named course tables. It does not drop the schema/roles, change
the marker, reset a production database or promise to reset future added lesson
objects. No CASCADE option broadens the named-table scope.
\set ON_ERROR_STOP on
\if :{?lab_id}
\else
\echo 'Stop: supply the non-secret lab_id from connection.txt.'
SELECT 1 / 0 AS guard_rejected;
\endif
SELECT current_database() = 'asql_lab'
AND current_user = 'asql_bootstrap'
AND current_setting('server_version_num') = '180006' AS target_ok
\gset
\if :target_ok
\else
\echo 'Stop: wrong database, execution role or server release.'
SELECT 1 / 0 AS guard_rejected;
\endif
SET lock_timeout = '3s';
SET statement_timeout = '15s';
SELECT COUNT(*) = 1 AS marker_ok
FROM asql_control.lab
WHERE course_id = 'advanced-sql'
AND lab_id = :'lab_id'
AND fixture_id = 'harbor-small'
\gset
\if :marker_ok
\else
\echo 'Stop: the course marker does not match this lab.'
SELECT 1 / 0 AS guard_rejected;
\endif
BEGIN;
TRUNCATE harbor.fulfilment_events, harbor.refunds, harbor.line_items,
harbor.orders, harbor.organizations;
INSERT INTO harbor.organizations VALUES (1, 'North'), (2, 'South');
INSERT INTO harbor.orders VALUES
(101, 1, 'paid', 'web', '2026-01-10 09:00:00+00'),
(102, 1, 'open', NULL, '2026-01-10 09:00:00+00'),
(103, 2, 'open', 'store', '2026-01-11 10:00:00+00'),
(104, 2, 'paid', 'partner', '2026-01-12 10:00:00+00');
INSERT INTO harbor.line_items VALUES
(11, 101, 40.00), (12, 101, 60.00), (13, 101, 20.00),
(14, 102, 30.00), (15, 104, 25.00), (16, 104, 25.00);
INSERT INTO harbor.refunds VALUES
(21, 101, 5.00), (22, 101, 15.00), (23, 104, 5.00);
INSERT INTO harbor.fulfilment_events VALUES
(31, 101, 'packed', '2026-01-10 10:00:00+00'),
(32, 101, 'shipped', '2026-01-10 11:00:00+00'),
(33, 101, 'delivered', '2026-01-11 11:00:00+00'),
(34, 102, 'packed', '2026-01-10 12:00:00+00'),
(35, 104, 'packed', '2026-01-12 12:00:00+00');
COMMIT;
The bootstrap-only target/marker checks run before TRUNCATE. The transaction groups the emptying and replacement inserts; if an insert fails and the client disconnects, the previous committed fixture remains. Lock/statement timeouts bound the attempt; an unexpected dependency or open transaction is a reason to inspect this owned lab, not delete another object or terminate another session.
After verifying your session context and resource labels, run:
asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id="$asql_run" \
-U asql_bootstrap -d asql_lab < reset-small.sql
asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id="$asql_run" \
-U asql_student -d asql_lab < check-small.sql
Do not infer a correct reset just from COMMIT: reconcile the same counts and amounts again. A shell error such as a missing local input file must also be resolved; it is not a reason to execute an incomplete hand-copied suffix.
Independent refusal and partial-failure checks
Try these on the owned baseline, retaining your original valid files.
- Run the reset with the deliberately wrong non-secret marker argument below. Predict whether any TRUNCATE is reached, then run the ordinary student check.
- Make a local copy named
reset-broken.sql. In that copy only, change the(11, 101, 40.00)input to(11, 101, -40.00). Run it with the correct lab ID and bootstrap role. Predict the resulting fixture after its error, then inspect it from a new student connection.
asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id=wrong-lab \
-U asql_bootstrap -d asql_lab < reset-small.sql
For the second case, after saving and checking the edited copy:
asql exec -T db psql -X -v ON_ERROR_STOP=1 -v lab_id="$asql_run" \
-U asql_bootstrap -d asql_lab < reset-broken.sql
Hint 1: Locate the marker check relative to BEGIN and TRUNCATE.
Hint 2: Locate COMMIT relative to the failing insert. Separate the client's stop from what the still-uncommitted transaction will do on disconnection.
Answer and reasoning
The wrong marker produces a stop reason and intentional guard error before the mutation transaction starts. The baseline counts and amounts stay unchanged. This is a successful refusal, despite its nonzero process status.
The broken reset passes target checks and reaches TRUNCATE inside a transaction, then the amount CHECK rejects its negative input. Stop-on-error disconnects the non-interactive client without COMMIT, rolling back the uncommitted emptying and inserts. The previously committed baseline remains: six lines, gross 200.00, three refunds totaling 25.00. Reconnect and observe it; an error message alone does not establish the post-state. Do not delete the CHECK or commit a partial repair to make the example appear successful.
If you ran this failure test from a deliberately changed valid starting state, rollback preserves that previous state, not magically the baseline. Only a successful explicit reset restores the supplied baseline.
Leave a known state for the next query
Run the original valid reset, then the student check once more. Remove only
your disposable reset-broken.sql copy; keep the three valid inputs and session
files. If you opened an interactive client with an unfinished transaction, use
ROLLBACK; and then \q in that client before proceeding.
Keep the identified lab for the next reporting lesson, or pause it using the connection lesson's owned procedure. For full removal, use that procedure's label/context checks and scoped volume deletion, verify exact-resource absence, then remove only the discarded lab's local password/workspace. Do not use DROP CASCADE, broad prune or an unrelated session termination as a reset shortcut.