-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingularity_merge.sql
More file actions
1830 lines (1644 loc) · 78.7 KB
/
singularity_merge.sql
File metadata and controls
1830 lines (1644 loc) · 78.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- =============================================================================
-- singularity_merge.sql
-- Core Elite × Recruiting — Apex Database Merge Migration
-- STATUS: ✅ RESOLVED — All stubs completed. Ready for staging validation.
-- =============================================================================
--
-- PURPOSE:
-- Inject Core Elite live-combine operations into the Recruiting "Apex Database"
-- without destroying existing Stripe, billing, or recruiting data.
--
-- APEX SCHEMA CONTEXT (confirmed 2026-04-20):
-- - organizations: DOES NOT EXIST in Apex → Part 2.1 creates it fresh
-- - profiles: EXISTS with user_id (≠ auth.uid() FK), display_name, org_id TEXT
-- - athletes: EXISTS (28 cols) — recruiting prospects without event_id
-- - events: DOES NOT EXIST in Apex → Part 1.1 creates it fresh
--
-- COLUMN NAME MAPPINGS (Apex column → CE parameter):
-- athletes.height_inches ↔ p_height_in (INT)
-- athletes.weight_lbs ↔ p_weight_lb (INT)
-- athletes.graduation_year ↔ p_grad_year (not used in register RPC; Apex has it already)
-- profiles.display_name ↔ full_name (synced via trigger; CE reads full_name)
-- profiles.user_id = auth.uid() (NOT profiles.id — Apex structural difference)
--
-- CRITICAL STRUCTURAL DIFFERENCE — PROFILES:
-- Core Elite: profiles.id = auth.uid() (id is the auth FK)
-- Apex: profiles.user_id = auth.uid() (id is a separate gen_random_uuid() PK)
-- Resolution: ALL RLS policies use user_id = auth.uid(). CE app code must be
-- updated to read profile rows by user_id, not id (see MERGE_STRATEGY.md §5).
--
-- IDEMPOTENCY:
-- Safe to run multiple times. Every statement uses IF NOT EXISTS / ON CONFLICT /
-- CREATE OR REPLACE / DO $$ guards. The transaction rolls back completely if any
-- statement fails — no partial state is committed.
--
-- MERGE STRATEGY DECISION LOG: See MERGE_STRATEGY.md (generated alongside this file).
--
-- =============================================================================
BEGIN;
-- =============================================================================
-- PART 0: PRE-FLIGHT SAFETY CHECKS
-- These checks ABORT THE ENTIRE MIGRATION if unsafe conditions are detected.
-- =============================================================================
DO $$
DECLARE
v_tbl_exists BOOLEAN;
BEGIN
-- ---------------------------------------------------------------------------
-- CHECK 0.1: organizations collision guard
-- If `organizations` exists but lacks `slug`, abort.
-- ---------------------------------------------------------------------------
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'organizations'
) INTO v_tbl_exists;
IF v_tbl_exists THEN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'organizations'
AND column_name = 'slug'
) THEN
RAISE EXCEPTION
E'PRE-FLIGHT ABORT: `organizations` table exists in Apex DB but lacks `slug` column.\n'
'Core Elite requires organizations.slug (UNIQUE TEXT) for white-label routing.\n'
'Resolution options:\n'
' A) ALTER TABLE organizations ADD COLUMN slug TEXT UNIQUE; (then UPDATE existing rows)\n'
' B) Rename Core Elite''s organizations table to `ce_organizations` (update all app queries)\n'
'After resolving, re-run this migration. Code: CE_ORGS_COLLISION';
END IF;
END IF;
-- ---------------------------------------------------------------------------
-- CHECK 0.2: athletes collision guard — ADVISORY (not a hard abort)
--
-- Apex has an athletes table without event_id (recruiting prospects).
-- Resolution: STUB 2.3 will ADD event_id via ALTER TABLE. Proceeding.
-- This check now only aborts if athletes.event_id exists but is incompatible.
-- ---------------------------------------------------------------------------
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'athletes'
) INTO v_tbl_exists;
IF v_tbl_exists THEN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'athletes'
AND column_name = 'event_id'
) THEN
RAISE NOTICE
'PRE-FLIGHT NOTICE: athletes table exists without event_id. '
'This is expected for the Apex recruiting database. '
'STUB 2.3 will ALTER TABLE athletes ADD COLUMN event_id to enable CE combine operations. '
'Existing recruiting prospect rows will have event_id = NULL (they are not combine athletes).';
END IF;
END IF;
-- ---------------------------------------------------------------------------
-- CHECK 0.3: events collision guard
-- If `events` exists but lacks `required_drills`, it may be a Recruiting events
-- table. Hard abort to prevent overwriting recruiting calendar data.
-- (Apex confirmed no events table — this guard remains for safety.)
-- ---------------------------------------------------------------------------
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'events'
) INTO v_tbl_exists;
IF v_tbl_exists THEN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'events'
AND column_name = 'required_drills'
) THEN
RAISE EXCEPTION
E'PRE-FLIGHT ABORT: `events` table exists in Apex DB but lacks `required_drills` column.\n'
'This may be a Recruiting events table (campus visits, prospect days, etc.).\n'
'Resolution options:\n'
' A) Rename Core Elite''s events table to `combine_events` (update all app queries + RPCs)\n'
' B) Add `required_drills JSONB DEFAULT ''[]''::jsonb` and\n'
' `is_combine_event BOOLEAN DEFAULT false` to the existing events table\n'
'Do NOT proceed until resolved. Code: CE_EVENTS_COLLISION';
END IF;
END IF;
-- ---------------------------------------------------------------------------
-- CHECK 0.4: Core Elite RPC collision guard
-- If register_athlete_secure exists with a DIFFERENT argument count, abort.
-- v5 has exactly 20 parameters.
-- ---------------------------------------------------------------------------
IF EXISTS (
SELECT 1 FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'
AND p.proname = 'register_athlete_secure'
AND pronargs != 20
) THEN
RAISE EXCEPTION
E'PRE-FLIGHT ABORT: `register_athlete_secure` exists with a different parameter count.\n'
'Running CREATE OR REPLACE will create a new overload, NOT replace the existing function.\n'
'Resolution: DROP FUNCTION register_athlete_secure(<old_arg_types>) CASCADE;\n'
'Code: CE_RPC_OVERLOAD_COLLISION';
END IF;
RAISE NOTICE 'Pre-flight checks passed. Proceeding with migration.';
END $$;
-- =============================================================================
-- PART 1: LOW-RISK TABLES
-- Domain-specific to combine operations. Safe to create with IF NOT EXISTS.
-- =============================================================================
-- ---------------------------------------------------------------------------
-- 1.1 events — Core Elite combine events
-- Confirmed NOT to exist in Apex DB. Creates fresh.
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
slug TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
date DATE NOT NULL,
location TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft', 'live', 'closed')),
required_drills JSONB NOT NULL DEFAULT '[]'::jsonb,
organization_id UUID, -- FK added after organizations confirmed (Part 2.1)
override_pin TEXT DEFAULT NULL,
registration_open BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now()
);
COMMENT ON TABLE events IS
'Core Elite combine events. Scoped by organization_id for multi-tenant isolation. '
'status: draft → live (open for combine floor) → closed (results locked). '
'override_pin: event-day admin PIN for Gate 2/3 result overrides.';
-- ---------------------------------------------------------------------------
-- 1.2 bands — physical QR wristbands
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS bands (
band_id TEXT PRIMARY KEY,
event_id UUID NOT NULL REFERENCES events(id),
display_number INT NOT NULL,
status TEXT NOT NULL DEFAULT 'available'
CHECK (status IN ('available', 'assigned', 'void')),
athlete_id UUID, -- FK added after athletes confirmed (Part 2.3)
assigned_at TIMESTAMPTZ,
assigned_by UUID REFERENCES auth.users(id),
UNIQUE (event_id, display_number)
);
COMMENT ON TABLE bands IS
'Physical QR wristbands for combine participants. One band per athlete per event. '
'band_id is the non-guessable QR payload scanned at stations.';
-- ---------------------------------------------------------------------------
-- 1.3 stations — physical testing stations
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS stations (
id TEXT PRIMARY KEY,
event_id UUID NOT NULL REFERENCES events(id),
name TEXT NOT NULL,
drill_type TEXT NOT NULL,
requires_auth BOOLEAN DEFAULT true,
enabled BOOLEAN DEFAULT true
);
COMMENT ON TABLE stations IS
'Combine testing stations. id is a human-readable label (e.g., SPEED-1). '
'drill_type maps to DRILL_CATALOG in src/constants.ts.';
-- ---------------------------------------------------------------------------
-- 1.4 results — immutable drill result records
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS results (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
client_result_id UUID UNIQUE NOT NULL,
event_id UUID NOT NULL REFERENCES events(id),
athlete_id UUID NOT NULL, -- FK added after athletes confirmed (Part 2.3)
band_id TEXT NOT NULL REFERENCES bands(band_id),
station_id TEXT NOT NULL REFERENCES stations(id),
drill_type TEXT NOT NULL,
value_num NUMERIC,
value_text TEXT,
attempt_number INT NOT NULL DEFAULT 1,
hlc_timestamp TEXT,
device_timestamp BIGINT,
source_type TEXT NOT NULL DEFAULT 'manual_staff'
CHECK (source_type IN ('live_ble', 'manual_staff', 'legacy_csv')),
session_id TEXT,
verification_hash TEXT,
validation_status TEXT NOT NULL DEFAULT 'clean'
CHECK (validation_status IN ('clean','extraordinary','reviewed')),
voided BOOLEAN DEFAULT false,
meta JSONB,
recorded_by UUID REFERENCES auth.users(id),
recorded_at TIMESTAMPTZ DEFAULT now()
);
COMMENT ON TABLE results IS
'Immutable combine drill results. Each attempt is a separate row. '
'Best result per drill computed at query time. '
'voided = true rows are excluded from leaderboards and exports. '
'verification_hash: HMAC-SHA-256 set by generate-verified-export Edge Function.';
-- ---------------------------------------------------------------------------
-- 1.5 device_status — station heartbeat (30-second interval)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS device_status (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES events(id),
station_id TEXT NOT NULL REFERENCES stations(id),
device_label TEXT,
last_seen_at TIMESTAMPTZ DEFAULT now(),
is_online BOOLEAN DEFAULT true,
pending_queue_count INT DEFAULT 0,
last_sync_at TIMESTAMPTZ,
hlc_timestamp TEXT,
CONSTRAINT device_status_unique_identity
UNIQUE (event_id, station_id, device_label)
);
-- ---------------------------------------------------------------------------
-- 1.6 waivers — parent/guardian liability waivers
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS waivers (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
athlete_id UUID NOT NULL, -- FK after athletes confirmed (Part 2.3)
event_id UUID NOT NULL REFERENCES events(id),
guardian_name TEXT NOT NULL,
guardian_relationship TEXT,
emergency_contact_name TEXT NOT NULL,
emergency_contact_phone TEXT NOT NULL,
signature_data_url TEXT NOT NULL,
agreed BOOLEAN NOT NULL DEFAULT true,
injury_waiver_ack BOOLEAN NOT NULL DEFAULT false,
media_release BOOLEAN NOT NULL DEFAULT false,
data_consent BOOLEAN NOT NULL DEFAULT false,
marketing_consent BOOLEAN NOT NULL DEFAULT false,
waiver_version TEXT NOT NULL DEFAULT '2026.1',
agreed_at TIMESTAMPTZ DEFAULT now(),
ip_address TEXT,
user_agent TEXT
);
-- ---------------------------------------------------------------------------
-- 1.7 token_claims — single-use band-claim tokens (valid 24 hours)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS token_claims (
token_hash TEXT PRIMARY KEY,
event_id UUID NOT NULL REFERENCES events(id),
athlete_id UUID NOT NULL, -- FK after athletes confirmed (Part 2.3)
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ
);
-- ---------------------------------------------------------------------------
-- 1.8 parent_portals — token-gated read-only result portals
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS parent_portals (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
athlete_id UUID NOT NULL, -- FK after athletes confirmed (Part 2.3)
event_id UUID NOT NULL REFERENCES events(id),
portal_token TEXT UNIQUE NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
-- ---------------------------------------------------------------------------
-- 1.9 report_jobs — async report generation queue
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS report_jobs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES events(id),
athlete_id UUID NOT NULL, -- FK after athletes confirmed (Part 2.3)
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','processing','ready','failed')),
completed_drills JSONB DEFAULT '[]'::jsonb,
generated_at TIMESTAMPTZ,
report_url TEXT,
summary JSONB
);
-- ---------------------------------------------------------------------------
-- 1.10 incidents — combine floor incident log
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS incidents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES events(id),
station_id TEXT NOT NULL REFERENCES stations(id),
athlete_id UUID, -- FK after athletes confirmed (Part 2.3)
type TEXT NOT NULL,
description TEXT,
severity TEXT NOT NULL CHECK (severity IN ('low','medium','high','critical')),
recorded_by UUID REFERENCES auth.users(id),
created_at TIMESTAMPTZ DEFAULT now()
);
-- ---------------------------------------------------------------------------
-- 1.11 capture_telemetry — per-capture BLE diagnostic record
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS capture_telemetry (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
client_telemetry_id UUID NOT NULL UNIQUE,
event_id UUID NOT NULL REFERENCES events(id),
result_id UUID REFERENCES results(id) ON DELETE SET NULL,
station_id TEXT NOT NULL REFERENCES stations(id),
athlete_id UUID NOT NULL, -- FK after athletes confirmed (Part 2.3)
drill_type TEXT NOT NULL,
device_timestamp BIGINT NOT NULL,
device_id TEXT NOT NULL,
device_label TEXT NOT NULL,
captured_at TIMESTAMPTZ NOT NULL,
capture_duration_ms INT,
ble_rssi INT,
ble_phy TEXT,
validation_status TEXT,
was_offline BOOLEAN NOT NULL DEFAULT false,
sync_latency_ms INT,
clock_offset_ms REAL,
rtt_ms REAL,
meta JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- ---------------------------------------------------------------------------
-- 1.12 result_provenance — device lineage per result (admin-only read)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS result_provenance (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
result_id UUID NOT NULL UNIQUE REFERENCES results(id) ON DELETE CASCADE,
device_id TEXT NOT NULL,
device_label TEXT NOT NULL,
station_id TEXT NOT NULL REFERENCES stations(id),
device_timestamp BIGINT NOT NULL,
hlc_timestamp TEXT,
sync_latency_ms INT,
was_offline BOOLEAN NOT NULL DEFAULT false,
recorded_at TIMESTAMPTZ DEFAULT now()
);
-- ---------------------------------------------------------------------------
-- 1.13 audit_log — append-only compliance log
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS audit_log (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID REFERENCES events(id),
action TEXT NOT NULL,
entity_type TEXT,
entity_id TEXT,
user_id UUID REFERENCES auth.users(id),
old_value JSONB,
new_value JSONB,
ip_address TEXT,
created_at TIMESTAMPTZ DEFAULT now()
);
-- If audit_log already existed in the Recruiting DB, add CE-required columns
ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS event_id UUID REFERENCES events(id);
ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS entity_type TEXT;
ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS entity_id TEXT;
ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS old_value JSONB;
ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS new_value JSONB;
-- =============================================================================
-- PART 2: COLLISION RESOLUTION
-- Resolved using confirmed Apex schema (captured 2026-04-20).
-- =============================================================================
-- ---------------------------------------------------------------------------
-- 2.1 organizations — RESOLVED
--
-- Apex DB has NO organizations table (confirmed). Creating Core Elite version.
-- The ELSE branch handles the edge case where this migration is re-run after
-- organizations was created by a prior partial run.
-- ---------------------------------------------------------------------------
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'organizations'
) THEN
EXECUTE $DDL$
CREATE TABLE organizations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
slug TEXT UNIQUE NOT NULL,
logo_url TEXT,
primary_color TEXT DEFAULT '#18181b',
secondary_color TEXT DEFAULT '#c8a200',
contact_email TEXT,
created_at TIMESTAMPTZ DEFAULT now()
)
$DDL$;
INSERT INTO organizations (id, name, slug)
VALUES (gen_random_uuid(), 'Core Elite', 'core-elite')
ON CONFLICT DO NOTHING;
RAISE NOTICE '2.1: organizations table created (no collision).';
ELSE
-- Re-run path: organizations already created by a prior run of this migration.
-- Idempotently extend with CE columns only.
ALTER TABLE organizations ADD COLUMN IF NOT EXISTS logo_url TEXT;
ALTER TABLE organizations ADD COLUMN IF NOT EXISTS primary_color TEXT DEFAULT '#18181b';
ALTER TABLE organizations ADD COLUMN IF NOT EXISTS secondary_color TEXT DEFAULT '#c8a200';
ALTER TABLE organizations ADD COLUMN IF NOT EXISTS contact_email TEXT;
INSERT INTO organizations (name, slug)
VALUES ('Core Elite', 'core-elite')
ON CONFLICT (slug) DO NOTHING;
RAISE NOTICE '2.1: organizations already exists — extended with CE columns.';
END IF;
END $$;
-- Wire events.organization_id → organizations now that organizations exists
ALTER TABLE events ADD COLUMN IF NOT EXISTS organization_id UUID REFERENCES organizations(id);
-- ---------------------------------------------------------------------------
-- 2.2 profiles — RESOLVED
--
-- Apex DB HAS profiles table with this structure:
-- id UUID PK (auto-generated, NOT the auth.uid() FK)
-- user_id UUID (this is the auth.uid() reference — DIFFERS from CE)
-- display_name TEXT
-- org_id TEXT
-- role TEXT
-- avatar_url TEXT, bio TEXT, created_at, updated_at
--
-- Strategy:
-- A) Do NOT drop the table.
-- B) Extend role CHECK to accept CE values ('admin', 'staff') alongside Apex values.
-- C) Add full_name TEXT (CE reads this) + trigger to sync ↔ display_name.
-- D) Add organization_id UUID FK (CE uses this; Apex uses org_id TEXT).
-- E) RLS policies throughout this migration use user_id = auth.uid()
-- (NOT id = auth.uid()) to match Apex's structural pattern.
-- F) App code update required: RouteGuard.tsx must query profiles by user_id.
-- See MERGE_STRATEGY.md §5.
-- ---------------------------------------------------------------------------
-- Step 2.2a: Widen the role CHECK constraint to include CE roles.
-- Dynamically finds and drops any existing CHECK on profiles.role, then
-- re-adds a permissive set covering both platforms' role values.
DO $$
DECLARE
v_constraint_name TEXT;
BEGIN
-- Find any existing CHECK constraint touching profiles.role
SELECT tc.constraint_name INTO v_constraint_name
FROM information_schema.constraint_column_usage ccu
JOIN information_schema.table_constraints tc
ON tc.constraint_name = ccu.constraint_name
WHERE ccu.table_schema = 'public'
AND ccu.table_name = 'profiles'
AND ccu.column_name = 'role'
AND tc.constraint_type = 'CHECK'
LIMIT 1;
IF v_constraint_name IS NOT NULL THEN
EXECUTE 'ALTER TABLE profiles DROP CONSTRAINT IF EXISTS ' || quote_ident(v_constraint_name);
RAISE NOTICE '2.2: Dropped existing profiles.role CHECK constraint: %', v_constraint_name;
END IF;
-- Add extended CHECK covering Apex recruiting roles + CE combine roles.
-- Additional Apex roles can be added to this list without another migration.
IF NOT EXISTS (
SELECT 1 FROM information_schema.check_constraints
WHERE constraint_schema = 'public'
AND constraint_name = 'profiles_role_apex_ce_check'
) THEN
ALTER TABLE profiles ADD CONSTRAINT profiles_role_apex_ce_check
CHECK (role IN (
'admin', 'staff', -- Core Elite combine roles
'coach', 'scout', 'recruiter', -- Recruiting platform roles
'athlete', 'viewer', 'guest' -- Additional Apex roles
)) NOT VALID;
RAISE NOTICE '2.2: Added permissive profiles_role_apex_ce_check constraint.';
END IF;
END $$;
-- Step 2.2b: Add CE-specific columns to Apex profiles.
-- full_name TEXT — CE code reads profiles.full_name; kept in sync with display_name via trigger.
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS full_name TEXT;
-- organization_id UUID — CE uses UUID FK; Apex uses org_id TEXT. Both coexist.
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS organization_id UUID REFERENCES organizations(id);
-- Step 2.2c: Seed full_name from display_name for existing Apex profiles.
UPDATE profiles
SET full_name = display_name
WHERE full_name IS NULL
AND display_name IS NOT NULL;
-- Step 2.2d: Bidirectional sync trigger — full_name ↔ display_name.
-- CE code writes full_name. Recruiting app reads/writes display_name.
-- BEFORE trigger allows modifying NEW before the row is stored.
CREATE OR REPLACE FUNCTION sync_profile_display_name() RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
IF NEW.full_name IS NOT NULL AND NEW.display_name IS NULL THEN
NEW.display_name := NEW.full_name;
ELSIF NEW.display_name IS NOT NULL AND NEW.full_name IS NULL THEN
NEW.full_name := NEW.display_name;
END IF;
ELSIF TG_OP = 'UPDATE' THEN
-- Only sync the field that actually changed; prevents infinite loop
IF NEW.full_name IS DISTINCT FROM OLD.full_name THEN
NEW.display_name := NEW.full_name;
ELSIF NEW.display_name IS DISTINCT FROM OLD.display_name THEN
NEW.full_name := NEW.display_name;
END IF;
END IF;
RETURN NEW;
END; $$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_sync_profile_display_name ON profiles;
CREATE TRIGGER trg_sync_profile_display_name
BEFORE INSERT OR UPDATE ON profiles
FOR EACH ROW EXECUTE FUNCTION sync_profile_display_name();
-- Step 2.2e: Unique index on profiles.user_id — required for ON CONFLICT in
-- handle_new_user trigger (Part 7) and RLS self-referential subqueries.
CREATE UNIQUE INDEX IF NOT EXISTS ce_idx_profiles_user_id ON profiles (user_id)
WHERE user_id IS NOT NULL;
-- ---------------------------------------------------------------------------
-- 2.3 athletes — RESOLVED
--
-- Apex DB HAS athletes (28 cols, recruiting prospects, no event_id).
-- Strategy: ALTER TABLE to add CE combine-specific columns.
-- Existing Apex athlete rows will have event_id = NULL (they are recruiting
-- prospects, not combine participants — this is correct and expected).
--
-- Column name alignment (Apex already has these — NO rename needed):
-- Apex athletes.height_inches ↔ CE parameter p_height_in
-- Apex athletes.weight_lbs ↔ CE parameter p_weight_lb
-- Apex athletes.graduation_year (not used by register_athlete_secure v5 directly)
-- Apex athletes.high_school ↔ CE athletes.high_school ✓ (same name)
-- ---------------------------------------------------------------------------
-- Core CE tenant isolation key (NULL = recruiting prospect, NOT NULL = combine athlete)
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS event_id UUID REFERENCES events(id);
-- CE registration fields — NULL for existing Apex recruiting prospects
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS date_of_birth DATE;
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS grade TEXT;
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS parent_name TEXT;
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS parent_email TEXT;
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS parent_phone TEXT;
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS band_id TEXT;
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS is_core_elite_verified BOOLEAN DEFAULT false;
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
-- Optional link: combine athlete → recruiting platform user (if the same person)
ALTER TABLE athletes ADD COLUMN IF NOT EXISTS recruiting_profile_id UUID REFERENCES auth.users(id);
-- parent_email format check — IS NULL allows existing Apex rows without email
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.check_constraints
WHERE constraint_schema = 'public'
AND constraint_name = 'athletes_parent_email_format_check'
) THEN
ALTER TABLE athletes ADD CONSTRAINT athletes_parent_email_format_check
CHECK (parent_email IS NULL
OR parent_email ~* '^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$') NOT VALID;
END IF;
END $$;
-- DOB range check — IS NULL allows Apex recruiting athletes without DOB
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.check_constraints
WHERE constraint_schema = 'public'
AND constraint_name = 'athletes_dob_range_check'
) THEN
ALTER TABLE athletes ADD CONSTRAINT athletes_dob_range_check
CHECK (date_of_birth IS NULL
OR (date_of_birth >= DATE '2005-01-01'
AND date_of_birth <= CURRENT_DATE - INTERVAL '9 years')) NOT VALID;
END IF;
END $$;
-- Add FK from athletes.band_id → bands.band_id (deferred — circular reference)
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'fk_athlete_band'
AND table_name = 'athletes'
) THEN
ALTER TABLE athletes ADD CONSTRAINT fk_athlete_band
FOREIGN KEY (band_id) REFERENCES bands(band_id)
DEFERRABLE INITIALLY DEFERRED;
END IF;
END $$;
-- Add FK from bands back to athletes (bands.athlete_id column already exists from Part 1)
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'bands_athlete_id_fkey'
AND table_name = 'bands'
) THEN
ALTER TABLE bands ADD CONSTRAINT bands_athlete_id_fkey
FOREIGN KEY (athlete_id) REFERENCES athletes(id);
END IF;
END $$;
-- Wire FK constraints for all Part 1 tables whose athlete_id column exists
-- but was created without a REFERENCES clause.
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'results_athlete_id_fkey' AND table_name = 'results'
) THEN
ALTER TABLE results ADD CONSTRAINT results_athlete_id_fkey
FOREIGN KEY (athlete_id) REFERENCES athletes(id)
DEFERRABLE INITIALLY DEFERRED;
END IF;
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'waivers_athlete_id_fkey' AND table_name = 'waivers'
) THEN
ALTER TABLE waivers ADD CONSTRAINT waivers_athlete_id_fkey
FOREIGN KEY (athlete_id) REFERENCES athletes(id);
END IF;
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'token_claims_athlete_id_fkey' AND table_name = 'token_claims'
) THEN
ALTER TABLE token_claims ADD CONSTRAINT token_claims_athlete_id_fkey
FOREIGN KEY (athlete_id) REFERENCES athletes(id);
END IF;
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'parent_portals_athlete_id_fkey' AND table_name = 'parent_portals'
) THEN
ALTER TABLE parent_portals ADD CONSTRAINT parent_portals_athlete_id_fkey
FOREIGN KEY (athlete_id) REFERENCES athletes(id);
END IF;
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'report_jobs_athlete_id_fkey' AND table_name = 'report_jobs'
) THEN
ALTER TABLE report_jobs ADD CONSTRAINT report_jobs_athlete_id_fkey
FOREIGN KEY (athlete_id) REFERENCES athletes(id);
END IF;
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'incidents_athlete_id_fkey' AND table_name = 'incidents'
) THEN
ALTER TABLE incidents ADD CONSTRAINT incidents_athlete_id_fkey
FOREIGN KEY (athlete_id) REFERENCES athletes(id);
END IF;
IF NOT EXISTS (
SELECT 1 FROM information_schema.table_constraints
WHERE constraint_name = 'capture_telemetry_athlete_id_fkey' AND table_name = 'capture_telemetry'
) THEN
ALTER TABLE capture_telemetry ADD CONSTRAINT capture_telemetry_athlete_id_fkey
FOREIGN KEY (athlete_id) REFERENCES athletes(id);
END IF;
END $$;
-- CE-specific unique index: one athlete per event by name+DOB (combine dedup guard)
CREATE UNIQUE INDEX IF NOT EXISTS ce_idx_athletes_event_name_dob_unique
ON athletes (event_id, lower(trim(first_name)), lower(trim(last_name)), date_of_birth)
WHERE event_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS ce_idx_athletes_event_email_name_unique
ON athletes (event_id, lower(parent_email), lower(first_name), lower(last_name))
WHERE event_id IS NOT NULL AND parent_email IS NOT NULL;
-- =============================================================================
-- PART 3: RLS POLICIES
-- ⚠️ ALL profiles subqueries use user_id = auth.uid() (NOT id = auth.uid())
-- because Apex profiles.user_id is the auth reference, not profiles.id.
-- =============================================================================
ALTER TABLE events ENABLE ROW LEVEL SECURITY;
ALTER TABLE athletes ENABLE ROW LEVEL SECURITY;
ALTER TABLE bands ENABLE ROW LEVEL SECURITY;
ALTER TABLE stations ENABLE ROW LEVEL SECURITY;
ALTER TABLE results ENABLE ROW LEVEL SECURITY;
ALTER TABLE device_status ENABLE ROW LEVEL SECURITY;
ALTER TABLE waivers ENABLE ROW LEVEL SECURITY;
ALTER TABLE token_claims ENABLE ROW LEVEL SECURITY;
ALTER TABLE parent_portals ENABLE ROW LEVEL SECURITY;
ALTER TABLE report_jobs ENABLE ROW LEVEL SECURITY;
ALTER TABLE incidents ENABLE ROW LEVEL SECURITY;
ALTER TABLE capture_telemetry ENABLE ROW LEVEL SECURITY;
ALTER TABLE result_provenance ENABLE ROW LEVEL SECURITY;
ALTER TABLE audit_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;
-- ── events ───────────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Public Read Events" ON events;
DROP POLICY IF EXISTS "CE Admin Full Access Events" ON events;
DROP POLICY IF EXISTS "CE Org Scoped Events" ON events;
CREATE POLICY "CE Public Read Events"
ON events FOR SELECT USING (true);
CREATE POLICY "CE Admin Full Access Events"
ON events FOR ALL TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
CREATE POLICY "CE Org Scoped Events"
ON events FOR SELECT TO authenticated
USING (
organization_id IS NULL
OR organization_id IN (
SELECT organization_id FROM profiles WHERE user_id = auth.uid()
)
OR EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
)
);
-- ── athletes ─────────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Staff Read Athletes" ON athletes;
DROP POLICY IF EXISTS "CE Admin Full Athletes" ON athletes;
CREATE POLICY "CE Staff Read Athletes"
ON athletes FOR SELECT TO authenticated USING (true);
CREATE POLICY "CE Admin Full Athletes"
ON athletes FOR ALL TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
-- ── results ──────────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Staff Insert Results" ON results;
DROP POLICY IF EXISTS "CE Staff Read Results" ON results;
DROP POLICY IF EXISTS "CE Admin Update Results" ON results;
CREATE POLICY "CE Staff Insert Results"
ON results FOR INSERT TO authenticated WITH CHECK (true);
CREATE POLICY "CE Staff Read Results"
ON results FOR SELECT TO authenticated USING (true);
CREATE POLICY "CE Admin Update Results"
ON results FOR UPDATE TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
-- ── device_status ─────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Staff Device Status" ON device_status;
CREATE POLICY "CE Staff Device Status"
ON device_status FOR ALL TO authenticated USING (true);
-- ── bands ─────────────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Staff Full Bands" ON bands;
DROP POLICY IF EXISTS "CE Public Read Band" ON bands;
DROP POLICY IF EXISTS "CE Public Claim Band" ON bands;
CREATE POLICY "CE Staff Full Bands" ON bands FOR ALL TO authenticated USING (true);
CREATE POLICY "CE Public Read Band" ON bands FOR SELECT USING (true);
CREATE POLICY "CE Public Claim Band" ON bands FOR UPDATE USING (true);
-- ── waivers ──────────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Public Insert Waivers" ON waivers;
DROP POLICY IF EXISTS "CE Staff Read Waivers" ON waivers;
CREATE POLICY "CE Public Insert Waivers" ON waivers FOR INSERT WITH CHECK (true);
CREATE POLICY "CE Staff Read Waivers" ON waivers FOR SELECT TO authenticated USING (true);
-- ── stations ─────────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Staff Read Stations" ON stations;
CREATE POLICY "CE Staff Read Stations"
ON stations FOR SELECT TO authenticated USING (true);
-- ── token_claims ──────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Token Claims All" ON token_claims;
CREATE POLICY "CE Token Claims All" ON token_claims FOR ALL USING (true);
-- ── parent_portals ────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Public Read Portal" ON parent_portals;
CREATE POLICY "CE Public Read Portal" ON parent_portals FOR SELECT USING (true);
-- ── audit_log ─────────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Admin Read Audit" ON audit_log;
CREATE POLICY "CE Admin Read Audit"
ON audit_log FOR SELECT TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
-- ── incidents ─────────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Admin Full Incidents" ON incidents;
DROP POLICY IF EXISTS "CE Staff Read Incidents" ON incidents;
CREATE POLICY "CE Admin Full Incidents"
ON incidents FOR ALL TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
CREATE POLICY "CE Staff Read Incidents"
ON incidents FOR SELECT TO authenticated USING (true);
-- ── report_jobs ───────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Staff Read Report Jobs" ON report_jobs;
CREATE POLICY "CE Staff Read Report Jobs"
ON report_jobs FOR SELECT TO authenticated USING (true);
-- ── organizations ─────────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Public Read Orgs" ON organizations;
DROP POLICY IF EXISTS "CE Admin Manage Orgs" ON organizations;
CREATE POLICY "CE Public Read Orgs"
ON organizations FOR SELECT USING (true);
CREATE POLICY "CE Admin Manage Orgs"
ON organizations FOR ALL TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
-- ── profiles ──────────────────────────────────────────────────────────────────
-- ⚠️ Uses user_id = auth.uid() (Apex structural pattern)
DROP POLICY IF EXISTS "CE Users Read Own Profile" ON profiles;
DROP POLICY IF EXISTS "CE Admin Full Profiles" ON profiles;
CREATE POLICY "CE Users Read Own Profile"
ON profiles FOR SELECT TO authenticated USING (auth.uid() = user_id);
CREATE POLICY "CE Admin Full Profiles"
ON profiles FOR ALL TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
-- ── capture_telemetry ────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Admin Read Telemetry" ON capture_telemetry;
DROP POLICY IF EXISTS "CE Staff Write Telemetry" ON capture_telemetry;
CREATE POLICY "CE Admin Read Telemetry"
ON capture_telemetry FOR SELECT TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
CREATE POLICY "CE Staff Write Telemetry"
ON capture_telemetry FOR INSERT TO authenticated WITH CHECK (true);
-- ── result_provenance ─────────────────────────────────────────────────────────
DROP POLICY IF EXISTS "CE Admin Read Provenance" ON result_provenance;
CREATE POLICY "CE Admin Read Provenance"
ON result_provenance FOR SELECT TO authenticated
USING (EXISTS (
SELECT 1 FROM profiles WHERE user_id = auth.uid() AND role = 'admin'
));
-- =============================================================================
-- PART 4: INDEXES
-- All use IF NOT EXISTS — safe on re-run.
-- =============================================================================
CREATE INDEX IF NOT EXISTS ce_idx_athletes_event_id
ON athletes (event_id) WHERE event_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS ce_idx_athletes_event_deleted
ON athletes (event_id) WHERE deleted_at IS NULL AND event_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS ce_idx_results_athlete_event
ON results (athlete_id, event_id);
CREATE INDEX IF NOT EXISTS ce_idx_results_athlete_drill
ON results (athlete_id, drill_type);
CREATE INDEX IF NOT EXISTS ce_idx_results_hlc_timestamp
ON results (hlc_timestamp);
CREATE INDEX IF NOT EXISTS ce_idx_results_device_ts
ON results (athlete_id, drill_type, device_timestamp DESC);
CREATE INDEX IF NOT EXISTS ce_idx_results_pending_validation
ON results (validation_status) WHERE validation_status = 'extraordinary';
CREATE INDEX IF NOT EXISTS ce_idx_results_session
ON results (session_id) WHERE session_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS ce_idx_results_unverified_ble
ON results (id) WHERE source_type = 'live_ble' AND verification_hash IS NULL;
CREATE INDEX IF NOT EXISTS ce_idx_device_status_event
ON device_status (event_id);
CREATE INDEX IF NOT EXISTS ce_idx_device_status_last_seen
ON device_status (last_seen_at);
CREATE INDEX IF NOT EXISTS ce_idx_parent_portals_token
ON parent_portals (portal_token);
CREATE INDEX IF NOT EXISTS ce_idx_incidents_event
ON incidents (event_id);
CREATE INDEX IF NOT EXISTS ce_idx_capture_telemetry_event
ON capture_telemetry (event_id);
CREATE INDEX IF NOT EXISTS ce_idx_capture_telemetry_lww
ON capture_telemetry (athlete_id, drill_type, event_id, device_timestamp DESC);
CREATE INDEX IF NOT EXISTS ce_idx_audit_entity
ON audit_log (entity_type, entity_id);
CREATE INDEX IF NOT EXISTS ce_idx_audit_event
ON audit_log (event_id);
-- =============================================================================
-- PART 5: RPCs
-- Full bodies injected. Column names use Apex schema where applicable.
-- All use CREATE OR REPLACE — safe re-run.
-- =============================================================================
-- ---------------------------------------------------------------------------
-- 5.1 upsert_device_status_hlc — HLC-guarded heartbeat upsert
-- ---------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION upsert_device_status_hlc(
p_event_id UUID,
p_station_id TEXT,
p_device_label TEXT,
p_last_seen_at TEXT,
p_is_online BOOLEAN,
p_pending_count INT,
p_last_sync_at TEXT,
p_hlc_timestamp TEXT
) RETURNS JSONB
LANGUAGE plpgsql SECURITY DEFINER AS $$
DECLARE
v_current_hlc TEXT;
BEGIN
SELECT hlc_timestamp INTO v_current_hlc
FROM device_status
WHERE event_id = p_event_id
AND station_id = p_station_id
AND device_label = p_device_label;
-- Reject stale write: existing HLC >= incoming means out-of-order offline delivery
IF v_current_hlc IS NOT NULL AND v_current_hlc >= p_hlc_timestamp THEN
RETURN jsonb_build_object('success', true, 'applied', false,
'reason', 'stale_hlc', 'current_hlc', v_current_hlc);
END IF;
INSERT INTO device_status (
event_id, station_id, device_label,
last_seen_at, is_online, pending_queue_count, last_sync_at, hlc_timestamp
) VALUES (
p_event_id, p_station_id, p_device_label,
p_last_seen_at::TIMESTAMPTZ, p_is_online, p_pending_count,
p_last_sync_at::TIMESTAMPTZ, p_hlc_timestamp
)
ON CONFLICT ON CONSTRAINT device_status_unique_identity DO UPDATE SET
last_seen_at = EXCLUDED.last_seen_at,
is_online = EXCLUDED.is_online,