Schema Designed
The SQL for the DocFlow app's tables, in the docflow schema. No service can read them.
-- DocFlow app, version 1. Schema: docflow.
-- Checked with `npm run schema:check`: runs on PGlite, and every sample row passes every constraint.
create schema if not exists docflow;
create table docflow.documents (
id uuid primary key,
owner_id uuid not null,
file_name text not null,
status text not null default 'pending_upload',
file_id uuid not null,
job_id uuid,
review_task_id uuid,
order_id uuid,
rejection_reason text,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint documents_file_name_check check (length(file_name) between 1 and 255),
constraint documents_status_check check (status in ('pending_upload', 'uploaded', 'rejected',
'extracting', 'extraction_failed', 'needs_review', 'reviewed', 'paid')),
constraint documents_parts_check check (
(status not in ('extracting', 'extraction_failed', 'needs_review', 'reviewed', 'paid') or job_id is not null)
and (status not in ('needs_review', 'reviewed', 'paid') or review_task_id is not null)
and (status <> 'paid' or order_id is not null)
),
constraint documents_rejected_check check ((status = 'rejected') = (rejection_reason is not null))
);
create index documents_owner_idx on docflow.documents (owner_id, created_at desc);
create table docflow.inbound_events (
event_id uuid primary key,
type text not null,
created_at timestamptz not null default now()
);
grant usage on schema docflow to docflow_service;
grant select, insert, update, delete on docflow.documents to docflow_service;
grant select, insert on docflow.inbound_events, docflow.audit_events to docflow_service;
Schema level: enforced by the database, whatever the code does
- A document's status always has the parts it needs (a job once extracting, a task once in review, an order once paid).
Constraints and indexes by table
docflow.documents
documents_pkey: primary key (id)documents_status_check: only the eight statusesdocuments_parts_check: a job exists from extracting on; a review task from needs_review on; an order when paiddocuments_rejected_check: rejection_reason exactly when rejecteddocuments_owner_idx: index on (owner_id, created_at desc), for the documents list
docflow.inbound_events
inbound_events_pkey: primary key (event_id)
Sample data
Common queries
The documents list
select * from docflow.documents
where owner_id = $1
order by created_at desc
limit $2;
Schema on GitHub →