-- Phase 4: documents. Scans and photos of a person's papers, and a -- company's documents for the extension packs. The file itself lies -- encrypted in the files directory (VISA_FILES_DIR) as .vdoc; this row -- holds what is known about it. A document belongs to a person or to a -- company, and a person's document may belong to one of their records. CREATE TABLE documents ( id BIGSERIAL PRIMARY KEY, person_id BIGINT REFERENCES people (id), company_id BIGINT REFERENCES companies (id), kind TEXT NOT NULL, -- the record it belongs to, at most one; deleting the record keeps the -- document with the person passport_id BIGINT REFERENCES passports (id) ON DELETE SET NULL, address_id BIGINT REFERENCES addresses (id) ON DELETE SET NULL, visa_id BIGINT REFERENCES visas (id) ON DELETE SET NULL, arrival_id BIGINT REFERENCES arrivals (id) ON DELETE SET NULL, extension_id BIGINT REFERENCES extensions (id) ON DELETE SET NULL, report_id BIGINT REFERENCES ninety_day_reports (id) ON DELETE SET NULL, reentry_permit_id BIGINT REFERENCES reentry_permits (id) ON DELETE SET NULL, work_permit_id BIGINT REFERENCES work_permits (id) ON DELETE SET NULL, -- the date printed on the document: issue, certification, statement dated_on DATE, note TEXT NOT NULL DEFAULT '', file_name TEXT NOT NULL, content_type TEXT NOT NULL CHECK ( content_type IN ('application/pdf', 'image/jpeg', 'image/png', 'image/webp') ), size_bytes INTEGER NOT NULL CHECK (size_bytes > 0), -- of the file as uploaded, checked again at each download sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), uploaded_by TEXT NOT NULL, uploaded_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), CHECK ((person_id IS NULL) <> (company_id IS NULL)), CHECK ( num_nonnulls( passport_id, address_id, visa_id, arrival_id, extension_id, report_id, reentry_permit_id, work_permit_id ) <= CASE WHEN person_id IS NULL THEN 0 ELSE 1 END ) ); CREATE INDEX documents_person ON documents (person_id) WHERE person_id IS NOT NULL; CREATE INDEX documents_company ON documents (company_id) WHERE company_id IS NOT NULL; -- A company's document names its company in the audit log, and a download -- is told from a view. Adding a column or changing a constraint changes no -- row, so the append-only trigger lets it through. ALTER TABLE audit_log ADD COLUMN company_id BIGINT; ALTER TABLE audit_log DROP CONSTRAINT audit_log_action_check; ALTER TABLE audit_log ADD CONSTRAINT audit_log_action_check CHECK ( action IN ( 'view', 'create', 'update', 'delete', 'archive', 'restore', 'sign-in', 'sign-out', 'download' ) ); ALTER TABLE audit_log DROP CONSTRAINT audit_log_entity_check; ALTER TABLE audit_log ADD CONSTRAINT audit_log_entity_check CHECK ( entity IN ( 'person', 'passport', 'address', 'session', 'company', 'visa', 'arrival', 'extension', 'reentry-permit', 'report', 'work-permit', 'document' ) );