NGU-Web/server/src/migrations/023_schema.sql
Zaldimmar 5274e09571 Clean up code found in the audit
- Replace every em-dash in src and server/src with a colon, comma or hyphen
- Give every relative import its file extension (.jsx imports of .tsx fixed)
- Delete old-historyMock.ts, unused exports, unused CSS utilities, the
  unused @ alias and the fallback option nothing passed
- One copy each of initials, capitalize, byName and the server's marks()
- Move the organization, chapter and event hooks from src/data to src/lib
- Schema sync always throws on a mismatch (strict was never turned off)
- Replace the placeholder README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 22:02:03 -05:00

1236 lines
53 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- ═══════════════════════════════════════════════════════════════
-- 023 SCHEMA
--
-- The whole database in one file: what migrations 001–023 built,
-- consolidated. A fresh database runs this and lands at v23. A
-- database already at v23 skips it. One partway (v1–v22) has to be
-- brought to v23 by a release from before the consolidation first;
-- migrate() refuses to run this file over it (see db.js).
--
-- The history of how each table got here is in git: every earlier
-- migration explained itself, and the reasoning that still applies
-- is kept below, next to what it explains.
--
-- Conventions:
--
-- STRICT every table but meta, so a column declared TEXT
-- refuses an integer rather than quietly storing one.
-- Worth it when the writer is a web form.
-- Booleans INTEGER with CHECK (x IN (0, 1)).
-- Dates TEXT, 'YYYY-MM-DD'; timestamps 'YYYY-MM-DD HH:MM:SS'.
-- Slugs text primary keys on anything with a URL. Immutable:
-- polymorphic children (content_blocks, links,
-- timeline_entries) reference their owner by free-text
-- id, so renaming one would orphan them.
-- updated_at kept current by a *_touch trigger, and compared by
-- the admin engine on save so two editors can't silently
-- overwrite each other.
--
-- Order: tables with their indexes, then views, then seed rows, then
-- triggers. Triggers go last because the migration runner may drop
-- statements that follow a BEGIN...END body.
-- ═══════════════════════════════════════════════════════════════
-- ── Meta ────────────────────────────────────────────────────────
-- Key/value notes about the database itself. Not STRICT: it
-- predates the convention and holds nothing typed.
CREATE TABLE meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
-- ═══════════════════════════════════════════════════════════════
-- ORGANIZATIONS
-- ═══════════════════════════════════════════════════════════════
--
-- Regions, chapters, partners and NGU itself. They differ in a
-- handful of fields, which live in side tables keyed by the same id
-- (regions, chapters), so everything that points at an organization
-- gets one real foreign key instead of a type/id pair SQLite can't
-- check. Partners get no side table: a table holding nothing but a
-- primary key is a place for confusion rather than data.
--
-- location_label is the display override for what the structured
-- fields can't express: "Online", "Various venues", "Unity Village,
-- MO". Read it first, fall back to composing from the parts.
--
-- in_timeline drives the admin's "put this on the history page"
-- checkbox: ticked, the engine upserts a timeline_entries row;
-- unticked, it deletes it.
CREATE TABLE organizations (
id TEXT PRIMARY KEY, -- slug: 'northwest', 'lynnwood'
kind TEXT NOT NULL
CHECK (kind IN ('national', 'region', 'chapter', 'partner')),
name TEXT NOT NULL,
short_name TEXT,
tagline TEXT, -- one line, for the card
color TEXT,
logo TEXT, -- filename in public/org-logos/
venue TEXT,
address TEXT,
locality TEXT,
state_code TEXT, -- US only
country TEXT NOT NULL DEFAULT 'US',
location_label TEXT,
latitude REAL,
longitude REAL,
is_online INTEGER NOT NULL DEFAULT 0 CHECK (is_online IN (0, 1)),
is_published INTEGER NOT NULL DEFAULT 1 CHECK (is_published IN (0, 1)),
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
in_timeline INTEGER NOT NULL DEFAULT 0 CHECK (in_timeline IN (0, 1))
) STRICT;
CREATE INDEX organizations_kind_idx ON organizations (kind, is_published, sort_order);
CREATE INDEX organizations_state_idx ON organizations (state_code);
CREATE TABLE regions (
id TEXT PRIMARY KEY REFERENCES organizations (id) ON DELETE CASCADE,
scope TEXT NOT NULL
CHECK (scope IN ('domestic', 'international', 'virtual')),
map_note TEXT
) STRICT;
-- Which map areas a region covers, and how much of each.
--
-- area_code is a plain string matched at render time against the
-- keys in mapGrid.ts. No foreign key, because the thing it points
-- at isn't in this database. An unrecognised code paints nothing,
-- which is how Africa and the UK exist as regions with no tile.
--
-- A region owning a whole area has share 1.0 and no edge. A shared
-- area gets one row per region, each naming its own slice, so
-- there's no primary and secondary to keep straight.
CREATE TABLE region_areas (
region_id TEXT NOT NULL REFERENCES regions (id) ON DELETE CASCADE,
area_code TEXT NOT NULL, -- 'WA', 'CA', 'CANADA'
share REAL NOT NULL DEFAULT 1.0 CHECK (share > 0 AND share <= 1),
edge TEXT CHECK (edge IN ('top', 'bottom')),
note TEXT, -- 'north', 'Salt Lake City area'
PRIMARY KEY (region_id, area_code)
) STRICT;
CREATE INDEX region_areas_area_idx ON region_areas (area_code);
-- region_id is stored rather than derived from the state; deriving
-- it is what forced per-chapter overrides in split states. No
-- `leads` column: who runs a chapter is an affiliation, exactly as
-- it is for every other organization.
CREATE TABLE chapters (
id TEXT PRIMARY KEY REFERENCES organizations (id) ON DELETE CASCADE,
region_id TEXT REFERENCES regions (id) ON DELETE SET NULL,
meets TEXT, -- '2nd Sundays, 6:00pm'
started TEXT -- 'Since 2021'
) STRICT;
CREATE INDEX chapters_region_idx ON chapters (region_id);
-- ═══════════════════════════════════════════════════════════════
-- EVENTS
-- ═══════════════════════════════════════════════════════════════
-- Whose gathering an event is: national, regional, partner, local,
-- international, other. A table rather than a CHECK because
-- Retreats.tsx keys presentation (title, accent, background) on the
-- id, so an unrecognised value would make an event vanish from the
-- page with no error; the foreign key stops that. `name` is the
-- admin dropdown's label. sort_order is scope order, widest first,
-- in gaps of ten so one can be slotted in without renumbering.
CREATE TABLE event_scopes (
id TEXT PRIMARY KEY, -- 'national', 'regional', 'partner'
name TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0
) STRICT;
-- Dates are stored three ways on purpose:
--
-- starts_on / ends_on ISO dates, nullable. What sorting and the
-- upcoming/past split run on.
-- date_label what the card shows. Real data includes
-- "March/April 2026", which no date type
-- holds and no formatter should reproduce.
-- status an override. Null derives from ends_on
-- (effective_status in v_events), so there's
-- no flag to remember to flip.
--
-- event_type is what kind of gathering it is, orthogonal to
-- scope_id: a region can run a class, a partner can run a retreat.
-- A CHECK rather than a table because a type carries no
-- presentation: an unknown value renders as its own name rather
-- than disappearing. The DEFAULT is also what lets the admin clear
-- the field: coerceValue omits an empty NOT NULL column rather than
-- writing NULL into it.
--
-- A repeating event (a weekly class, a monthly meeting) is still
-- one row. is_series says the dates repeat; the series_ columns say
-- how. Occurrences are never stored: they're a pure function of
-- these columns plus starts_on and ends_on, worked out by the site
-- (src/lib/eventSeries.ts).
--
-- starts_on the first meeting, and the anchor: which week
-- an every-other-week series is "on", which day
-- of the month a monthly one keeps, and the
-- weekday used when none is ticked
-- ends_on when set, the last day it can meet, which
-- also keeps effective_status right
-- series_count when set, stops it after that many meetings,
-- whichever comes first
-- series_frequency weekly on the ticked weekdays,
-- every N weeks
-- monthly_date on starts_on's day of the
-- month, every N months; a
-- short month uses its last day
-- monthly_weekday on starts_on's weekday
-- position (2nd Tuesday), every
-- N months; a 5th becomes "last"
-- series_sun..sat one boolean per weekday, each a checkbox
-- series_*_time 'HH:MM', 24-hour, local to the event. The GLOB
-- is a backstop; the admin checks the range.
--
-- frequency and interval are NOT NULL with defaults so a box ticked
-- with nothing else filled in is still a complete schedule (weekly,
-- on starts_on's weekday). All of them are ignored while is_series
-- is 0.
--
-- There is no sort_order: events sort by date.
CREATE TABLE events (
id TEXT PRIMARY KEY,
scope_id TEXT NOT NULL REFERENCES event_scopes (id),
title TEXT NOT NULL,
theme TEXT,
tagline TEXT,
starts_on TEXT, -- 'YYYY-MM-DD'
ends_on TEXT,
date_label TEXT,
status TEXT CHECK (status IN ('upcoming', 'past', 'cancelled')),
venue TEXT,
address TEXT,
locality TEXT,
state_code TEXT,
country TEXT NOT NULL DEFAULT 'US',
location_label TEXT,
latitude REAL,
longitude REAL,
is_online INTEGER NOT NULL DEFAULT 0 CHECK (is_online IN (0, 1)),
org_logo TEXT, -- null → first host's logo
event_logo TEXT,
color TEXT, -- null → first host's, then the page's
gradient TEXT,
is_published INTEGER NOT NULL DEFAULT 1 CHECK (is_published IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
in_timeline INTEGER NOT NULL DEFAULT 0 CHECK (in_timeline IN (0, 1)),
event_type TEXT NOT NULL DEFAULT 'retreat'
CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other')),
is_series INTEGER NOT NULL DEFAULT 0 CHECK (is_series IN (0, 1)),
series_frequency TEXT NOT NULL DEFAULT 'weekly'
CHECK (series_frequency IN ('weekly', 'monthly_date', 'monthly_weekday')),
series_interval INTEGER NOT NULL DEFAULT 1 CHECK (series_interval >= 1),
series_sun INTEGER NOT NULL DEFAULT 0 CHECK (series_sun IN (0, 1)),
series_mon INTEGER NOT NULL DEFAULT 0 CHECK (series_mon IN (0, 1)),
series_tue INTEGER NOT NULL DEFAULT 0 CHECK (series_tue IN (0, 1)),
series_wed INTEGER NOT NULL DEFAULT 0 CHECK (series_wed IN (0, 1)),
series_thu INTEGER NOT NULL DEFAULT 0 CHECK (series_thu IN (0, 1)),
series_fri INTEGER NOT NULL DEFAULT 0 CHECK (series_fri IN (0, 1)),
series_sat INTEGER NOT NULL DEFAULT 0 CHECK (series_sat IN (0, 1)),
series_start_time TEXT CHECK (series_start_time GLOB '[0-2][0-9]:[0-5][0-9]'),
series_end_time TEXT CHECK (series_end_time GLOB '[0-2][0-9]:[0-5][0-9]'),
series_count INTEGER CHECK (series_count >= 1)
) STRICT;
CREATE INDEX events_date_idx ON events (starts_on);
CREATE INDEX events_scope_idx ON events (scope_id, is_published, starts_on);
CREATE INDEX events_type_idx ON events (event_type, is_published, starts_on);
-- Hosts are a list, and each is an organization or a person: a
-- retreat can be run jointly by two regions, and some events are
-- one person's. Two nullable foreign keys rather than a polymorphic
-- kind/id pair, so the references stay real and cascade on their
-- own. Deleting an organization drops it from the host list and
-- leaves the event standing.
--
-- The first host by sort_order supplies the logo and colour
-- fallbacks in v_events. A person supplies neither (a photo is a
-- headshot, not a logo), so an event hosted only by a person falls
-- through to the page's default.
--
-- UNIQUE (event_id, org_id, person_id) would not stop duplicates:
-- SQLite treats NULLs as distinct. Two partial indexes, one per kind.
CREATE TABLE event_hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL REFERENCES events (id) ON DELETE CASCADE,
org_id TEXT REFERENCES organizations (id) ON DELETE CASCADE,
person_id TEXT REFERENCES people (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
-- Exactly one of the two. (x IS NULL) evaluates to 0 or 1, so
-- <> between them is xor.
CHECK ((org_id IS NULL) <> (person_id IS NULL))
) STRICT;
CREATE INDEX event_hosts_event_idx ON event_hosts (event_id, sort_order);
CREATE INDEX event_hosts_org_idx ON event_hosts (org_id);
CREATE INDEX event_hosts_person_idx ON event_hosts (person_id);
CREATE UNIQUE INDEX event_hosts_org_uniq
ON event_hosts (event_id, org_id) WHERE org_id IS NOT NULL;
CREATE UNIQUE INDEX event_hosts_person_uniq
ON event_hosts (event_id, person_id) WHERE person_id IS NOT NULL;
-- ═══════════════════════════════════════════════════════════════
-- PEOPLE
-- ═══════════════════════════════════════════════════════════════
--
-- Public by design. Everything in this table can appear on a card,
-- and is_published = 0 is the only thing between a row and the open
-- web, hence the default of 0, unlike organizations. Anything that
-- must never be served lives in person_private, so a careless
-- SELECT * can't leak it. Bios and pages go in content_blocks,
-- socials in links. People sort by sort_name; there is no
-- sort_order.
CREATE TABLE people (
id TEXT PRIMARY KEY, -- slug: 'jane-doe'
display_name TEXT NOT NULL, -- 'Jane Doe'
sort_name TEXT, -- 'Doe, Jane', list ordering
pronouns TEXT, -- 'she/her'
tagline TEXT, -- fallback when no title applies
photo TEXT, -- filename in public/people/
public_email TEXT, -- safe to print on the site
public_phone TEXT,
locality TEXT,
state_code TEXT,
country TEXT NOT NULL DEFAULT 'US',
location_label TEXT,
is_published INTEGER NOT NULL DEFAULT 0 CHECK (is_published IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
bio TEXT,
primary_org_id TEXT REFERENCES organizations (id) ON DELETE SET NULL
) STRICT;
CREATE INDEX people_sort_idx ON people (is_published, sort_name);
CREATE INDEX people_primary_org ON people (primary_org_id);
-- Never joined into a public response. A separate table rather than
-- extra columns so the boundary is structural instead of a rule
-- someone has to remember. birth_date rather than age: an age column
-- is wrong within a year of being written.
CREATE TABLE person_private (
person_id TEXT PRIMARY KEY REFERENCES people (id) ON DELETE CASCADE,
birth_date TEXT, -- 'YYYY-MM-DD'
private_email TEXT,
private_phone TEXT,
address TEXT,
notes TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
-- A team belongs to exactly one organization: NGU national has a
-- Board and a Leadership Team, a region or chapter can have its own.
-- UNIQUE (id, org_id) looks redundant against the primary key, and
-- is, except that it gives affiliations a composite foreign key to
-- point at, which stops someone filing a person under a team
-- belonging to a different organization.
CREATE TABLE teams (
id TEXT PRIMARY KEY, -- slug: 'board', 'nw-leadership'
org_id TEXT NOT NULL REFERENCES organizations (id) ON DELETE CASCADE,
name TEXT NOT NULL,
tagline TEXT,
color TEXT,
logo TEXT,
is_published INTEGER NOT NULL DEFAULT 1 CHECK (is_published IN (0, 1)),
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE (id, org_id)
) STRICT;
CREATE INDEX teams_org_idx ON teams (org_id, sort_order);
-- The leadership list for every organization. A chapter lead, a
-- regional coordinator and a national board member are the same
-- kind of row; only org_id differs, and one person can hold several.
--
-- ended_on null means current; past roles are kept, not deleted.
-- is_owner marks authority within the organization and drives
-- billing order. It is deliberately orthogonal to role, and it is
-- NOT an edit permission.
--
-- Deleting a team that still has members fails rather than
-- silently detaching them: the composite foreign key has no ON
-- DELETE action. Clear or reassign the members first.
CREATE TABLE affiliations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
org_id TEXT NOT NULL REFERENCES organizations (id) ON DELETE CASCADE,
team_id TEXT,
title TEXT, -- 'Board Chair', 'Chapter Lead'
role TEXT NOT NULL DEFAULT 'member'
CHECK (role IN ('lead', 'board', 'staff', 'volunteer', 'member')),
is_owner INTEGER NOT NULL DEFAULT 0 CHECK (is_owner IN (0, 1)),
started_on TEXT,
ended_on TEXT, -- null = current
is_public INTEGER NOT NULL DEFAULT 1 CHECK (is_public IN (0, 1)),
sort_order INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (team_id, org_id) REFERENCES teams (id, org_id)
) STRICT;
CREATE INDEX affiliations_person_idx ON affiliations (person_id);
CREATE INDEX affiliations_org_idx
ON affiliations (org_id, is_public, is_owner DESC, sort_order);
CREATE INDEX affiliations_team_idx ON affiliations (team_id, sort_order);
-- Both the public billing (speakers, leaders) and the private record
-- of who attended, told apart by is_public. It defaults to 0, so a
-- new row is invisible until someone decides otherwise.
CREATE TABLE event_people (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL REFERENCES events (id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
role TEXT NOT NULL DEFAULT 'attendee'
CHECK (role IN ('speaker', 'leader', 'facilitator', 'host',
'musician', 'volunteer', 'attendee')),
title TEXT, -- 'Keynote Speaker'
is_public INTEGER NOT NULL DEFAULT 0 CHECK (is_public IN (0, 1)),
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE (event_id, person_id, role)
) STRICT;
CREATE INDEX event_people_event_idx ON event_people (event_id, is_public, sort_order);
CREATE INDEX event_people_person_idx ON event_people (person_id);
-- An award exists independently of who won it. org_id is who gives
-- it: nullable, because an award can predate that decision and
-- person_awards rows must survive the awarding org being deleted.
-- An unpublished award is a draft, off the site entirely.
CREATE TABLE awards (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
logo TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
org_id TEXT REFERENCES organizations (id) ON DELETE SET NULL,
is_published INTEGER NOT NULL DEFAULT 1 CHECK (is_published IN (0, 1))
) STRICT;
CREATE INDEX awards_org_idx ON awards (org_id, sort_order);
CREATE INDEX awards_published_idx ON awards (is_published, sort_order);
CREATE TABLE person_awards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
award_id TEXT NOT NULL REFERENCES awards (id) ON DELETE CASCADE,
event_id TEXT REFERENCES events (id) ON DELETE SET NULL, -- where presented
awarded_on TEXT,
citation TEXT,
is_public INTEGER NOT NULL DEFAULT 1 CHECK (is_public IN (0, 1)),
UNIQUE (person_id, award_id, awarded_on)
) STRICT;
CREATE INDEX person_awards_person_idx ON person_awards (person_id);
-- ═══════════════════════════════════════════════════════════════
-- CONTENT BLOCKS AND LINKS
-- ═══════════════════════════════════════════════════════════════
--
-- Shared by the four things that own a card and a page:
-- organizations, events, people and teams. A bio, an event
-- description and a region's page all render through one component.
--
-- owner_kind + owner_id is polymorphic, so SQLite can't hold it as
-- a foreign key. The *_owner_exists triggers check it on insert and
-- the *_cleanup triggers remove a deleted owner's rows. 'award' is
-- not an owner kind; adding it is a table rebuild for this CHECK.
--
-- slot 'card' is the short version on the tile, 'body' the full
-- page. Same renderer, different query.
CREATE TABLE content_blocks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider')),
text TEXT,
media TEXT,
href TEXT
) STRICT;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
CREATE TABLE content_block_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
block_id INTEGER NOT NULL REFERENCES content_blocks (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
text TEXT NOT NULL,
detail TEXT,
url TEXT -- null → plain list item
) STRICT;
CREATE INDEX content_block_items_block_idx
ON content_block_items (block_id, sort_order);
CREATE TABLE links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team')),
owner_id TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'action'
CHECK (kind IN ('action', 'social', 'website', 'email')),
platform TEXT, -- 'instagram', 'discord'
label TEXT NOT NULL,
url TEXT NOT NULL,
is_primary INTEGER NOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1))
) STRICT;
CREATE INDEX links_owner_idx ON links (owner_kind, owner_id, kind, sort_order);
-- ═══════════════════════════════════════════════════════════════
-- TIMELINE
-- ═══════════════════════════════════════════════════════════════
--
-- The history page's spine. A row that points at a record holds
-- almost nothing of its own: title, date and logo are read back
-- from the record at query time (v_timeline), so editing the event
-- edits the timeline and there is no second copy to drift. Decade
-- headers are not here; they live in src/data/historyDecades.ts.
--
-- ref_kind + ref_id is polymorphic, like content_blocks and links,
-- and checked by the same kind of trigger.
CREATE TABLE timeline_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- What the entry is about, which drives the marker and the body
-- layout on the page. Usually mirrors ref_kind; 'people' is the
-- exception, being a team ref rendered as a roster, and
-- 'milestone' is the free-standing case with no ref at all.
kind TEXT NOT NULL DEFAULT 'milestone'
CHECK (kind IN ('milestone', 'event', 'organization',
'award', 'people')),
ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'award',
'person', 'team')),
ref_id TEXT,
-- Null inherits from the referenced row: an event's starts_on. A
-- hand-authored entry has to supply its own, which the descriptor
-- can't require conditionally, the read layer reports an entry
-- with neither rather than the table refusing it.
occurred_on TEXT,
-- How much of occurred_on is trustworthy. Backfilled rows often
-- have a full date where only the year is actually known, and
-- 'year' is what routes them to "Elsewhere in 2009" instead of
-- asserting a month nobody can source.
precision TEXT NOT NULL DEFAULT 'day'
CHECK (precision IN ('year', 'month', 'day')),
-- All null-inherits-from-the-ref. Filling one in is an override,
-- for when the timeline wants to say something the event card
-- doesn't.
title TEXT,
blurb TEXT,
meta TEXT,
link_url TEXT,
is_featured INTEGER NOT NULL DEFAULT 0 CHECK (is_featured IN (0, 1)),
is_published INTEGER NOT NULL DEFAULT 1 CHECK (is_published IN (0, 1)),
sort_order INTEGER NOT NULL DEFAULT 0, -- tie-break within a date
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
-- Half a reference is worse than none: it would resolve to a link
-- with no destination and no way to notice.
CHECK ((ref_kind IS NULL) = (ref_id IS NULL)),
-- One timeline entry per referenced record, which is what makes
-- the in_timeline checkbox an upsert rather than a duplicate
-- factory. SQLite permits any number of NULL pairs here, so
-- hand-authored entries are unaffected.
UNIQUE (ref_kind, ref_id)
) STRICT;
CREATE INDEX timeline_entries_date_idx
ON timeline_entries (is_published, occurred_on DESC);
CREATE TABLE timeline_entry_people (
entry_id INTEGER NOT NULL REFERENCES timeline_entries (id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
note TEXT, -- 'Founding lead'
sort_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (entry_id, person_id)
) STRICT;
CREATE INDEX timeline_entry_people_person_idx
ON timeline_entry_people (person_id);
-- ═══════════════════════════════════════════════════════════════
-- FRONT PAGE
-- ═══════════════════════════════════════════════════════════════
--
-- The home page's editable half. One row in front_page, the CHECK
-- on id makes a second one impossible, and the admin engine treats
-- it as a singleton, and ordered collections hanging off it, each
-- replaced wholesale on save. Nothing has a foreign key into them,
-- which is what makes that safe.
--
-- What stays in code: how each section looks, and the list of
-- section keys. A section is a component, so the CHECK on
-- front_page_sections.section is the list of components that exist;
-- a row can reorder, retitle or hide one, never invent one.
--
-- hero_mode is switched by hand; 'livestream' shows the embed until
-- someone switches it back. countdown_event_id pins the countdown;
-- null counts down to the next upcoming published event.
--
-- Stats: 'manual' prints value as typed, 'years_since' reads value
-- as a year and counts up from it, everything else is a COUNT the
-- API runs. Adding a source is this CHECK, the enum in both
-- descriptor halves, and the query in routes/home.js.
CREATE TABLE front_page (
id TEXT PRIMARY KEY CHECK (id = 'home'),
hero_mode TEXT NOT NULL DEFAULT 'brand'
CHECK (hero_mode IN ('brand', 'photos', 'livestream')),
eyebrow TEXT,
headline TEXT NOT NULL DEFAULT 'Next Generation of Unity',
subhead TEXT,
primary_label TEXT,
primary_url TEXT,
secondary_label TEXT,
secondary_url TEXT,
slide_seconds INTEGER NOT NULL DEFAULT 7
CHECK (slide_seconds BETWEEN 3 AND 60),
livestream_url TEXT,
livestream_title TEXT,
countdown_event_id TEXT REFERENCES events (id) ON DELETE SET NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE TABLE front_page_slides (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES front_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
media TEXT NOT NULL, -- filename in public/front-page/, or a URL
alt TEXT,
caption TEXT,
link_url TEXT
) STRICT;
CREATE TABLE front_page_sections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES front_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
section TEXT NOT NULL
CHECK (section IN ('countdown', 'retreats', 'calendar', 'stats',
'timeline', 'connect')),
title TEXT,
blurb TEXT,
is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)),
UNIQUE (page_id, section)
) STRICT;
CREATE TABLE front_page_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES front_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'manual'
CHECK (source IN ('manual', 'years_since', 'regions', 'chapters',
'partners', 'events_held', 'retreats_held',
'people', 'awards_given')),
value TEXT,
suffix TEXT, -- '+', 'k', ' states'
note TEXT
) STRICT;
-- The connect section's "I want to…" choices, each with its actions.
CREATE TABLE front_page_paths (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES front_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL, -- 'Attend'
icon TEXT, -- one emoji
blurb TEXT
) STRICT;
CREATE TABLE front_page_path_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path_id INTEGER NOT NULL REFERENCES front_page_paths (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
description TEXT,
url TEXT NOT NULL
) STRICT;
CREATE INDEX front_page_path_actions_path_idx ON front_page_path_actions (path_id, sort_order);
-- ═══════════════════════════════════════════════════════════════
-- FEEDBACK
-- ═══════════════════════════════════════════════════════════════
--
-- The public form's submissions. section_id is the page section the
-- visitor picked (a subnav hash), nothing to do with events.
CREATE TABLE feedback (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
feedback_type TEXT NOT NULL DEFAULT 'general',
message TEXT NOT NULL,
name TEXT,
email TEXT,
page_path TEXT,
section_id TEXT,
status TEXT NOT NULL DEFAULT 'new'
CHECK (status IN ('new', 'read', 'actioned', 'archived', 'spam')),
admin_note TEXT,
user_agent TEXT,
ip_hash TEXT -- hashed, never the address
) STRICT;
CREATE INDEX feedback_triage_idx ON feedback (status, created_at DESC);
-- ═══════════════════════════════════════════════════════════════
-- AUTHENTICATION
-- ═══════════════════════════════════════════════════════════════
--
-- Who may sign in, and who currently is. There is no self-signup:
-- accounts are created with admin-cli.js, on the box, by someone
-- with shell access. No invite flow, no email delivery, no
-- password-reset surface for anyone to attack.
CREATE TABLE admin_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
-- Stored lowercased. The application lowercases on every read
-- and write, so the UNIQUE index is genuinely case-insensitive
-- without depending on a collation.
email TEXT NOT NULL UNIQUE,
name TEXT,
-- Nullable so a Google-only account can exist later with no
-- password at all. A row with both can use either route in.
password_hash TEXT,
-- Google's stable subject id. Nullable, unique when present,
-- SQLite allows any number of NULLs in a unique index.
google_sub TEXT UNIQUE,
-- Listed low to high. The application treats these as a ladder,
-- not a set: each one passes every check the one below it
-- passes. The default stays 'admin' so no existing tooling
-- starts creating accounts with different powers than it did
-- yesterday.
--
-- viewer read
-- editor + create and update
-- admin + delete
-- superadmin + accounts, roles and sessions
role TEXT NOT NULL DEFAULT 'admin'
CHECK (role IN ('viewer', 'editor', 'admin', 'superadmin')),
is_active INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
last_login_at TEXT
) STRICT;
-- One row per active login. The cookie holds a random token; this
-- table holds only its SHA-256, so a database leak doesn't hand
-- anyone a working session.
CREATE TABLE sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_hash TEXT NOT NULL UNIQUE,
user_id INTEGER NOT NULL REFERENCES admin_users (id) ON DELETE CASCADE,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_seen_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL,
user_agent TEXT,
ip_hash TEXT
) STRICT;
CREATE INDEX sessions_user_idx ON sessions (user_id);
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
-- ═══════════════════════════════════════════════════════════════
-- VIEWS
-- ═══════════════════════════════════════════════════════════════
-- Every host of every event, resolved to a name and the bits the
-- fallbacks need. is_published travels with the row rather than
-- being filtered here, so the public routes can hide an unpublished
-- host and the admin can still see one.
CREATE VIEW v_event_hosts AS
SELECT
eh.id,
eh.event_id,
eh.sort_order,
CASE WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
AS host_kind,
COALESCE(eh.org_id, eh.person_id) AS host_id,
COALESCE(o.name, p.display_name) AS host_name,
o.kind AS host_org_kind,
o.logo AS host_logo,
o.color AS host_color,
p.photo AS host_photo,
COALESCE(o.is_published, p.is_published) AS host_is_published
FROM event_hosts eh
LEFT JOIN organizations o ON o.id = eh.org_id
LEFT JOIN people p ON p.id = eh.person_id;
-- Events with their fallbacks resolved, so components read one
-- field: effective_org_logo and effective_color from the event or
-- its first host, effective_status from status or the dates. e.* so
-- a new events column reaches /events with no change here.
--
-- A correlated subquery picks the first host rather than GROUP BY
-- with bare columns beside MIN(sort_order): the bare-column form
-- works only in SQLite and resolves a tie differently run to run.
CREATE VIEW v_events AS
SELECT
e.*,
h.host_kind,
h.host_id,
h.host_name,
h.host_org_kind,
COALESCE(e.org_logo, h.host_logo) AS effective_org_logo,
COALESCE(e.color, h.host_color) AS effective_color,
COALESCE(
e.status,
CASE WHEN e.ends_on IS NOT NULL AND e.ends_on < date('now')
THEN 'past' ELSE 'upcoming' END
) AS effective_status
FROM events e
LEFT JOIN v_event_hosts h
ON h.id = (
SELECT x.id
FROM v_event_hosts x
WHERE x.event_id = e.id
ORDER BY x.sort_order, x.id
LIMIT 1
);
-- An event's public billing: published people, public rows only.
CREATE VIEW v_event_people AS
SELECT
ep.event_id, ep.person_id, ep.role, ep.title, ep.sort_order,
p.display_name, p.pronouns, p.tagline, p.photo
FROM event_people ep
JOIN people p ON p.id = ep.person_id AND p.is_published = 1
WHERE ep.is_public = 1;
-- Current, public leadership for every organization, with the
-- person's primary organization named for cross-links.
CREATE VIEW v_org_leadership AS
SELECT
a.org_id,
a.team_id,
t.name AS team_name,
t.sort_order AS team_sort_order,
a.person_id,
a.title,
a.role,
a.is_owner,
a.sort_order,
p.display_name,
p.sort_name,
p.pronouns,
p.tagline,
p.photo,
p.public_email,
p.location_label,
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
FROM affiliations a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
LEFT JOIN teams t ON t.id = a.team_id
LEFT JOIN organizations o ON o.id = p.primary_org_id
WHERE a.is_public = 1
AND a.ended_on IS NULL
ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name;
-- Timeline entries with everything inherited from the referenced
-- record resolved: date, title, blurb, logo.
CREATE VIEW v_timeline AS
SELECT
t.id,
t.kind,
t.ref_kind,
t.ref_id,
t.precision,
t.is_featured,
t.is_published,
t.sort_order,
COALESCE(t.occurred_on, e.starts_on, pa.awarded_on) AS effective_date,
COALESCE(
t.title,
e.title,
o.name,
aw.name,
p.display_name,
tm.name
) AS effective_title,
COALESCE(t.blurb, e.tagline, o.tagline, aw.description, p.tagline, tm.tagline)
AS effective_blurb,
t.meta,
t.link_url,
-- Filename only. The directory is the frontend's business.
COALESCE(e.event_logo, e.org_logo, o.logo, aw.logo, p.photo, tm.logo)
AS effective_logo,
o.kind AS org_kind,
tm.org_id AS team_org_id,
tm.name AS team_name,
-- Whether the referenced record is itself visible. An entry must not
-- outlive the thing it points at being unpublished, a draft event
-- would otherwise leak its title and date onto a public page. Null
-- for a standalone milestone, which answers to nothing but its own
-- is_published.
CASE t.ref_kind
WHEN 'event' THEN e.is_published
WHEN 'organization' THEN o.is_published
WHEN 'person' THEN p.is_published
WHEN 'team' THEN tm.is_published
ELSE NULL
END AS ref_is_published,
t.occurred_on,
t.title AS title_override
FROM timeline_entries t
LEFT JOIN events e ON t.ref_kind = 'event' AND e.id = t.ref_id
LEFT JOIN organizations o ON t.ref_kind = 'organization' AND o.id = t.ref_id
LEFT JOIN awards aw ON t.ref_kind = 'award' AND aw.id = t.ref_id
LEFT JOIN people p ON t.ref_kind = 'person' AND p.id = t.ref_id
LEFT JOIN teams tm ON t.ref_kind = 'team' AND tm.id = t.ref_id
LEFT JOIN person_awards pa ON t.ref_kind = 'award' AND pa.award_id = t.ref_id
AND pa.id = (SELECT MIN(id) FROM person_awards
WHERE award_id = t.ref_id);
-- ═══════════════════════════════════════════════════════════════
-- SEED
-- ═══════════════════════════════════════════════════════════════
--
-- What a new database needs before anyone signs in: the scopes an
-- event can be filed under, and the front page as it ships, every
-- section, the stats that need no typing, and the Church Center
-- forms sorted into paths. Everything else comes in through the
-- admin.
INSERT INTO meta (key, value) VALUES ('created_at', datetime('now'));
INSERT INTO event_scopes (id, name, sort_order) VALUES
('national', 'National', 10),
('regional', 'Regional', 20),
('local', 'Local', 30),
('international', 'International', 40),
('partner', 'Partner', 50),
('other', 'Other', 60);
INSERT INTO front_page
(id, eyebrow, headline, subhead,
primary_label, primary_url, secondary_label, secondary_url)
VALUES
('home',
'Young adults of the Unity movement',
'Next Generation of Unity',
'A community for 18–40 year olds, rooted in spiritual growth, leadership and sacred service.',
'Find a retreat', '/retreats',
'Find your way in', '#connect');
INSERT INTO front_page_sections (page_id, sort_order, section, title, blurb) VALUES
('home', 0, 'countdown', NULL, NULL),
('home', 1, 'retreats', 'National Retreats', 'Our flagship gatherings, open to young adults across the country.'),
('home', 2, 'calendar', 'What''s on', 'Every gathering, class and meeting in one place.'),
('home', 3, 'stats', 'NGU by the numbers', NULL),
('home', 4, 'timeline', 'Moments that shaped us', 'Highlights from our history.'),
('home', 5, 'connect', 'Find your way in', 'Tell us what you''re looking for.');
INSERT INTO front_page_stats (page_id, sort_order, label, source) VALUES
('home', 0, 'Regions', 'regions'),
('home', 1, 'Chapters', 'chapters'),
('home', 2, 'Retreats held', 'retreats_held'),
('home', 3, 'Awards given', 'awards_given');
INSERT INTO front_page_paths (page_id, sort_order, label, icon, blurb) VALUES
('home', 0, 'Attend', '🧭', 'Come to a gathering near you or across the country.'),
('home', 1, 'Serve', '🤲', 'Help create transformative experiences for young adults.'),
('home', 2, 'Belong', '🌱', 'Make NGU your community.'),
('home', 3, 'Partner', '🤝', 'Bring your ministry or organization alongside us.');
INSERT INTO front_page_path_actions (path_id, sort_order, label, description, url)
SELECT p.id, a.sort_order, a.label, a.description, a.url
FROM front_page_paths p
JOIN (
SELECT 'Attend' AS path, 0 AS sort_order, 'See upcoming retreats' AS label,
'National, regional and partner gatherings.' AS description,
'/retreats' AS url
UNION ALL SELECT 'Attend', 1, 'NGU calendar',
'Everything on the schedule, in one place.',
'https://ngu.churchcenter.com/calendar?view=gallery'
UNION ALL SELECT 'Serve', 0, 'Volunteer',
'Lend a hand at a retreat or event.',
'https://ngu.churchcenter.com/people/forms/1176908'
UNION ALL SELECT 'Serve', 1, 'Speaker & Musician Directory',
'Join our network of speakers, musicians and facilitators.',
'https://ngu.churchcenter.com/people/forms/1173181'
UNION ALL SELECT 'Belong', 0, 'Become a member',
'Join the NGU community officially.',
'https://ngu.churchcenter.com/people/forms/1135816'
UNION ALL SELECT 'Belong', 1, 'Find your region',
'Chapters and regions across the country.',
'/community'
UNION ALL SELECT 'Partner', 0, 'Affiliation form',
'Affiliate your ministry or spiritual organization with NGU.',
'https://ngu.churchcenter.com/people/forms/1135750'
) a ON a.path = p.label
WHERE p.page_id = 'home';
-- ═══════════════════════════════════════════════════════════════
-- TRIGGERS
-- ═══════════════════════════════════════════════════════════════
--
-- Last in the file: nothing may follow a BEGIN...END body.
-- ── Polymorphic owners exist ───────────────────────────────────
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
END;
END;
CREATE TRIGGER links_owner_exists
BEFORE INSERT ON links
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'links: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'links: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'links: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'links: no such team')
END;
END;
CREATE TRIGGER timeline_entries_ref_exists
BEFORE INSERT ON timeline_entries
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such organization')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such award')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such team')
END;
END;
CREATE TRIGGER timeline_entries_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON timeline_entries
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such organization')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such award')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'timeline_entries: no such team')
END;
END;
-- ── A deleted owner takes its blocks, links and timeline entry ──
CREATE TRIGGER organizations_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'organization' AND owner_id = old.id;
DELETE FROM links WHERE owner_kind = 'organization' AND owner_id = old.id;
END;
CREATE TRIGGER events_cleanup
AFTER DELETE ON events
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'event' AND owner_id = old.id;
DELETE FROM links WHERE owner_kind = 'event' AND owner_id = old.id;
END;
CREATE TRIGGER people_cleanup
AFTER DELETE ON people
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'person' AND owner_id = old.id;
DELETE FROM links WHERE owner_kind = 'person' AND owner_id = old.id;
END;
CREATE TRIGGER teams_cleanup
AFTER DELETE ON teams
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'team' AND owner_id = old.id;
DELETE FROM links WHERE owner_kind = 'team' AND owner_id = old.id;
END;
CREATE TRIGGER timeline_events_cleanup
AFTER DELETE ON events
BEGIN
DELETE FROM timeline_entries WHERE ref_kind = 'event' AND ref_id = old.id;
END;
CREATE TRIGGER timeline_organizations_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM timeline_entries WHERE ref_kind = 'organization' AND ref_id = old.id;
END;
CREATE TRIGGER timeline_awards_cleanup
AFTER DELETE ON awards
BEGIN
DELETE FROM timeline_entries WHERE ref_kind = 'award' AND ref_id = old.id;
END;
CREATE TRIGGER timeline_people_cleanup
AFTER DELETE ON people
BEGIN
DELETE FROM timeline_entries WHERE ref_kind = 'person' AND ref_id = old.id;
END;
CREATE TRIGGER timeline_teams_cleanup
AFTER DELETE ON teams
BEGIN
DELETE FROM timeline_entries WHERE ref_kind = 'team' AND ref_id = old.id;
END;
-- ── updated_at ─────────────────────────────────────────────────
-- An UPDATE that doesn't set updated_at itself gets it set, which
-- is what the admin engine's optimistic concurrency compares.
CREATE TRIGGER organizations_touch
AFTER UPDATE ON organizations
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE organizations SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER events_touch
AFTER UPDATE ON events
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE events SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER people_touch
AFTER UPDATE ON people
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE people SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER teams_touch
AFTER UPDATE ON teams
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE teams SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER timeline_entries_touch
AFTER UPDATE ON timeline_entries
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE timeline_entries SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER front_page_touch
AFTER UPDATE ON front_page
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE front_page SET updated_at = datetime('now') WHERE id = new.id;
END;