22 min read · Websites and web apps

A quotation that was already sent gets its price changed later and nobody knows. An old SOP stays open on the shop floor even though a new version exists. A contract the manager signed does not match the file the sales team keeps. All three come from a document system that treats a document as one file that can be overwritten forever, instead of a set of versions where each one has a status and an owner of the decision.
This article designs a version and approval lifecycle with rules enforced in the database itself, not only in application code. It uses node:sqlite from Node 24 with TypeScript that runs directly, so nothing needs to be installed. It includes real run output and a test suite. Managers can follow the tables and explanations; engineers can run the code.
The real problem: documents that can be overwritten leave nobody knowing which version is the real one
Three hypothetical situations, not any real BT San customer project.
- A hypothetical equipment seller: a salesperson sends a quotation whose discount the manager approved, then edits the numbers in the same file to close the deal. The copy the customer holds and the copy in the system no longer match, and there is no record of who approved which set of numbers.
- A hypothetical factory: two line supervisors edit the incoming-material inspection SOP at the same time on different screens. Whoever saves last silently overwrites the other's work.
- A hypothetical contractor: a contract drafter submits it for review, then approves it personally because they hold both permissions. The legal team never saw that version.
The shared problem is that status, decision maker and content are managed separately and can each be edited in any way. The fix is to separate the document (the subject) from its versions (the content of each copy), let a version change status only along defined paths, and make an approved version data that can no longer be edited.
Concepts used, and what the reference documentation confirms
| Topic | What the documentation says | Effect on the design |
|---|---|---|
| RAISE in a trigger | The SQLite documentation says that when a trigger calls RAISE(ABORT, message), the statement stops and the application receives the SQLITE_CONSTRAINT code with the given message, and a trigger can have a WHEN condition. | Use triggers to reject UPDATE or DELETE on an approved version. It works even when someone runs SQL directly without going through the app. |
| Partial unique index | SQLite says a partial index can be UNIQUE and enforces uniqueness only for rows that match the WHERE condition. | One index enforces that a document can have only one version with status approved. |
| BEGIN IMMEDIATE | The SQLite documentation says IMMEDIATE takes the write lock as soon as BEGIN runs, and if another writer is active it fails at BEGIN with SQLITE_BUSY, which is easier to handle than failing midway. | Used for the decision step, which must record the approval and change the status together. |
| node:sqlite | The Node documentation says node:sqlite can only be loaded with the node: scheme, and the latest version of the page marks it as a release candidate (Stability 1.2), calling DatabaseSync a former alias of Database. | The example uses DatabaseSync as it runs on Node 24.21. If you upgrade Node, check the documentation page for the version you use. |
| Trigger firing order | The CREATE TRIGGER page we could read says nothing about order when several triggers exist for one event. | Do not let a rule depend on which trigger fires first. Each trigger should be able to block on its own (see the note in the testing section). |
| Separation of duties and logging | The OWASP Authorization Cheat Sheet has sections on deny by default and least privilege (but does not use the phrase separation of duties). The Logging Cheat Sheet says logs must capture when, where, who and what, and that tampering with them should be detected. | The requester and the approver are different people, and the approval record is append-only with the person and the time. |
Separation of duties (the requester must not be the approver) is a general internal-control principle that this article adopts as a business rule. It does not claim that OWASP uses this phrase in the pages we checked.
Overview of the example
The code is in the folder examples/web-document-version-approval-lifecycle/. It uses only Node 24 built-ins: no npm install and no network access. All data is hypothetical.
| File | Role |
|---|---|
| schema.ts | Tables, indexes and the triggers that enforce the rules in the database |
| docs.ts | Application functions: edit a draft with an optimistic lock, open a new draft, submit for review, decide |
| demo.ts | Walks the lifecycle from draft to approved, and tries 9 forbidden actions |
| docs.test.ts | A node:test suite with 6 tests |
| output.txt | The real output of the demo |
| README.md | How to run it and its limits |
A version has five statuses: draft, in review (in_review), approved, rejected and superseded. Only three paths are allowed: draft to in_review, in_review to approved or rejected, and approved to superseded when a new version is approved. The database rejects everything else.
Step 1: tables, and the indexes that allow only one current version
The documents table stores the subject (ID and type, such as quotation, SOP, contract or price list). The document_versions table stores the content of each version with its status, plus lock_no for detecting concurrent edits. The approvals table stores approval records separately. Two indexes matter: one allows only one approved version per document, and the other allows only one open version (draft or in review).
-- หนึ่งเอกสารมีฉบับอนุมัติปัจจุบันได้ฉบับเดียว
CREATE UNIQUE INDEX one_approved_per_document
ON document_versions(document_id) WHERE status = 'approved';
-- และมีฉบับที่ยังเปิดอยู่ (ร่างหรือรอตรวจ) ได้ฉบับเดียว กันสองคนเปิดร่างซ้อน
CREATE UNIQUE INDEX one_open_per_document
ON document_versions(document_id) WHERE status IN ('draft','in_review');The second index has a side effect you may not expect: two people cannot open a new draft from the approved version at the same time. The second person gets UNIQUE constraint failed, which the app should translate into a clear message: a draft is already open, go and edit that one.
Step 2: triggers that make approved versions uneditable, and block self-approval
The version_frozen trigger rejects any UPDATE on a version that is approved, rejected or superseded. The single exception is approved to superseded with the same content, title and version number, which is what approving a new version must do. Only drafts can be deleted.
-- ฉบับที่อนุมัติ/ปฏิเสธ/ถูกแทนที่แล้วแก้ไม่ได้ ยกเว้นขยับ approved -> superseded โดยเนื้อหาเท่าเดิม
CREATE TRIGGER version_frozen BEFORE UPDATE ON document_versions
WHEN OLD.status IN ('approved','rejected','superseded')
AND NOT (OLD.status = 'approved' AND NEW.status = 'superseded'
AND NEW.title = OLD.title AND NEW.body = OLD.body
AND NEW.version_no = OLD.version_no AND NEW.document_id = OLD.document_id)
BEGIN SELECT RAISE(ABORT, 'version is frozen: create a new draft instead'); END;Another pair of triggers guards approval records. The person who is submitted_by for a version cannot decide on it, and a decision can only be made on a version in review. Approval records cannot be edited or deleted; they can only be appended.
-- ผู้ขออนุมัติอนุมัติเองไม่ได้ และตัดสินได้เฉพาะฉบับที่รอตรวจ
CREATE TRIGGER no_self_approval BEFORE INSERT ON approvals
WHEN NEW.approver = (SELECT submitted_by FROM document_versions WHERE id = NEW.version_id)
BEGIN SELECT RAISE(ABORT, 'requester cannot decide on own version'); END;
CREATE TRIGGER decide_only_in_review BEFORE INSERT ON approvals
WHEN (SELECT status FROM document_versions WHERE id = NEW.version_id) <> 'in_review'
BEGIN SELECT RAISE(ABORT, 'version is not in review'); END;Step 3: edit drafts without overwriting each other: optimistic lock
The editDraft function takes the lock_no the editor read when they opened the screen. The UPDATE statement has the conditions that lock_no matches and the status is draft. If no row is changed, someone saved first or the version is no longer a draft, so the function reads the current state to report the cause. It never holds a row lock while the user has the form open.
// แก้ร่างด้วย optimistic lock: ต้องส่ง lock_no ที่เคยอ่านมา ถ้าไม่ตรงแปลว่ามีคนแก้ไปก่อน
export function editDraft(db: DatabaseSync, id: number, expectedLock: number, title: string, body: string): number {
const r = db.prepare(
"UPDATE document_versions SET title=?, body=?, lock_no = lock_no + 1 WHERE id=? AND lock_no=? AND status='draft'",
).run(title, body, id, expectedLock);
if (r.changes === 1) return expectedLock + 1;
const cur = getVersion(db, id);
if (cur.status !== "draft") throw new ConflictError(`not editable: status is ${cur.status}`);
throw new ConflictError(`stale edit: you read lock ${expectedLock}, current is ${cur.lock_no}`);
}Step 4: editing an approved version = opening a new draft, not overwriting
When an approved SOP needs a change, newDraftFromLatest copies the content of the latest version into the next version number as a draft. The old approved version stays the current one until the new version passes, so the shop floor never hits a period with no usable document.
// แก้ฉบับอนุมัติ = เปิดร่างใหม่ที่คัดลอกเนื้อหาจากฉบับล่าสุด ไม่เขียนทับของเดิม
export function newDraftFromLatest(db: DatabaseSync, documentId: number, user: string): number {
const last = db.prepare(
"SELECT * FROM document_versions WHERE document_id=? ORDER BY version_no DESC LIMIT 1",
).get(documentId) as Version;
const r = db.prepare(
"INSERT INTO document_versions (document_id, version_no, title, body, created_by) VALUES (?,?,?,?,?)",
).run(documentId, last.version_no + 1, last.title, last.body, user);
return Number(r.lastInsertRowid);
}Step 5: decide inside a single transaction
The decide function starts with BEGIN IMMEDIATE and records the approval (here the trigger checks that the decider is not the requester and that the version is in review). If the decision is to approve, it first moves the existing approved version to superseded, and only then promotes this version to approved. The order matters, because the unique index does not allow two approved versions even for a moment. If any step fails, everything rolls back, so there is never an approval record left behind without a status change.
// ตัดสินใจ: บันทึกใบอนุมัติและเปลี่ยนสถานะใน transaction เดียว ถ้าข้อใดล้ม ทุกอย่างย้อนกลับ
export function decide(
db: DatabaseSync, id: number, approver: string, decision: "approved" | "rejected", comment: string, now: string,
): void {
db.exec("BEGIN IMMEDIATE");
try {
db.prepare("INSERT INTO approvals (version_id, approver, decision, comment, decided_at) VALUES (?,?,?,?,?)")
.run(id, approver, decision, comment, now);
if (decision === "approved") {
const v = getVersion(db, id);
// ต้องปลดฉบับเก่าก่อน ไม่งั้น unique index จะไม่ยอมให้มีสองฉบับอนุมัติ
db.prepare("UPDATE document_versions SET status='superseded' WHERE document_id=? AND status='approved'").run(v.document_id);
}
db.prepare("UPDATE document_versions SET status=? WHERE id=? AND status='in_review'").run(decision, id);
db.exec("COMMIT");
} catch (e) { db.exec("ROLLBACK"); throw e; }
}Real run: one full lifecycle and nine forbidden cases
demo.ts creates SOP-001. Anna drafts it, edits it and submits it for review, and Bob approves it. Then it tries nine things that should not be possible. After that it opens draft v2, which is rejected, and then builds v3, which Chai approves. Run it with node --no-warnings demo.ts (Node 24.21). The names and times are hypothetical.
1) สร้าง SOP-001 ฉบับร่าง v1 โดย Anna แล้วแก้ร่าง
แก้สำเร็จ lock 1 -> 2
[blocked] Dao แก้ด้วยหน้าจอที่เปิดค้างไว้ (lock=1 แต่ปัจจุบัน 2)
-> stale edit: you read lock 1, current is 2
2) ส่งตรวจ แล้วลองอนุมัติเอง
[blocked] Anna อนุมัติฉบับที่ตัวเองส่งตรวจ
-> requester cannot decide on own version
[blocked] แก้เนื้อหาระหว่างรอตรวจ
-> content cannot change while in review
Bob อนุมัติ v1 แล้ว
v1 approved lock=2 author=anna requester=anna
3) ฉบับอนุมัติแล้วแก้หรือลบไม่ได้
[blocked] UPDATE body ของ v1 ด้วย SQL ตรง
-> version is frozen: create a new draft instead
[blocked] DELETE v1
-> only a draft can be deleted
[blocked] แก้ร่างผ่านฟังก์ชัน editDraft กับ v1
-> not editable: status is approved
[blocked] แก้ใบอนุมัติ
-> approval records are append-only
4) แก้ฉบับอนุมัติ = เปิดร่าง v2 ใหม่ (v1 ยังเป็นฉบับใช้งาน)
[blocked] Chai เปิดร่างซ้อนอีกฉบับ
-> UNIQUE constraint failed: document_versions.document_id
v2 ถูกปฏิเสธ ฉบับใช้งานยังเป็น v1
5) ทำ v3 แล้ว Chai อนุมัติ: v1 ถูกแทนที่
v1 superseded lock=2 author=anna requester=anna
v2 rejected lock=2 author=anna requester=anna
v3 approved lock=1 author=anna requester=anna
[blocked] ยัดฉบับอนุมัติที่สองด้วย SQL ตรง
-> UNIQUE constraint failed: document_versions.document_id
6) ประวัติการอนุมัติ (ใครอนุมัติอะไร เมื่อไร)
2026-03-02T09:00:00+07:00 bob approved v1 "ถูกต้องตามหน้างาน"
2026-03-03T09:00:00+07:00 bob rejected v2 "ขาดขั้นตอนของเสีย"
2026-03-04T09:00:00+07:00 chai approved v3 "เพิ่มขั้นตอนของเสียแล้ว"- Case 1: the first draft edit passes the lock and moves it from 1 to 2. Someone who left the screen open at lock 1 is rejected and told the current value is 2.
- Case 2: after Anna submits for review, she cannot approve it herself, and she cannot edit the content while it waits for review. Bob can approve. The resulting version clearly shows anna as the requester.
- Case 3: after approval, a direct UPDATE, a DELETE, a call to editDraft and an edit to the approval record are all rejected. The message comes from a trigger or from the app function.
- Case 4: draft v2 can be opened while v1 is still the current version. A second person cannot open another draft (UNIQUE constraint). Bob rejects v2, and the current version is still v1.
- Case 5: v3 passes with Chai. The table shows v1 as superseded, v2 as rejected and v3 as approved, and inserting a second approved row with direct SQL is rejected by the unique index.
- Case 6: the approval history shows the person, the result, the version, the comment and the time for all three records.
Tests
docs.test.ts runs with node --no-warnings --test docs.test.ts and gives 6 passes. It covers a stale lock, self-approval (which must roll back completely, leaving the status as in_review), approved versions that cannot be edited or deleted, a new version replacing the old one with no second open draft allowed, a second approved row rejected by the index, and a rejected version that cannot be reopened as a draft.
test("requester cannot approve own version; someone else can", () => {
const db = openDb();
const v = createDocument(db, "C-1", "contract", "t", "b", "anna");
submitForReview(db, v, "anna");
assert.throws(() => decide(db, v, "anna", "approved", "", "t"), /requester cannot/);
assert.equal(getVersion(db, v).status, "in_review"); // ย้อนกลับครบ ไม่มีสถานะค้างครึ่งทาง
decide(db, v, "bob", "approved", "", "t");
assert.equal(getVersion(db, v).status, "approved");
});The last test taught the author something while writing the example. Changing rejected to draft can be blocked by either of two triggers, and the one that fired first in the real run was invalid status transition, not the frozen trigger we expected. The documentation we could read does not specify the order, so the test accepts either message instead of depending on an order that is not guaranteed.
Using it with a real database
- Database: PostgreSQL also has partial unique indexes. Triggers are written as plpgsql functions that can RAISE EXCEPTION. The lock_no check uses the same UPDATE ... WHERE lock_no = ? pattern, and the transaction should use an isolation level suited to two approvers racing.
- Attachments: keep the real files (PDF, Word) in object storage and store the file's hash with the version. An approved version must be tied to that hash. If the file changes, the hash changes and the change is detected. Large files should be uploaded directly to storage, not through the app server.
- User identity: the example takes a name as a string. A real system must take it from a verified session and never accept the approver's name from a form.
- Multi-level approval, delegates during leave and after-the-fact investigation can all be built on the approvals table. See the articles on multi-level approval and change history linked at the end of the page.
- Thai language: store and compare text as the same UTF-8 throughout the system, and do not use a Thai title as the document ID. Use a separate alphanumeric code.
Hypothetical example: applying it to four document jobs
- Quotation: require approval only when the discount exceeds a threshold. The version sent to the customer is locked with its number, and a new price negotiation opens the next version instead of editing the one already sent.
- SOP: one current version per document. The shop floor opens only approved, and superseded is kept so you can look back at which procedure was used last month.
- Contract: the drafter, reviewer and signer are different roles. Legal decides while the version is in review, and the approval is tied to the hash of the signed file.
- Price list: it has an effective date, and a new version can be approved in advance. This example has no effective date yet, so you would add a column and change the unique index condition to match.
Common mistakes, and a checklist
- Checking the rules only in app code, so a data-fix script or someone running SQL directly can bypass them.
- Using is_current as a flag the app moves itself, which lets a race produce two current versions (let an index enforce it instead).
- Letting approved versions be edited and then logging what changed, when they should have been blocked from the start.
- Letting the requester be the approver because one role holds both permissions.
- Deleting rejected versions to keep things tidy, which erases the history.
- Using updated_at instead of lock_no to detect concurrent edits, which can miss a clash when two people save in the same second.
- Write the allowed status paths as a table and have the database enforce them.
- Test with direct SQL that an approved version cannot be edited, deleted or joined by a second approved version.
- Test two people editing a draft at the same time, and two people opening a draft at the same time.
- Approval records store the person, result, comment and time, and are append-only.
- The current version must be easier to open than old ones, and old ones must be clearly labelled as superseded.
- Rehearse recovery and re-test the triggers after every migration.
Caution: this is a learning example, not production code. The database is in memory, there is no login or permission system, it was not tested under many concurrent users, and node:sqlite is not yet a fully stable API according to its documentation. Legal requirements and document-control standards for each industry are outside the scope of this article and must be checked with a specialist in that field.
References
- SQLite — CREATE TRIGGER (RAISE, WHEN clause) (accessed 2026-11-21)
- SQLite — Partial Indexes (unique partial indexes) (accessed 2026-11-21)
- SQLite — BEGIN TRANSACTION (DEFERRED, IMMEDIATE) (accessed 2026-11-21)
- Node.js — SQLite (node:sqlite) (accessed 2026-11-21)
- OWASP — Authorization Cheat Sheet (deny by default, least privilege) (accessed 2026-11-21)
- OWASP — Logging Cheat Sheet (when, where, who, what; tamper detection) (accessed 2026-11-21)




