Vibe Coding Advanced / Owned practice and prerequisite bridges

Understand and preserve a database snapshot

Lesson 4 of 32. Open to read. No account needed.

An AI edit can preserve every source file you expected and still damage stored data. A Git commit records selected file contents; this workbench ignores its data/ directory. Changing code back does not restore booking rows. Before a later data change, learn what the rows mean, which constraints protect them and how to verify an independent point-in-time copy.

You will preserve a source database, create a backup, reopen a separate verification copy, and test constraints and transactions on disposable copies. Keep the source, backup and actual observations as A04. No model call, cloud database or account is needed.

Read the relationships before changing a row

A table stores records with named columns; one row is one record. The app has four tables: members, equipment, slots and bookings. A booking refers to the other three using IDs rather than copying their labels.

Booking booking-a refers through memberId, equipmentId and slotId to member-a, drill-01 and slot-am. Referenced IDs are keys; status and the active equipment-slot pair also have constraints.

Follow each arrow from the booking's reference to an existing row's id. The diagram shows one example, not a rule that a member can have only one booking. Several bookings may refer to the same member or equipment. The active equipment/slot pair has its own restriction.

In src/db.ts, the supplied seed function executes this actual SQL excerpt. Read it as a schema definition; do not run it against your existing file:

CREATE TABLE bookings (
  id TEXT PRIMARY KEY,
  memberId TEXT NOT NULL REFERENCES members(id),
  equipmentId TEXT NOT NULL REFERENCES equipment(id),
  slotId TEXT NOT NULL REFERENCES slots(id),
  status TEXT NOT NULL CHECK (status IN ('active', 'cancelled'))
);

TEXT stores text values. The primary key names the booking's identity; duplicate supplied non-null IDs are rejected. A foreign key such as REFERENCES members(id) requires that a referenced member exists when foreign key enforcement is enabled. Every app/lesson database connection explicitly uses enableForeignKeyConstraints: true; do not infer that every SQLite client enables it. The foreign-key reference explains that connection-specific requirement.

NOT NULL rejects SQL's missing value NULL; it does not mean “nonempty string”. CHECK restricts status to the two supplied strings. The app supplies nonempty booking IDs. SQLite's legacy TEXT PRIMARY KEY can permit NULL unless a separate non-null rule applies, so do not treat this declaration as complete input validation. The table reference documents these distinctions; you are inspecting this schema, not silently redesigning it in this lesson.

The same seed defines this unique partial index:

CREATE UNIQUE INDEX active_equipment_slot ON bookings(equipmentId, slotId) WHERE status = 'active';

It enforces uniqueness of the pair among active rows. Two different booking IDs cannot both reserve drill-01 / slot-am while active. A cancelled row is outside this index's selected set. Neither a foreign key nor this index proves who is allowed to change a booking. They protect specific data relationships; the app's permission policy is separate. See the partial-index reference.

Give each file one job

Use the owned baseline from Lesson 1. Keep A01 and any later source/data/evidence you already produced. The reference profile is macOS arm64, Node 24.19.0, pnpm 11.25.0 and locked TypeScript 6.0.3, with the app built and its twelve baseline checks passing. The materializer needs CPython 3.12/POSIX; the author checked CPython 3.12.14. Fresh external tool acquisition and other hosts have not been verified.

The lesson-04-v1 booking-workbench.zip snapshot introduced five files: tools/database-state.mjs, tools/snapshot.mjs, tools/transaction-bridge.mjs, contracts/database-snapshot.md and blank records/database-snapshot.json. It contains 37 native files / 39 archive entries; later snapshots may extend it. Record the actual version/count. If helpers are missing, verify the current Practice files checksum and follow L01 into a new absent owned destination. Do not merge over an older learner workspace. The new helpers are ordinary JavaScript modules; no additional package or SQLite shell installation is needed.

All commands below run in the materialized native project root, containing tools/, data/ after seeding, and the built app dist/. Use only synthetic data. Open the blank A04 record and enter your workspace, payload identity and A01 location. Fill actual results, including failures; it is not a prefilled pass.

File under this project's data/Role
source-04.sqliteNew lesson source; preserve throughout
backup-04.sqliteRetained point-in-time backup; never use for write experiments
verify-04.sqliteNew copy made from the backup; reopen independently
tx-04-constraints.sqliteDisposable constraint probes, always rolled back
tx-04-fail.sqliteDisposable two-step failure experiment
tx-04-commit.sqliteSeparate disposable successful transaction

These are example new basenames, not paths to an existing personal database. If any name already exists, preserve it and use a new name consistently. The transaction tool requires a tx-04- prefix and the fresh two-active-row baseline; that prefix helps avoid mistakes but is not proof of ownership.

Stop the owned app, then make the backup

Create the new source and inspect it:

node tools/seed.mjs source-04.sqlite
node tools/snapshot.mjs inspect source-04.sqlite

The seed refuses an existing target. Inspection opens an existing regular owned file read-only, verifies schema marker 1, and records the full path, SHA-256, schema objects and all four tables ordered by ID. A logical manifest here means those schema/row observations together with integrity/foreign-key checks. It is separate from a hash of the file's bytes.

For a fresh source, the booking rows are:

IDMemberEquipmentSlotStatus
booking-amember-adrill-01slot-amactive
booking-bmember-bcamera-01slot-pmactive

In tools/database-state.mjs, the booking observation uses this actual query:

SELECT id, memberId, equipmentId, slotId, status FROM bookings ORDER BY id

SELECT reads the named columns; ORDER BY id stabilizes comparison rather than promising insertion order. The tool also requires PRAGMA integrity_check to return ok and PRAGMA foreign_key_check to return no violations. These are bounded structure/relationship checks, not proof of all business rules. Preserve the actual output and full source path in A04.

If an owned app is already using this source, stop it in its own verified terminal with Ctrl-C. For a fresh rehearsal you can start it, confirm its reported path and URL, then stop it:

node tools/start.mjs source-04.sqlite 0

Port 0 selects a free loopback port. Record the actual PID/URL/database path; do not use a remembered port. Press Ctrl-C in that terminal and wait for STOPPED: owned app closed; source and database retained before continuing. Close your own other database handles and start no other writer during this exercise. A process stop record establishes closure of that owned app, not an OS-wide census of every possible database connection.

Now create and compare a new backup:

node tools/snapshot.mjs create source-04.sqlite backup-04.sqlite
node tools/snapshot.mjs compare source-04.sqlite backup-04.sqlite

Creation uses the SQLite backup API, not a raw file copy. In tools/snapshot.mjs, after checking the source/target paths and reading the source manifest, the actual reservation/backup block is:

const reserved = openSync(target, 'wx', 0o600);
closeSync(reserved);
const pages = await backup(source, target);

Node's backup API can overwrite an existing destination. The wrapper therefore uses wx exclusive creation to reserve a new file before calling it. 0o600 gives the owner read/write permission on this POSIX profile. An existing file or symlink is refused. If backup or verification fails, the new partial target remains for diagnosis; do not reuse it as a verified backup or delete another file to force a pass. Retry only with a new target name after diagnosing the cause.

The source is opened read-only. After copying, the wrapper checks its source bytes/manifest again, reopens the target read-only, and compares logical manifests. It closes handles even on failure. It does not enumerate other processes or provide a sandbox against hostile same-user file replacement.

Expect result: verified-snapshot, sourceBytesUnchanged: true and logicalManifestEqual: true; record the actual page count and both file hashes. The compare command should report equal: true. It compares schema/ rows, not hash equality: SQLite copies can be logically equal while their file bytes differ. A hash identifies the particular file you checked; it does not establish that it opened or met application requirements.

Why not copy only the main file while writes continue? Journalling can involve additional state, including a write-ahead log. A successful filesystem copy does not establish one consistent recoverable database. The SQLite backup mechanism handles database copying through SQLite. This lesson stops the app as an additional simple practice boundary and verifies the result; it does not test concurrent backup workloads, a crash or power loss.

Reopen a copy without overwriting the source

A stopped source is backed up into a retained new file. Another new file is reopened for verification. Separate copies from the backup receive transaction experiments; rollback is distinct from restoring an old backup.

Follow the vertical connectors from source to backup to verification copy. Follow the right-hand branch from the backup to the disposable transaction copies. Each connector creates a new named file. The sequences inside the transaction box describe SQL work on those copies, not writes to the original.

Create the verification copy from the backup and compare it:

node tools/snapshot.mjs create backup-04.sqlite verify-04.sqlite
node tools/snapshot.mjs compare backup-04.sqlite verify-04.sqlite
node tools/start.mjs verify-04.sqlite 0

Match the new start record to verify-04.sqlite, then open its URL. Wait for Baseline ready. Practice member A should see one active drill/morning booking; the stored manifest contains both members' rows. Do not create/cancel anything during this read-only verification. Stop this verified listener with Ctrl-C and wait for its stop message, then inspect verify-04.sqlite again. The same two IDs, owners, equipment, slots and statuses must remain.

This establishes that the copied database can open independently through the supplied app. A successful backup call alone would not establish that. Retain the source and backup; never overwrite the source merely to demonstrate restoration. A point-in-time backup also does not merge later committed writes. The later recovery lessons develop that decision; reverting Git is not a data restore procedure for these ignored SQLite files.

Work through four constraint rejections

Create a dedicated copy, then run the provided probes:

node tools/snapshot.mjs create backup-04.sqlite tx-04-constraints.sqlite
node tools/transaction-bridge.mjs tx-04-constraints.sqlite constraints

The probe uses a bound insert: INSERT INTO bookings VALUES (?, ?, ?, ?, ?). The five ? positions receive ID, member, equipment, slot and status values; they do not become SQL syntax. Each probe begins a transaction and always rolls it back, even if an insert unexpectedly succeeds. It reports a mismatch rather than treating that unexpected success as an accepted baseline.

Probe value changeExpected rejection
Reuse booking-a as a new row IDPrimary-key uniqueness
Reference member-missingForeign-key constraint
New ID, but active drill-01 / slot-amActive equipment/slot uniqueness
New ID and status: pendingStatus CHECK

Expect four matching rejections and the same two active rows afterwards. Read the actual database error and before/after manifest. This explains the duplicate-slot protection; a different row ID does not make an occupied pair available. It does not assert that constraints enforce every permission rule.

Independent variation: what survives a two-step failure?

A transaction groups changes that you intend to commit together. BEGIN IMMEDIATE starts a write transaction, or fails if it cannot obtain the needed writer access. COMMIT keeps its changes; ROLLBACK abandons its uncommitted changes. A database connection is the open handle on which those statements run. Do not assume that every statement error automatically rolls back all earlier statements; SQLite's transaction reference describes that distinction.

Before running the following experiment, predict three observations: the two statuses after the first update inside the transaction, after the second step's failure, and after reopening the file. tools/transaction-bridge.mjs first updates booking-a to cancelled. In mode fail, its second step tries to set booking-b to pending. Its catch block contains:

transactionActiveAfterError = db.isTransaction;
if (db.isTransaction) db.exec('ROLLBACK');
result = 'rolled-back';

Read the full supplied try/catch alongside this excerpt. The tool records its intermediate rows before the second update, and explicitly rolls back if a transaction remains active after failure. Predict what would remain pending if that rollback were omitted. Do not remove it or run arbitrary SQL on the source to find out.

Now create two fresh copies and execute the failure on the first:

node tools/snapshot.mjs create backup-04.sqlite tx-04-fail.sqlite
node tools/snapshot.mjs create backup-04.sqlite tx-04-commit.sqlite
node tools/transaction-bridge.mjs tx-04-fail.sqlite fail
node tools/snapshot.mjs inspect tx-04-fail.sqlite

On the second copy, mode commit sets both statuses to cancelled using valid values. Predict its reopened rows, then run:

node tools/transaction-bridge.mjs tx-04-commit.sqlite commit
node tools/snapshot.mjs inspect tx-04-commit.sqlite
node tools/snapshot.mjs compare backup-04.sqlite tx-04-commit.sqlite

The direct SQL experiments deliberately bypass the app's policy on disposable synthetic copies. They do not implement owner cancellation or change the main application's intentionally incomplete helper. Keep src/policy.ts, the schema and baseline smoke checks unchanged.

Hint 1: A change visible on the same connection inside a transaction is not yet a committed result. Hint 2: Follow the explicit rollback in the failure path; compare it with the successful COMMIT on the other copy.

Reasoned answer after your attempt

After the first update, A is cancelled and B is active inside the transaction. The second update's CHECK error rejects pending; in this supplied case the transaction is still active. Its earlier A update has not automatically become a committed result or disappeared. The explicit ROLLBACK undoes that first update. Reopening tx-04-fail.sqlite shows both active, matching the backup. Without that rollback, earlier work could remain pending and a later commit could preserve an unintended partial operation.

On tx-04-commit.sqlite, both valid updates reach COMMIT. Reopening shows both cancelled, with IDs/owners/equipment/slots preserved. Compare should report equal: false and exit 1 because those rows differ from the backup. That difference is expected evidence. Both transaction experiments exit zero when their specified expectations are met, including the deliberate failure and rollback; an unexpected result exits nonzero. Read result, expectationMet, intermediate rows and reopened rows before judging success.

Inspect the original source and backup again. Their rows and hashes should still match your earlier A04 observations. A transaction rollback undoes that transaction's uncommitted work; it does not restore an older backup or undo already committed work. The separate copies make that boundary observable.

Diagnose and retain the evidence

Differing resultSafe next check
Existing target refusedPreserve it. Choose a new name; never overwrite it or assume a retained partial target is valid.
Missing/schema/integrity/path refusalConfirm native root, owned basename and schema 1; retain the file and failure. Do not migrate/reset as a diagnostic.
Snapshot/source verification differsStop and inspect owned writers, paths and observations. Keep source/target; retry with a new target only after diagnosis.
Constraint unexpectedly succeedsKeep the reported mismatch. Check actual schema/foreign-key-enabled connection; do not weaken expected results.
Transaction refuses its starting stateIt requires a fresh two-active-row tx-04- copy. Preserve the changed file and make another copy from the backup.
Commit copy differs from backupExpected after committing status changes; compare actual fields. This is not a failed backup.
Error/lock during a transactionPreserve output and close only your own handles. The tool rolls back any still-active transaction and closes; never stop an unrelated service to force access.

A04 is complete when source/backup/verification roles and full paths are clear, each retained file has an actual identity and manifest, the verification app reopens the expected rows, and your predicted/actual constraint and transaction outcomes include reopening. Keep the stop records and the failed attempts. Explain why a copy exit code or Git checkout is insufficient recovery evidence.

Stop only a listener whose start record you verified and wait for STOPPED. The snapshot/transaction tools close their own handles and leave no service. Retain source, backup, verification/transaction copies, native code and A01/A04 for later reasoning. Do not broadly delete data or restore over the original. No external or billable resource requires cleanup.

27 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy