Inspection checklist app database schema

Fifteen tables. templates holds one row per template version, keyed by id and version, with sections and questions as child tables whose question ids carry across versions, so an inspection keeps the exact questions it used and a repeat failure can find the same question a month later. inspections, answers and actions carry the daily work: answers store whether they failed, actions are tied to the failed answer, and whether an action is a repeat failure is worked out, not stored.

  • 15 tables, 7 indexes
  • Verified on SQLite 3.53.4 and PostgreSQL 19.0 (PGlite 0.6.1),
  • 101 seed rows from the blueprint
  • The blueprint's test build passed 14 of 14 acceptance checks

Copy the SQLDownload SQLDownload seed data

By Sam Claassen · From the Inspections blueprint · MIT licensed · Markdown version

Inspections entity-relationship diagram

settingsidPK+ 4 more columnspeopleidPK+ 4 more columnssitesidPKmanager_id→ people+ 2 more columnsperson_sitesperson_idPK → peoplesite_idPK → sitestemplatesidPKversionPK+ 2 more columnstemplate_sectionstemplate_idPKversionPKpositionPK+ 1 more columntemplate_questionstemplate_idPKversionPKidPK+ 9 more columnsschedulesidPKsite_id→ sitesassignee_id→ people+ 6 more columnsinspectionsidPKsite_id→ sitesinspector_id→ peopleschedule_id→ schedules+ 9 more columnsanswersinspection_idPK → inspectionsquestion_idPK+ 4 more columnsanswer_photosinspection_idPKquestion_idPKpositionPK+ 1 more columnactionsidPKsite_id→ sitesassignee_id→ people+ 9 more columnsaction_photosaction_idPK → actionspositionPK+ 1 more columneventsidPKactor→ people+ 3 more columnsnotificationsidPK+ 8 more columnssettingsidPK+ 4 more columnspeopleidPK+ 4 more columnssitesidPKmanager_id→ people+ 2 more columnsperson_sitesperson_idPK → peoplesite_idPK → sitestemplatesidPKversionPK+ 2 more columnstemplate_sectionstemplate_idPKversionPKpositionPK+ 1 more columntemplate_questionstemplate_idPKversionPKidPK+ 9 more columnsschedulesidPKsite_id→ sitesassignee_id→ people+ 6 more columnsinspectionsidPKsite_id→ sitesinspector_id→ peopleschedule_id→ schedules+ 9 more columnsanswersinspection_idPK → inspectionsquestion_idPK+ 4 more columnsanswer_photosinspection_idPKquestion_idPKpositionPK+ 1 more columnactionsidPKsite_id→ sitesassignee_id→ people+ 9 more columnsaction_photosaction_idPK → actionspositionPK+ 1 more columneventsidPKactor→ people+ 3 more columnsnotificationsidPK+ 8 more columns
Each box is a table with its key columns. A line runs from a table up to a table it references, with the forked end on the side that has many rows; a dashed line is an optional reference.

Relationships

  • sites.manager_id references people.id: each sites row points to exactly one people row, and one people row can have many sites rows pointing to it.
  • person_sites.person_id references people.id: each person_sites row points to exactly one people row, and one people row can have many person_sites rows pointing to it.
  • person_sites.site_id references sites.id: each person_sites row points to exactly one sites row, and one sites row can have many person_sites rows pointing to it. On delete: cascade.
  • template_sections.template_id, version references templates.id, version: each template_sections row points to exactly one templates row, and one templates row can have many template_sections rows pointing to it.
  • template_questions.template_id, version, section_position references template_sections.template_id, version, position: each template_questions row points to exactly one template_sections row, and one template_sections row can have many template_questions rows pointing to it.
  • schedules.site_id references sites.id: each schedules row points to at most one sites row, and one sites row can have many schedules rows pointing to it. On delete: set null.
  • schedules.assignee_id references people.id: each schedules row points to at most one people row, and one people row can have many schedules rows pointing to it.
  • inspections.site_id references sites.id: each inspections row points to at most one sites row, and one sites row can have many inspections rows pointing to it. On delete: set null.
  • inspections.inspector_id references people.id: each inspections row points to at most one people row, and one people row can have many inspections rows pointing to it.
  • inspections.schedule_id references schedules.id: each inspections row points to at most one schedules row, and one schedules row can have many inspections rows pointing to it.
  • inspections.template_id, template_version references templates.id, version: each inspections row points to at most one templates row, and one templates row can have many inspections rows pointing to it.
  • answers.inspection_id references inspections.id: each answers row points to exactly one inspections row, and one inspections row can have many answers rows pointing to it.
  • answer_photos.inspection_id, question_id references answers.inspection_id, question_id: each answer_photos row points to exactly one answers row, and one answers row can have many answer_photos rows pointing to it.
  • actions.site_id references sites.id: each actions row points to at most one sites row, and one sites row can have many actions rows pointing to it. On delete: set null.
  • actions.assignee_id references people.id: each actions row points to exactly one people row, and one people row can have many actions rows pointing to it.
  • actions.inspection_id, question_id references answers.inspection_id, question_id: each actions row points to exactly one answers row, and one answers row can have many actions rows pointing to it.
  • action_photos.action_id references actions.id: each action_photos row points to exactly one actions row, and one actions row can have many action_photos rows pointing to it.
  • events.actor references people.id: each events row points to at most one people row, and one people row can have many events rows pointing to it.

Inspections tables

The schema has 15 tables. Every column below is read from the SQL file itself. Also described as: safety inspection system database design, audit checklist database tables, corrective action tracker schema.

TableImplementsWhat a row is
settingsSettingsThe single row with the company, time zone and action due days.
peoplePersonA person who signs in as admin, manager or inspector.
sitesSiteA store or site with its manager.
person_siteschild table of PersonOne site a person works at.
templatesTemplateOne version of a checklist template: draft, published or archived.
template_sectionschild table of TemplateOne section of a template version, in order.
template_questionschild table of TemplateOne question in a template version, with its kind, weight, range and flags.
schedulesScheduleA recurring inspection of a template at a site.
inspectionsInspectionOne inspection, scheduled or started by hand, with its status and score.
answersAnswerOne answer to one question of an inspection.
answer_photoschild table of AnswerOne photo attached to an answer.
actionsActionOne corrective action raised by a failed answer.
action_photoschild table of ActionOne photo of the fix when an action is closed.
eventsEventOne append-only record of a change, a job run or an export.
notificationsNotificationOne outgoing email in the outbox.

settings

The single settings row.

ColumnTypeNullDefaultKeyNotes
idINTEGERnoPrimary keyone row onlyCheck: id = 1
company_nameTEXTno
time_zoneTEXTno'America/New_York'IANA name; dates and due times are in this zone
action_due_days_highINTEGERno1days after the completion date
action_due_days_normalINTEGERno7

people

A person who signs in: admin, manager or inspector.

ColumnTypeNullDefaultKeyNotes
idTEXTnoPrimary key
nameTEXTno
emailTEXTnoUniquethe sign-in identity
roleTEXTnoCheck: role IN ('admin', 'manager', 'inspector')
activeBOOLEANno
  • App rule (R8): deactivating or demoting a site's manager needs another manager for their sites first.

sites

A store or site.

ColumnTypeNullDefaultKeyNotes
idTEXTnoPrimary key
nameTEXTno
addressTEXTyes
manager_idTEXTnoReferences people.id
  • App rule (R8): the manager is an active person with the manager role; a site with open actions can't be removed.

person_sites

One site a person works at (child table of Person.site_ids). Removing a site takes it off everyone's list.

ColumnTypeNullDefaultKeyNotes
person_idTEXTnoPrimary key (part); References people.id
site_idTEXTnoPrimary key (part); References sites.id, on delete cascade

templates

One version of a checklist template. Each version is its own row, keyed by id and version (R1).

ColumnTypeNullDefaultKeyNotes
idTEXTnoPrimary key (part)
versionINTEGERnoPrimary key (part)Check: version >= 1
nameTEXTno
statusTEXTnodraft: unpublished edit; archived: older version or retired templateCheck: status IN ('draft', 'published', 'archived')
  • Unique index templates_one_published on (id) where status = 'published'
  • Unique index templates_one_draft on (id) where status = 'draft'

template_sections

One section of a template version, in order (child table of Template.sections).

ColumnTypeNullDefaultKeyNotes
template_idTEXTnoPrimary key (part)
versionINTEGERnoPrimary key (part)
positionINTEGERnoPrimary key (part)section order
titleTEXTyesoptional; the signature sits in a final section titled "Sign-off"

template_questions

One question in a template version (child table of the section's questions).

ColumnTypeNullDefaultKeyNotes
template_idTEXTnoPrimary key (part)
versionINTEGERnoPrimary key (part)
idTEXTnoPrimary key (part)kept across versions: a repeat failure is the same question id
section_positionINTEGERno
positionINTEGERnoorder within the section
textTEXTno
kindTEXTnoCheck: kind IN ('yes_no', 'rating', 'number', 'text', 'photo', 'signature')
weightNUMERICno1points; 0 is allowedCheck: weight >= 0
minNUMERICyesnumber questions: fails below min
maxNUMERICyesnumber questions: fails above max
photo_required_on_failBOOLEANnoFALSE
high_priorityBOOLEANnoFALSEits action is due action_due_days_high days later
  • Table check: kind <> 'number' OR min IS NOT NULL OR max IS NOT NULL
  • Table check: kind = 'number' OR (min IS NULL AND max IS NULL)
  • Table check: min IS NULL OR max IS NULL OR min <= max
  • Unique index template_questions_one_signature on (template_id, version) where kind = 'signature'
  • App rule (section 5): the signature question is in a final Sign-off section and can never be not applicable.

schedules

A recurring inspection at a site. Paused, never deleted. template_id names a template, not one version, so it has no foreign key: the version is chosen when each inspection starts.

ColumnTypeNullDefaultKeyNotes
idTEXTnoPrimary key
template_idTEXTno
site_idTEXTyesReferences sites.id, on delete set nullremoving a site pauses its schedules (R8)
everyTEXTnoCheck: every IN ('daily', 'weekly', 'monthly')
weekdayINTEGERyesweekly: 1 = Monday, 7 = SundayCheck: weekday BETWEEN 1 AND 7
day_of_monthINTEGERyesmonthly: 29 to 31 fall on a shorter month's last dayCheck: day_of_month BETWEEN 1 AND 31
due_timeTEXTnoHH:MM company time, kept across daylight-saving changesCheck: due_time LIKE '__:__'
assignee_idTEXTyesReferences people.idempty when the assignee is inactive
activeBOOLEANnofalse = paused
  • Table check: (every = 'daily' AND weekday IS NULL AND day_of_month IS NULL) OR (every = 'weekly' AND weekday IS NOT NULL AND day_of_month IS NULL) OR (every = 'monthly' AND day_of_month IS NOT NULL AND weekday IS NULL)

inspections

One inspection: scheduled (created by the hourly job) or started by hand.

ColumnTypeNullDefaultKeyNotes
idTEXTnoPrimary key
numberTEXTnoUniqueI-0001Check: number LIKE 'I-%'
template_idTEXTno
template_versionINTEGERyesthe version published when it was started; empty while due
site_idTEXTyesReferences sites.id, on delete set nullempty once the site is removed ("Removed site")
inspector_idTEXTyesReferences people.idwhoever started it; while due, the schedule's assignee or empty
schedule_idTEXTyesReferences schedules.idempty for inspections started by hand
due_atTIMESTAMPyes
started_atTIMESTAMPyes
completed_atTIMESTAMPyes
statusTEXTnoCheck: status IN ('due', 'in_progress', 'completed', 'missed', 'site_closed')
score_percentINTEGERyesempty when every scorable question is not applicableCheck: score_percent BETWEEN 0 AND 100
signatureTEXTyesthe signer's typed name (an optional drawing is stored as a file reference)
  • Table check: (status = 'completed' AND completed_at IS NOT NULL AND started_at IS NOT NULL AND template_version IS NOT NULL) OR (status <> 'completed' AND completed_at IS NULL AND score_percent IS NULL)
  • Table check: status <> 'due' OR started_at IS NULL
  • Table check: status <> 'in_progress' OR started_at IS NOT NULL
  • Table check: status NOT IN ('missed', 'site_closed') OR schedule_id IS NOT NULL
  • Index inspections_site_idx on (site_id, template_id, completed_at)
  • Index inspections_due_idx on (status, due_at)
  • App rule (section 7): a due scheduled inspection not completed by due_at plus 12 hours becomes missed; hand-started ones never are.
  • App rule (R2): completing needs every question answered or not applicable, required photos and the signature; completed inspections are read-only.

answers

One answer to one question of an inspection.

ColumnTypeNullDefaultKeyNotes
inspection_idTEXTnoPrimary key (part); References inspections.id
question_idTEXTnoPrimary key (part)template_questions.id in the inspection's template version (app rule: no foreign key, the version lives on the inspection)
valueTEXTyesyes_no: 'yes' or 'no'; rating: '1' to '5'; number: decimal text; text: the text; empty for photo and signature
not_applicableBOOLEANnoFALSE
failedBOOLEANnoFALSEcalculated by section 6 when saved: No, a rating of 2 or below, or a number outside min to max
noteTEXTyes
  • Table check: NOT (not_applicable = TRUE AND failed = TRUE)

answer_photos

One photo attached to an answer (child table of Answer.photos). Stored privately.

ColumnTypeNullDefaultKeyNotes
inspection_idTEXTnoPrimary key (part)
question_idTEXTnoPrimary key (part)
positionINTEGERnoPrimary key (part)
file_keyTEXTnoreference to the private file (up to 10 MB), served only to people who can see the inspection

actions

One corrective action, created for every failed answer when its inspection is completed.

ColumnTypeNullDefaultKeyNotes
idTEXTnoPrimary key
numberTEXTnoUniqueA-0001Check: number LIKE 'A-%'
inspection_idTEXTno
question_idTEXTno
site_idTEXTyesReferences sites.id, on delete set null
titleTEXTnothe question text
priorityTEXTnoCheck: priority IN ('high', 'normal')
assignee_idTEXTnoReferences people.idthe site's manager at completion; reassignable to an active person at the site
due_onDATEno
statusTEXTnoCheck: status IN ('open', 'done')
done_noteTEXTyesCheck: LENGTH(done_note) BETWEEN 1 AND 2000
done_atTIMESTAMPyes
  • Table check: (status = 'done' AND done_note IS NOT NULL AND done_at IS NOT NULL) OR (status = 'open' AND done_note IS NULL AND done_at IS NULL)
  • Index actions_open_idx on (status, site_id, due_on)
  • App rule (section 6): a repeat failure is worked out, not stored: the same question id failed at the same site in the previous completed inspection from the same template.
  • App rule (R4): overdue from the day after due_on in company time.

action_photos

One photo of the fix (child table of Action.done_photos); required for high-priority actions, up to 5.

ColumnTypeNullDefaultKeyNotes
action_idTEXTnoPrimary key (part); References actions.id
positionINTEGERnoPrimary key (part)Check: position BETWEEN 1 AND 5
file_keyTEXTnoreference to the private file, up to 10 MB

events

One append-only event: every change, each job run and each export. Never edited or deleted (R10).

ColumnTypeNullDefaultKeyNotes
idTEXTnoPrimary key
atTIMESTAMPno
actorTEXTyesReferences people.idempty for the hourly job
typeTEXTno
dataTEXTyesJSON text, e.g. what a job run created, marked missed and emailed
  • Index events_at_idx on (at)

notifications

One outgoing email in the outbox, listed newest first by number.

ColumnTypeNullDefaultKeyNotes
idTEXTnoPrimary key
numberTEXTnoUniqueN-0001Check: number LIKE 'N-%'
created_atTIMESTAMPno
kindTEXTnoaction created, due today, overdue, inspection missed or repeat failure (section 10)
to_emailTEXTno
subjectTEXTno
bodyTEXTno
statusTEXTnologged = no email provider configuredCheck: status IN ('queued', 'sent', 'failed', 'logged')
errorTEXTyes

The SQL

The whole schema in one file. It runs top to bottom, unmodified, on SQLite and PostgreSQL. Download inspections.sql or copy it from here.

inspections.sql
-- Inspections database schema
-- Source: https://personalsoftwarefactory.com/blueprints/inspections (data model, section 5 of the blueprint)
-- Verified on SQLite 3.53.4 and PostgreSQL 19.0 (PGlite). All timestamps are UTC.
-- License: MIT. Free to copy and adapt.

-- The single settings row.
CREATE TABLE settings (
  id INTEGER PRIMARY KEY CHECK (id = 1), -- one row only
  company_name TEXT NOT NULL,
  time_zone TEXT NOT NULL DEFAULT 'America/New_York', -- IANA name; dates and due times are in this zone
  action_due_days_high INTEGER NOT NULL DEFAULT 1, -- days after the completion date
  action_due_days_normal INTEGER NOT NULL DEFAULT 7
);

-- A person who signs in: admin, manager or inspector.
-- App rule (R8): deactivating or demoting a site's manager needs another manager for their sites first.
CREATE TABLE people (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT NOT NULL UNIQUE, -- the sign-in identity
  role TEXT NOT NULL CHECK (role IN ('admin', 'manager', 'inspector')),
  active BOOLEAN NOT NULL
);

-- A store or site.
-- App rule (R8): the manager is an active person with the manager role; a site with open actions can't be removed.
CREATE TABLE sites (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  address TEXT,
  manager_id TEXT NOT NULL REFERENCES people(id)
);

-- One site a person works at (child table of Person.site_ids). Removing a site takes it off everyone's list.
CREATE TABLE person_sites (
  person_id TEXT NOT NULL REFERENCES people(id),
  site_id TEXT NOT NULL REFERENCES sites(id) ON DELETE CASCADE,
  PRIMARY KEY (person_id, site_id)
);

-- One version of a checklist template. Each version is its own row, keyed by id and version (R1).
CREATE TABLE templates (
  id TEXT NOT NULL,
  version INTEGER NOT NULL CHECK (version >= 1),
  name TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('draft', 'published', 'archived')), -- draft: unpublished edit; archived: older version or retired template
  PRIMARY KEY (id, version)
);
CREATE UNIQUE INDEX templates_one_published ON templates (id) WHERE status = 'published'; -- one current version per template
CREATE UNIQUE INDEX templates_one_draft ON templates (id) WHERE status = 'draft';

-- One section of a template version, in order (child table of Template.sections).
CREATE TABLE template_sections (
  template_id TEXT NOT NULL,
  version INTEGER NOT NULL,
  position INTEGER NOT NULL, -- section order
  title TEXT, -- optional; the signature sits in a final section titled "Sign-off"
  PRIMARY KEY (template_id, version, position),
  FOREIGN KEY (template_id, version) REFERENCES templates(id, version)
);

-- One question in a template version (child table of the section's questions).
-- App rule (section 5): the signature question is in a final Sign-off section and can never be not applicable.
CREATE TABLE template_questions (
  template_id TEXT NOT NULL,
  version INTEGER NOT NULL,
  id TEXT NOT NULL, -- kept across versions: a repeat failure is the same question id
  section_position INTEGER NOT NULL,
  position INTEGER NOT NULL, -- order within the section
  text TEXT NOT NULL,
  kind TEXT NOT NULL CHECK (kind IN ('yes_no', 'rating', 'number', 'text', 'photo', 'signature')),
  weight NUMERIC NOT NULL DEFAULT 1 CHECK (weight >= 0), -- points; 0 is allowed
  min NUMERIC, -- number questions: fails below min
  max NUMERIC, -- number questions: fails above max
  photo_required_on_fail BOOLEAN NOT NULL DEFAULT FALSE,
  high_priority BOOLEAN NOT NULL DEFAULT FALSE, -- its action is due action_due_days_high days later
  PRIMARY KEY (template_id, version, id),
  FOREIGN KEY (template_id, version, section_position) REFERENCES template_sections(template_id, version, position),
  CHECK (kind <> 'number' OR min IS NOT NULL OR max IS NOT NULL), -- a number question needs a min, a max or both
  CHECK (kind = 'number' OR (min IS NULL AND max IS NULL)),
  CHECK (min IS NULL OR max IS NULL OR min <= max)
);
CREATE UNIQUE INDEX template_questions_one_signature ON template_questions (template_id, version) WHERE kind = 'signature'; -- at most one per template

-- A recurring inspection at a site. Paused, never deleted.
-- template_id names a template, not one version, so it has no foreign key: the version is chosen when each inspection starts.
CREATE TABLE schedules (
  id TEXT PRIMARY KEY,
  template_id TEXT NOT NULL,
  site_id TEXT REFERENCES sites(id) ON DELETE SET NULL, -- removing a site pauses its schedules (R8)
  every TEXT NOT NULL CHECK (every IN ('daily', 'weekly', 'monthly')),
  weekday INTEGER CHECK (weekday BETWEEN 1 AND 7), -- weekly: 1 = Monday, 7 = Sunday
  day_of_month INTEGER CHECK (day_of_month BETWEEN 1 AND 31), -- monthly: 29 to 31 fall on a shorter month's last day
  due_time TEXT NOT NULL CHECK (due_time LIKE '__:__'), -- HH:MM company time, kept across daylight-saving changes
  assignee_id TEXT REFERENCES people(id), -- empty when the assignee is inactive
  active BOOLEAN NOT NULL, -- false = paused
  CHECK ((every = 'daily' AND weekday IS NULL AND day_of_month IS NULL) OR (every = 'weekly' AND weekday IS NOT NULL AND day_of_month IS NULL) OR (every = 'monthly' AND day_of_month IS NOT NULL AND weekday IS NULL))
);

-- One inspection: scheduled (created by the hourly job) or started by hand.
-- App rule (section 7): a due scheduled inspection not completed by due_at plus 12 hours becomes missed; hand-started ones never are.
-- App rule (R2): completing needs every question answered or not applicable, required photos and the signature; completed inspections are read-only.
CREATE TABLE inspections (
  id TEXT PRIMARY KEY,
  number TEXT NOT NULL UNIQUE CHECK (number LIKE 'I-%'), -- I-0001
  template_id TEXT NOT NULL,
  template_version INTEGER, -- the version published when it was started; empty while due
  site_id TEXT REFERENCES sites(id) ON DELETE SET NULL, -- empty once the site is removed ("Removed site")
  inspector_id TEXT REFERENCES people(id), -- whoever started it; while due, the schedule's assignee or empty
  schedule_id TEXT REFERENCES schedules(id), -- empty for inspections started by hand
  due_at TIMESTAMP,
  started_at TIMESTAMP,
  completed_at TIMESTAMP,
  status TEXT NOT NULL CHECK (status IN ('due', 'in_progress', 'completed', 'missed', 'site_closed')),
  score_percent INTEGER CHECK (score_percent BETWEEN 0 AND 100), -- empty when every scorable question is not applicable
  signature TEXT, -- the signer's typed name (an optional drawing is stored as a file reference)
  FOREIGN KEY (template_id, template_version) REFERENCES templates(id, version),
  CHECK ((status = 'completed' AND completed_at IS NOT NULL AND started_at IS NOT NULL AND template_version IS NOT NULL) OR (status <> 'completed' AND completed_at IS NULL AND score_percent IS NULL)),
  CHECK (status <> 'due' OR started_at IS NULL),
  CHECK (status <> 'in_progress' OR started_at IS NOT NULL),
  CHECK (status NOT IN ('missed', 'site_closed') OR schedule_id IS NOT NULL) -- only scheduled inspections are missed or site closed
);
CREATE INDEX inspections_site_idx ON inspections (site_id, template_id, completed_at);
CREATE INDEX inspections_due_idx ON inspections (status, due_at);

-- One answer to one question of an inspection.
CREATE TABLE answers (
  inspection_id TEXT NOT NULL REFERENCES inspections(id),
  question_id TEXT NOT NULL, -- template_questions.id in the inspection's template version (app rule: no foreign key, the version lives on the inspection)
  value TEXT, -- yes_no: 'yes' or 'no'; rating: '1' to '5'; number: decimal text; text: the text; empty for photo and signature
  not_applicable BOOLEAN NOT NULL DEFAULT FALSE,
  failed BOOLEAN NOT NULL DEFAULT FALSE, -- calculated by section 6 when saved: No, a rating of 2 or below, or a number outside min to max
  note TEXT,
  PRIMARY KEY (inspection_id, question_id),
  CHECK (NOT (not_applicable = TRUE AND failed = TRUE))
);

-- One photo attached to an answer (child table of Answer.photos). Stored privately.
CREATE TABLE answer_photos (
  inspection_id TEXT NOT NULL,
  question_id TEXT NOT NULL,
  position INTEGER NOT NULL,
  file_key TEXT NOT NULL, -- reference to the private file (up to 10 MB), served only to people who can see the inspection
  PRIMARY KEY (inspection_id, question_id, position),
  FOREIGN KEY (inspection_id, question_id) REFERENCES answers(inspection_id, question_id)
);

-- One corrective action, created for every failed answer when its inspection is completed.
-- App rule (section 6): a repeat failure is worked out, not stored: the same question id failed at the same site in the previous completed inspection from the same template.
-- App rule (R4): overdue from the day after due_on in company time.
CREATE TABLE actions (
  id TEXT PRIMARY KEY,
  number TEXT NOT NULL UNIQUE CHECK (number LIKE 'A-%'), -- A-0001
  inspection_id TEXT NOT NULL,
  question_id TEXT NOT NULL,
  site_id TEXT REFERENCES sites(id) ON DELETE SET NULL,
  title TEXT NOT NULL, -- the question text
  priority TEXT NOT NULL CHECK (priority IN ('high', 'normal')),
  assignee_id TEXT NOT NULL REFERENCES people(id), -- the site's manager at completion; reassignable to an active person at the site
  due_on DATE NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('open', 'done')),
  done_note TEXT CHECK (LENGTH(done_note) BETWEEN 1 AND 2000),
  done_at TIMESTAMP,
  FOREIGN KEY (inspection_id, question_id) REFERENCES answers(inspection_id, question_id),
  CHECK ((status = 'done' AND done_note IS NOT NULL AND done_at IS NOT NULL) OR (status = 'open' AND done_note IS NULL AND done_at IS NULL))
);
CREATE INDEX actions_open_idx ON actions (status, site_id, due_on);

-- One photo of the fix (child table of Action.done_photos); required for high-priority actions, up to 5.
CREATE TABLE action_photos (
  action_id TEXT NOT NULL REFERENCES actions(id),
  position INTEGER NOT NULL CHECK (position BETWEEN 1 AND 5),
  file_key TEXT NOT NULL, -- reference to the private file, up to 10 MB
  PRIMARY KEY (action_id, position)
);

-- One append-only event: every change, each job run and each export. Never edited or deleted (R10).
CREATE TABLE events (
  id TEXT PRIMARY KEY,
  at TIMESTAMP NOT NULL,
  actor TEXT REFERENCES people(id), -- empty for the hourly job
  type TEXT NOT NULL,
  data TEXT -- JSON text, e.g. what a job run created, marked missed and emailed
);
CREATE INDEX events_at_idx ON events (at);

-- One outgoing email in the outbox, listed newest first by number.
CREATE TABLE notifications (
  id TEXT PRIMARY KEY,
  number TEXT NOT NULL UNIQUE CHECK (number LIKE 'N-%'), -- N-0001
  created_at TIMESTAMP NOT NULL,
  kind TEXT NOT NULL, -- action created, due today, overdue, inspection missed or repeat failure (section 10)
  to_email TEXT NOT NULL,
  subject TEXT NOT NULL,
  body TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('queued', 'sent', 'failed', 'logged')), -- logged = no email provider configured
  error TEXT
);

Seed data

Loads the configuration from section 14: the settings row, 4 people with 5 site assignments, 3 sites, both templates (the audit's archived versions 1 and 2 and published version 3, and the daily checklist) with 12 sections and 66 questions, and 6 schedules. Left out: the inspection history (the daily checklists, the October audits I-0040 to I-0042 and actions A-0030 to A-0032), because the spec gives no completion, start or done times, no answer values for the daily checklists and no completion date for the Harbor and Hilltop audits. The spec gives no text for the signature question, so it is "Signature", and no section title for the daily checklist, so that section has none.

Download inspections-seed.sql (101 rows). It loads with foreign keys enforced on both engines.

Load it

SQLite, into a new file:

sqlite3
curl -s https://personalsoftwarefactory.com/schemas/inspections.sql https://personalsoftwarefactory.com/schemas/inspections-seed.sql | sqlite3 inspections.db

PostgreSQL, into a new database:

psql
createdb inspections && curl -s https://personalsoftwarefactory.com/schemas/inspections.sql https://personalsoftwarefactory.com/schemas/inspections-seed.sql | psql -v ON_ERROR_STOP=1 inspections

SQLite only enforces foreign keys when the connection asks for it: run PRAGMA foreign_keys = ON; when your app opens the database.

Design decisions

Each template version is its own row

From the build test · field report

Section 5 keys templates by id and version, and R1 says inspections keep the version they used. templates has the primary key (id, version), sections and questions hang off that pair, and partial unique indexes allow one published and one draft version per template. The build test found that template versions had no stated storage; this is the storage the spec now names.

Question ids carry across versions

From the build test · field report

A repeat failure is the same question id failing at the same site in the previous completed inspection from the same template, any version (section 6). template_questions is keyed by (template_id, version, id), so Fire exit clear has the same id in versions 1, 2 and 3 even though version 3 made it high priority. The build test found the spec never said whether a question keeps its identity across versions; it does.

Lists are child tables

Template.sections, Person.site_ids, Answer.photos and Action.done_photos are lists in the spec. Repeat failures, visibility and the Sites screen all filter on them, so each is a child table rather than JSON text: template_sections, template_questions, person_sites, answer_photos and action_photos (at most 5 positions, R4).

Actions point at the failed answer

From the build test · field report

Every failed answer creates one action when the inspection is completed (section 6), and the same question failing twice in one inspection makes two actions. actions references answers by (inspection_id, question_id), so an action can't exist without the answer that raised it. Whether it is a repeat failure is not stored, as section 5 says; the build test found Action had no field for it and the spec now says to work it out wherever it is shown.

Status rules that fit one row are CHECKs

From the build test · field report

A completed inspection has completed_at, started_at and a template version; nothing else has a score; due inspections have not started; only scheduled inspections can be missed or site closed (section 7 and section 13). A done action has a note and a time. Schedules need exactly the field their cadence uses: a weekday for weekly, a day of the month for monthly. The build test found site closed had no status in the data model; Inspection.status now includes site_closed.

Removing a site keeps its history

From the build test · field report

R8 says removing a site keeps its past inspections, shown as "Removed site", pauses its schedules and takes it off everyone's site list. The data model has no removed flag, so this schema reads removal as a delete: person_sites rows cascade away, and inspections, actions and schedules keep their rows with site_id set to NULL. The app pauses those schedules in the same transaction. The build test found R8 didn't say what removing a site does besides needing no open actions.

Example queries

The queries behind the tool's main screens. Each returned the same rows on both engines against the seed data.

Current template versions and points possible

SQL
SELECT t.name, t.version, COUNT(q.id) AS questions, SUM(CASE WHEN q.kind IN ('yes_no', 'rating', 'number') THEN q.weight ELSE 0 END) AS points_possible FROM templates t JOIN template_questions q ON q.template_id = t.id AND q.version = t.version WHERE t.status = 'published' GROUP BY t.id, t.name, t.version ORDER BY t.name;

On the seed data: 2 rows, Daily opening checklist version 1 with 4 questions and 4 points, Monthly store audit version 3 with 21 questions and 20 points.

One question across versions

SQL
SELECT t.version, t.status, q.text, CASE WHEN q.high_priority = TRUE THEN 'high' ELSE 'normal' END AS priority, CASE WHEN q.photo_required_on_fail = TRUE THEN 'yes' ELSE 'no' END AS photo_on_fail FROM template_questions q JOIN templates t ON t.id = q.template_id AND t.version = q.version WHERE q.template_id = 'template_store_audit' AND q.id = 'fire_exit_clear' ORDER BY t.version;

On the seed data: 3 rows; Fire exit clear is high priority with a photo required only in version 3, the published one.

Schedules screen

SQL
SELECT t.name AS template, s.name AS site, sc.every, sc.day_of_month, sc.due_time, p.name AS assignee FROM schedules sc JOIN templates t ON t.id = sc.template_id AND t.status = 'published' LEFT JOIN sites s ON s.id = sc.site_id LEFT JOIN people p ON p.id = sc.assignee_id WHERE sc.active = TRUE ORDER BY t.name, s.name;

On the seed data: 6 rows, for example Monthly store audit at Riverside on day 6 at 17:00, assigned to Luis Ortega.

Who works at each site

SQL
SELECT s.name AS site, m.name AS manager, COUNT(ps.person_id) AS people_assigned FROM sites s JOIN people m ON m.id = s.manager_id LEFT JOIN person_sites ps ON ps.site_id = s.id GROUP BY s.id, s.name, m.name ORDER BY s.name;

On the seed data: 3 rows, Harbor (Amy Chen, 2 people), Hilltop (Amy Chen, 1) and Riverside (Luis Ortega, 2).

Inspection screen questions

SQL
SELECT sec.title AS section, q.position, q.text, q.kind, q.min, q.max, CASE WHEN q.high_priority = TRUE THEN 'high' ELSE 'normal' END AS priority FROM template_questions q JOIN template_sections sec ON sec.template_id = q.template_id AND sec.version = q.version AND sec.position = q.section_position WHERE q.template_id = 'template_opening_checklist' AND q.version = 1 ORDER BY sec.position, q.position;

On the seed data: 4 rows for the Daily opening checklist; Fridge temperature is a high-priority number question from 0 to 5.

What was not tested

  • MySQL, MariaDB, SQL Server and Oracle. The file avoids engine-specific syntax, but it was not run on them.
  • Other versions of SQLite and PostgreSQL than the two named above.
  • PostgreSQL as a server. The PostgreSQL run used PGlite, which is PostgreSQL compiled to run in-process.
  • Production load. The check loads the seed rows and runs the example queries; it says nothing about performance with real volumes.
  • Migrations. This is a schema for a new database, not a path from an existing one.

The blueprint this schema comes from

Tables are the easy half. This schema is section 5 of the Inspections blueprint, a free spec that also has the business rules, the screens, 4 phased build prompts and 14 acceptance checks for building the whole tool with an AI app builder. We built it from those prompts and the result passed 14 of 14 acceptance checks in a browser.

Follow new blueprints

Every new blueprint and build test appears in the feed and in the public GitHub repository. No account, no email list.