Repository navigation
Expand file tree
/
Copy pathschema.sql
More file actions
7502 lines (6789 loc) · 292 KB
/
Copy pathschema.sql
File metadata and controls
7502 lines (6789 loc) · 292 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
-- ============================================================
-- Poke Notes — Database Schema
-- ============================================================
-- Run this in your new Supabase project SQL editor.
-- Run on dev first, verify, then run on prod.
-- ============================================================
-- ============================================================
-- EXTENSIONS
-- ============================================================
create extension if not exists "pgcrypto"; -- for gen_random_uuid()
create extension if not exists pg_cron;
create schema if not exists extensions;
create extension if not exists pg_net with schema extensions;
-- ============================================================
-- PROFILES
-- Extends auth.users with app-specific user data.
-- One row per user, created automatically on first sign-in.
-- ============================================================
create table public.profiles (
id uuid primary key references auth.users(id) on delete cascade,
display_name text not null default '',
first_name text not null default '',
last_name text not null default '',
email text not null default '',
ptcgl_username text not null default '',
ptcgl_username_aliases text[] not null default '{}',
role text not null default 'user'
check (role in ('user', 'admin')),
avatar_color text not null default 'red',
avatar_path text constraint profiles_avatar_path_owned check (
avatar_path is null or avatar_path ~ ('^' || id::text || '/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.webp$')
),
auth_account_created_at timestamptz,
last_login_at timestamptz,
last_active_at timestamptz,
login_count integer not null default 0,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
comment on table public.profiles is
'App-specific user profile data. Extends auth.users.';
comment on column public.profiles.ptcgl_username is
'The user''s Pokemon TCG Live username. Required for self-player identification during log import.';
comment on column public.profiles.ptcgl_username_aliases is
'Alternate account-owned Pokemon TCG Live usernames accepted for self-player identification.';
comment on column public.profiles.role is
'user = standard access, admin = full admin panel access.';
-- ============================================================
-- DECKS
-- A user's saved deck strategies.
-- ============================================================
create table public.decks (
id text primary key,
user_id uuid not null references auth.users(id) on delete cascade,
-- Core identity
deck_name text not null default '',
archetype_id text not null default '',
format text not null default '',
go_preference text not null default ''
check (go_preference in ('First', 'Second', '')),
-- Pokemon selection (stored as array of slug strings)
deck_pokemon jsonb not null default '[]',
-- Strategy content
core_strategy text not null default '',
general_notes text not null default '',
setup_goals jsonb not null default '[]',
resource_plan text not null default '',
matchups jsonb not null default '[]',
-- Deck lists (array of deck list objects, stored as JSONB
-- because they are complex nested structures with card entries)
deck_lists jsonb not null default '[]',
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
comment on table public.decks is
'User deck strategies. Each deck can have multiple deck lists and matchup plans.';
comment on column public.decks.archetype_id is
'Backend-owned canonical deck archetype key derived from the selected Pokemon slugs.';
comment on column public.decks.matchups is
'Array of matchup plan objects. Each has id, deckName, deckPokemon, and timestamps.';
comment on column public.decks.deck_lists is
'Array of deck list objects. Each has id, name, format, rawList, and parsed card data.';
-- ============================================================
-- DECK LISTS
-- Relational deck-list rows, kept in compatibility with decks.deck_lists.
-- ============================================================
create table public.deck_lists (
id text primary key,
deck_id text not null references public.decks(id) on delete cascade,
user_id uuid not null references auth.users(id) on delete cascade,
name text not null default '',
format text not null default '',
date text not null default '',
created_by text not null default '',
notes text not null default '',
raw_list text not null default '',
parsed_cards jsonb not null default '[]',
sorted_cards jsonb not null default '[]',
sorted_cards_version integer,
position integer not null default 0,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint deck_lists_user_deck_id_unique
unique (user_id, deck_id, id)
);
comment on table public.deck_lists is
'Relational deck-list rows. Kept in compatibility with public.decks.deck_lists during migration.';
comment on column public.deck_lists.position is
'Display order migrated from the previous decks.deck_lists JSON array order.';
-- ============================================================
-- DECK MATCHUPS
-- Relational matchup-note rows, kept in compatibility with decks.matchups.
-- ============================================================
create table public.deck_matchups (
id text primary key,
deck_id text not null references public.decks(id) on delete cascade,
user_id uuid not null references auth.users(id) on delete cascade,
deck_name text not null default '',
deck_pokemon jsonb not null default '[]',
format text not null default '',
go_preference text not null default ''
check (go_preference in ('First', 'Second', '')),
matchup_favor text not null default '',
ideal_bench text not null default '',
techs_needed text not null default '',
matchup_plan text not null default '',
position integer not null default 0,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint deck_matchups_user_deck_id_unique
unique (user_id, deck_id, id)
);
comment on table public.deck_matchups is
'Relational deck matchup-note rows. Kept in compatibility with public.decks.matchups during migration.';
-- ============================================================
-- TOURNAMENTS
-- Tournament runs tied to a deck strategy or a manually tracked deck.
-- ============================================================
create table public.tournaments (
id text primary key,
user_id uuid not null references auth.users(id) on delete cascade,
name text not null default '',
tournament_identifier text not null default '',
location text not null default '',
championship_points integer
check (championship_points is null or championship_points >= 0),
professor_points integer
check (professor_points is null or professor_points >= 0),
date_from date not null,
date_to date not null,
linked_deck_id text references public.decks(id) on delete set null,
linked_deck_list_id text,
deck_name text not null default '',
deck_sprites jsonb not null default '[]',
category text not null default ''
check (category in ('', 'online', 'local', 'challenge', 'cup', 'prerelease', 'regional', 'international', 'world')),
placement text not null default ''
check (placement in ('', 'no placement', 'dropped', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 't1024', 't512', 't256', 't128', 't64', 't32', 't16', 't8', 't4', 'finalist', 'champion')),
participation text not null default 'player'
check (participation in ('player', 'judge')),
judge_role text
check (judge_role in ('judge', 'head judge')),
format text not null default '',
notes text not null default '',
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint tournaments_valid_date_range
check (date_to >= date_from),
constraint tournaments_participation_role_consistency
check (
(participation = 'player' and judge_role is null) or
(participation = 'judge' and judge_role is not null and placement = '')
)
);
comment on table public.tournaments is
'User tournament records. Can link to a saved deck or store a manual deck snapshot.';
comment on column public.tournaments.tournament_identifier is
'Optional organizer-facing Tournament ID, such as a Play! Pokemon event identifier.';
comment on column public.tournaments.location is
'Optional venue, store, city, or online location supplied by the user.';
comment on column public.tournaments.championship_points is
'Optional Championship Points awarded for the tournament.';
comment on column public.tournaments.professor_points is
'Optional Professor Points awarded for judging the tournament.';
comment on column public.tournaments.deck_sprites is
'Array of Pokemon slug strings used for tournament deck display.';
comment on column public.tournaments.linked_deck_list_id is
'References a deck list within linked_deck_id. Not a foreign key as deck lists are stored in JSONB.';
comment on column public.tournaments.participation is
'Whether the account owner attended this event as a player or judge.';
comment on column public.tournaments.judge_role is
'Judge responsibility for judge participation: judge or head judge.';
-- ============================================================
-- TOURNAMENT ROUNDS
-- Individual rounds within a tournament run.
-- ============================================================
create table public.tournament_rounds (
id text primary key,
tournament_id text not null references public.tournaments(id) on delete cascade,
user_id uuid not null references auth.users(id) on delete cascade,
round_number integer not null check (round_number > 0),
opponent_deck_name text not null default '',
opponent_deck_sprites jsonb not null default '[]',
result text not null
check (
result in ('BYE', 'ID', 'NO SHOW') OR
result in ('Win', 'Loss', 'Tie') OR
result ~ '^[WLT]{1,3}$'
),
notes text not null default '',
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint tournament_rounds_unique_round
unique (tournament_id, round_number)
);
comment on table public.tournament_rounds is
'Round-by-round results for a tournament run.';
comment on column public.tournament_rounds.opponent_deck_sprites is
'Array of Pokemon slug strings used for opponent deck display.';
-- ============================================================
-- LOGS
-- Battle logs imported from PTCGL.
-- All filterable/sortable fields are proper columns.
-- The sections JSONB column is write-once at import time.
-- ============================================================
create table public.logs (
id text primary key,
user_id uuid not null references auth.users(id) on delete cascade,
-- Core result data — all used for filtering and stats
date date not null,
result text not null check (result in ('Win', 'Loss')),
format text not null default '',
go_order text not null default ''
check (go_order in ('First', 'Second', '')),
-- Self player (the importing user's side)
self_player_name text not null default '',
self_deck_name text not null default '',
self_deck_slug text not null default '',
self_deck_sprites text not null default '', -- comma-separated slugs
-- Opponent player
opponent_player_name text not null default '',
opponent_deck_name text not null default '',
opponent_deck_slug text not null default '',
opponent_deck_sprites text not null default '', -- comma-separated slugs
-- Game stats — stored at import time, never recomputed
total_turns integer not null default 0,
coin_toss_won boolean, -- null if not determinable
self_prizes_taken integer not null default 0,
opponent_prizes_taken integer not null default 0,
self_attack_damage integer not null default 0,
opponent_attack_damage integer not null default 0,
self_mulligans integer not null default 0,
opponent_mulligans integer not null default 0,
-- Deck linking — both optional, can be null
linked_deck_id text references public.decks(id) on delete set null,
linked_deck_list_id text, -- references deck_lists.id within the deck
-- Game end reason (e.g. 'Concede', 'Prizes', '')
reason text not null default '',
-- Raw and parsed log content — write-once at import
raw_log text not null default '',
sections jsonb not null default '[]',
-- Private owner-authored annotation, normalized at the database boundary
match_notes text,
-- Full text search vector — updated by trigger
search_vector tsvector,
imported_at timestamptz not null default now(),
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint logs_match_notes_normalized
check (
match_notes is null
or (
match_notes = btrim(match_notes, E' \t\n\r')
and length(match_notes) > 0
)
)
);
comment on table public.logs is
'Battle logs imported from PTCGL. All stats columns are populated at import and never recomputed.';
comment on column public.logs.sections is
'Parsed turn-by-turn log sections. Write-once at import. Never updated after creation.';
comment on column public.logs.self_deck_sprites is
'Comma-separated Pokemon slug strings for sprite display. E.g. "dragapult,dusknoir"';
comment on column public.logs.coin_toss_won is
'Whether the self player won the opening coin toss. Null if not determinable from the log.';
comment on column public.logs.linked_deck_list_id is
'References a deck list within linked_deck_id. Not a foreign key as deck lists are stored in JSONB.';
comment on column public.logs.match_notes is
'Private owner-authored notes. Null means no note; non-null values are trimmed and non-empty.';
create table public.user_log_stats (
user_id uuid primary key references auth.users(id) on delete cascade,
games_played bigint not null default 0,
games_won bigint not null default 0,
games_lost bigint not null default 0,
attack_damage bigint not null default 0,
opponent_attack_damage bigint not null default 0,
coin_flips_won bigint not null default 0,
coin_flips_lost bigint not null default 0,
mulligans_taken bigint not null default 0,
prizes_taken bigint not null default 0,
tracked_damage bigint not null default 0,
tracked_prizes bigint not null default 0,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
comment on table public.user_log_stats is
'Per-user stats totals maintained from log changes. refresh_user_log_stats rebuilds totals for verification and recovery.';
create table if not exists public.deck_log_stats (
user_id uuid not null references auth.users(id) on delete cascade,
deck_id text not null references public.decks(id) on delete cascade,
games_played bigint not null default 0,
games_won bigint not null default 0,
games_lost bigint not null default 0,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
primary key (user_id, deck_id)
);
comment on table public.deck_log_stats is
'Per-deck linked-log rollup for the deck index. Updated whenever linked log records change.';
create table if not exists public.user_archetype_matchup_stats (
user_id uuid not null references auth.users(id) on delete cascade,
matchup_key text not null,
opponent_deck_name text not null default '',
opponent_deck_sprites text not null default '',
source_deck_slugs text not null default '',
games_played bigint not null default 0,
games_won bigint not null default 0,
games_lost bigint not null default 0,
last_played_date date,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
primary key (user_id, matchup_key)
);
comment on table public.user_archetype_matchup_stats is
'Per-user opponent archetype matchup rollup for the stats page. Grouped by visible archetype identity, not raw detector slug.';
comment on column public.user_archetype_matchup_stats.matchup_key is
'Stable visible matchup key. Prefers opponent sprites, then display name, then raw slug.';
comment on column public.user_archetype_matchup_stats.source_deck_slugs is
'Comma-separated raw opponent_deck_slug values that contributed to this visible matchup row.';
create or replace function public.refresh_user_log_stats(target_user_id uuid)
returns void
language plpgsql
security definer
set search_path = public
as $$
begin
if target_user_id is null then
return;
end if;
-- A fresh snapshot after the lock sees the preceding committed log mutation.
-- Without serialization, a waiting upsert can overwrite totals it read earlier.
perform pg_catalog.pg_advisory_xact_lock(
pg_catalog.hashtextextended('user_log_stats:' || target_user_id::text, 0)
);
insert into public.user_log_stats (
user_id,
games_played,
games_won,
games_lost,
attack_damage,
opponent_attack_damage,
coin_flips_won,
coin_flips_lost,
mulligans_taken,
prizes_taken,
tracked_damage,
tracked_prizes
)
select
target_user_id,
count(*)::bigint as games_played,
count(*) filter (where result = 'Win')::bigint as games_won,
count(*) filter (where result = 'Loss')::bigint as games_lost,
coalesce(sum(self_attack_damage), 0)::bigint as attack_damage,
coalesce(sum(opponent_attack_damage), 0)::bigint as opponent_attack_damage,
count(*) filter (where coin_toss_won is true)::bigint as coin_flips_won,
count(*) filter (where coin_toss_won is false)::bigint as coin_flips_lost,
coalesce(sum(self_mulligans), 0)::bigint as mulligans_taken,
coalesce(sum(self_prizes_taken), 0)::bigint as prizes_taken,
coalesce(sum(self_attack_damage + opponent_attack_damage), 0)::bigint as tracked_damage,
coalesce(sum(self_prizes_taken + opponent_prizes_taken), 0)::bigint as tracked_prizes
from public.logs
where user_id = target_user_id
on conflict (user_id) do update
set games_played = excluded.games_played,
games_won = excluded.games_won,
games_lost = excluded.games_lost,
attack_damage = excluded.attack_damage,
opponent_attack_damage = excluded.opponent_attack_damage,
coin_flips_won = excluded.coin_flips_won,
coin_flips_lost = excluded.coin_flips_lost,
mulligans_taken = excluded.mulligans_taken,
prizes_taken = excluded.prizes_taken,
tracked_damage = excluded.tracked_damage,
tracked_prizes = excluded.tracked_prizes,
updated_at = now();
end;
$$;
create or replace function public.refresh_deck_log_stats(
target_user_id uuid,
target_deck_id text
)
returns void
language plpgsql
security definer
set search_path = public
as $$
declare
next_games_played bigint;
next_games_won bigint;
next_games_lost bigint;
begin
if target_user_id is null or nullif(target_deck_id, '') is null then
return;
end if;
if not exists (
select 1
from public.decks d
where d.id = target_deck_id
and d.user_id = target_user_id
) then
delete from public.deck_log_stats
where user_id = target_user_id
and deck_id = target_deck_id;
return;
end if;
select
count(*)::bigint,
count(*) filter (where result = 'Win')::bigint,
count(*) filter (where result = 'Loss')::bigint
into next_games_played, next_games_won, next_games_lost
from public.logs
where user_id = target_user_id
and linked_deck_id = target_deck_id;
if coalesce(next_games_played, 0) = 0 then
delete from public.deck_log_stats
where user_id = target_user_id
and deck_id = target_deck_id;
return;
end if;
insert into public.deck_log_stats (
user_id,
deck_id,
games_played,
games_won,
games_lost
)
values (
target_user_id,
target_deck_id,
next_games_played,
coalesce(next_games_won, 0),
coalesce(next_games_lost, 0)
)
on conflict (user_id, deck_id) do update
set games_played = excluded.games_played,
games_won = excluded.games_won,
games_lost = excluded.games_lost,
updated_at = now();
end;
$$;
create or replace function public.sync_deck_log_stats_from_log_row()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
begin
if tg_op = 'DELETE' then
perform public.refresh_deck_log_stats(old.user_id, old.linked_deck_id);
return old;
end if;
perform public.refresh_deck_log_stats(new.user_id, new.linked_deck_id);
if tg_op = 'UPDATE' and (
old.user_id is distinct from new.user_id or
old.linked_deck_id is distinct from new.linked_deck_id
) then
perform public.refresh_deck_log_stats(old.user_id, old.linked_deck_id);
end if;
return new;
end;
$$;
revoke all on function public.refresh_deck_log_stats(uuid, text) from public;
revoke all on function public.refresh_deck_log_stats(uuid, text) from anon;
revoke all on function public.refresh_deck_log_stats(uuid, text) from authenticated;
revoke all on function public.sync_deck_log_stats_from_log_row() from public;
revoke all on function public.sync_deck_log_stats_from_log_row() from anon;
revoke all on function public.sync_deck_log_stats_from_log_row() from authenticated;
create or replace function public.get_archetype_matchup_key(
target_opponent_deck_slug text,
target_opponent_deck_name text,
target_opponent_deck_sprites text
)
returns text
language sql
immutable
set search_path = public
as $$
select coalesce(
nullif(trim(coalesce(target_opponent_deck_sprites, '')), ''),
nullif(trim(coalesce(target_opponent_deck_name, '')), ''),
nullif(trim(coalesce(target_opponent_deck_slug, '')), '')
);
$$;
create or replace function public.refresh_user_archetype_matchup_stats(
target_user_id uuid,
target_matchup_key text
)
returns void
language plpgsql
security definer
set search_path = public
as $$
declare
normalized_key text := nullif(trim(coalesce(target_matchup_key, '')), '');
next_games_played bigint;
next_games_won bigint;
next_games_lost bigint;
next_opponent_deck_name text;
next_opponent_deck_sprites text;
next_source_deck_slugs text;
next_last_played_date date;
begin
if target_user_id is null or normalized_key is null then
return;
end if;
select
count(*)::bigint,
count(*) filter (where result = 'Win')::bigint,
count(*) filter (where result = 'Loss')::bigint,
coalesce((array_agg(opponent_deck_name order by date desc, imported_at desc, id desc))[1], '')::text,
coalesce((array_agg(opponent_deck_sprites order by date desc, imported_at desc, id desc))[1], '')::text,
coalesce(string_agg(distinct nullif(trim(opponent_deck_slug), ''), ',' order by nullif(trim(opponent_deck_slug), '')), '')::text,
max(date)
into
next_games_played,
next_games_won,
next_games_lost,
next_opponent_deck_name,
next_opponent_deck_sprites,
next_source_deck_slugs,
next_last_played_date
from public.logs
where user_id = target_user_id
and public.get_archetype_matchup_key(
opponent_deck_slug,
opponent_deck_name,
opponent_deck_sprites
) = normalized_key;
if coalesce(next_games_played, 0) = 0 then
delete from public.user_archetype_matchup_stats
where user_id = target_user_id
and matchup_key = normalized_key;
return;
end if;
insert into public.user_archetype_matchup_stats (
user_id,
matchup_key,
opponent_deck_name,
opponent_deck_sprites,
source_deck_slugs,
games_played,
games_won,
games_lost,
last_played_date
)
values (
target_user_id,
normalized_key,
next_opponent_deck_name,
next_opponent_deck_sprites,
next_source_deck_slugs,
next_games_played,
coalesce(next_games_won, 0),
coalesce(next_games_lost, 0),
next_last_played_date
)
on conflict (user_id, matchup_key) do update
set opponent_deck_name = excluded.opponent_deck_name,
opponent_deck_sprites = excluded.opponent_deck_sprites,
source_deck_slugs = excluded.source_deck_slugs,
games_played = excluded.games_played,
games_won = excluded.games_won,
games_lost = excluded.games_lost,
last_played_date = excluded.last_played_date,
updated_at = now();
end;
$$;
create or replace function public.sync_user_archetype_matchup_stats_from_log_row()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
begin
if tg_op = 'DELETE' then
perform public.refresh_user_archetype_matchup_stats(
old.user_id,
public.get_archetype_matchup_key(old.opponent_deck_slug, old.opponent_deck_name, old.opponent_deck_sprites)
);
return old;
end if;
perform public.refresh_user_archetype_matchup_stats(
new.user_id,
public.get_archetype_matchup_key(new.opponent_deck_slug, new.opponent_deck_name, new.opponent_deck_sprites)
);
if tg_op = 'UPDATE' and (
old.user_id is distinct from new.user_id or
public.get_archetype_matchup_key(old.opponent_deck_slug, old.opponent_deck_name, old.opponent_deck_sprites)
is distinct from public.get_archetype_matchup_key(new.opponent_deck_slug, new.opponent_deck_name, new.opponent_deck_sprites)
) then
perform public.refresh_user_archetype_matchup_stats(
old.user_id,
public.get_archetype_matchup_key(old.opponent_deck_slug, old.opponent_deck_name, old.opponent_deck_sprites)
);
end if;
return new;
end;
$$;
revoke all on function public.get_archetype_matchup_key(text, text, text) from public;
revoke all on function public.get_archetype_matchup_key(text, text, text) from anon;
revoke all on function public.get_archetype_matchup_key(text, text, text) from authenticated;
revoke all on function public.refresh_user_archetype_matchup_stats(uuid, text) from public;
revoke all on function public.refresh_user_archetype_matchup_stats(uuid, text) from anon;
revoke all on function public.refresh_user_archetype_matchup_stats(uuid, text) from authenticated;
revoke all on function public.sync_user_archetype_matchup_stats_from_log_row() from public;
revoke all on function public.sync_user_archetype_matchup_stats_from_log_row() from anon;
revoke all on function public.sync_user_archetype_matchup_stats_from_log_row() from authenticated;
drop trigger if exists refresh_deck_log_stats_after_insert on public.logs;
create trigger refresh_deck_log_stats_after_insert
after insert on public.logs
for each row execute function public.sync_deck_log_stats_from_log_row();
drop trigger if exists refresh_deck_log_stats_after_delete on public.logs;
create trigger refresh_deck_log_stats_after_delete
after delete on public.logs
for each row execute function public.sync_deck_log_stats_from_log_row();
drop trigger if exists refresh_deck_log_stats_after_link_update on public.logs;
create trigger refresh_deck_log_stats_after_link_update
after update of user_id, result, linked_deck_id on public.logs
for each row execute function public.sync_deck_log_stats_from_log_row();
drop trigger if exists refresh_user_archetype_matchup_stats_after_insert on public.logs;
create trigger refresh_user_archetype_matchup_stats_after_insert
after insert on public.logs
for each row execute function public.sync_user_archetype_matchup_stats_from_log_row();
drop trigger if exists refresh_user_archetype_matchup_stats_after_delete on public.logs;
create trigger refresh_user_archetype_matchup_stats_after_delete
after delete on public.logs
for each row execute function public.sync_user_archetype_matchup_stats_from_log_row();
drop trigger if exists refresh_user_archetype_matchup_stats_after_matchup_update on public.logs;
create trigger refresh_user_archetype_matchup_stats_after_matchup_update
after update of user_id, result, date, opponent_deck_slug, opponent_deck_name, opponent_deck_sprites
on public.logs
for each row execute function public.sync_user_archetype_matchup_stats_from_log_row();
create or replace function public.get_log_stats_overview()
returns table (
games_played bigint,
games_won bigint,
games_lost bigint,
attack_damage bigint,
opponent_attack_damage bigint,
coin_flips_won bigint,
coin_flips_lost bigint,
mulligans_taken bigint,
prizes_taken bigint,
tracked_damage bigint,
tracked_prizes bigint
)
language sql
security invoker
set search_path = public
as $$
select
coalesce(stats.games_played, 0)::bigint as games_played,
coalesce(stats.games_won, 0)::bigint as games_won,
coalesce(stats.games_lost, 0)::bigint as games_lost,
coalesce(stats.attack_damage, 0)::bigint as attack_damage,
coalesce(stats.opponent_attack_damage, 0)::bigint as opponent_attack_damage,
coalesce(stats.coin_flips_won, 0)::bigint as coin_flips_won,
coalesce(stats.coin_flips_lost, 0)::bigint as coin_flips_lost,
coalesce(stats.mulligans_taken, 0)::bigint as mulligans_taken,
coalesce(stats.prizes_taken, 0)::bigint as prizes_taken,
coalesce(stats.tracked_damage, 0)::bigint as tracked_damage,
coalesce(stats.tracked_prizes, 0)::bigint as tracked_prizes
from (select auth.uid() as user_id) user_scope
left join public.user_log_stats stats
on stats.user_id = user_scope.user_id;
$$;
create or replace function public.get_admin_dashboard_overview()
returns table (
user_count bigint,
admin_count bigint,
pokemon_catalog_count bigint,
archetype_catalog_count bigint,
excluded_archetype_count bigint,
pokemon_last_synced_at timestamptz,
archetype_last_synced_at timestamptz
)
language plpgsql
security definer
set search_path = public
as $$
begin
if auth.uid() is null or not exists (
select 1
from public.profiles
where id = auth.uid()
and role = 'admin'
) then
raise exception 'Not authorized' using errcode = '42501';
end if;
return query
select
(select count(*) from public.profiles)::bigint as user_count,
(select count(*) from public.profiles where role = 'admin')::bigint as admin_count,
(select count(*) from public.pokemon_catalog)::bigint as pokemon_catalog_count,
(select count(*) from public.archetype_catalog)::bigint as archetype_catalog_count,
(select count(*) from public.archetype_catalog where is_excluded = true)::bigint as excluded_archetype_count,
(select max(last_synced_at) from public.pokemon_catalog) as pokemon_last_synced_at,
(select max(last_synced_at) from public.archetype_catalog) as archetype_last_synced_at;
end;
$$;
create or replace function public.get_deck_index()
returns table (
id text,
user_id uuid,
deck_name text,
archetype_id text,
format text,
go_preference text,
deck_pokemon jsonb,
deck_list_count integer,
created_at timestamptz,
updated_at timestamptz
)
language sql
stable
security invoker
set search_path = public
as $$
select
d.id,
d.user_id,
d.deck_name,
d.archetype_id,
d.format,
d.go_preference,
d.deck_pokemon,
greatest(
(
select count(*)::integer
from public.deck_lists dl
where dl.user_id = d.user_id
and dl.deck_id = d.id
),
case
when jsonb_typeof(d.deck_lists) = 'array' then jsonb_array_length(d.deck_lists)
else 0
end
) as deck_list_count,
d.created_at,
d.updated_at
from public.decks d
where d.user_id = auth.uid()
order by d.updated_at desc;
$$;
create or replace function public.get_deck_index_page_data()
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
with request_context as (
select (select auth.uid()) as user_id
)
select coalesce(
jsonb_agg(
jsonb_build_object(
'id', decks.id,
'user_id', decks.user_id,
'deck_name', decks.deck_name,
'archetype_id', decks.archetype_id,
'format', decks.format,
'go_preference', decks.go_preference,
'deck_pokemon', decks.deck_pokemon,
'deck_list_count', greatest(
(
select count(*)::integer
from public.deck_lists
where deck_lists.user_id = decks.user_id
and deck_lists.deck_id = decks.id
),
case
when jsonb_typeof(decks.deck_lists) = 'array' then jsonb_array_length(decks.deck_lists)
else 0
end
),
'games_played', coalesce(deck_log_stats.games_played, 0),
'games_won', coalesce(deck_log_stats.games_won, 0),
'games_lost', coalesce(deck_log_stats.games_lost, 0),
'created_at', decks.created_at,
'updated_at', decks.updated_at
)
order by decks.updated_at desc
),
'[]'::jsonb
)
from public.decks
cross join request_context
left join public.deck_log_stats
on deck_log_stats.user_id = request_context.user_id
and deck_log_stats.deck_id = decks.id
where decks.user_id = request_context.user_id;
$$;
revoke execute on function public.get_deck_index_page_data() from public, anon;
grant execute on function public.get_deck_index_page_data() to authenticated;
create or replace function public.get_deck_index_stats(target_deck_ids text[])
returns table (
deck_id text,
total bigint,
wins bigint,
losses bigint
)
language sql
stable
security invoker
set search_path = public
as $$
select
s.deck_id,
s.games_played as total,
s.games_won as wins,
s.games_lost as losses
from public.deck_log_stats s
where s.user_id = auth.uid()
and s.deck_id = any(target_deck_ids);
$$;
revoke all on function public.get_admin_dashboard_overview() from public;
grant execute on function public.get_admin_dashboard_overview() to authenticated;
revoke all on function public.get_deck_index_stats(text[]) from public;
grant execute on function public.get_deck_index_stats(text[]) to authenticated;
-- ============================================================
-- LOG SHARES
-- Snapshot shares of battle logs for public viewing.
-- Snapshots are immutable — changes to the original log
-- do not affect existing shares.
-- ============================================================
create table public.log_shares (
id text primary key, -- cryptographically random URL-safe token
owner_user_id uuid not null references auth.users(id) on delete cascade,
source_log_id text,
-- Full snapshot of the log at time of sharing
-- Includes all log fields plus resolved deck list if linked
payload jsonb not null,
expires_at timestamptz not null default (now() + interval '30 days'),
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
comment on table public.log_shares is
'Public share tokens for battle logs. Payload is a full snapshot taken at share time.';
comment on column public.log_shares.id is
'Share token. Must be cryptographically random and never sequential.';
comment on column public.log_shares.source_log_id is
'Source battle log ID for owner-side share management. Nullable for legacy rows created before this column existed.';
comment on column public.log_shares.payload is
'Complete snapshot of the log including all fields and resolved deck list. Immutable after creation.';
-- ============================================================
-- POKEMON CATALOG
-- Master list of all Pokemon with slugs, stages, evolution
-- chains, and localised names.
-- Populated and refreshed by the catalog sync cron job.
-- Replaces the bundled pokedex-catalog.js and pokemon-stages.js files.
-- ============================================================
create table public.pokemon_catalog (
slug text primary key, -- e.g. "dragapult", "dialga-origin"
label text not null, -- e.g. "Dragapult", "Origin Forme Dialga"
national_dex integer,
stage text not null default 'Basic'
check (stage in ('Basic', 'Stage 1', 'Stage 2')),
evolves_from text references public.pokemon_catalog(slug) on delete set null,
sprite_url text not null default '',
-- Localised names for non-English log identification
name_de text,
name_es text,
name_fr text,
name_it text,
name_pt_br text,
last_synced_at timestamptz not null default now()
);
comment on table public.pokemon_catalog is
'Master Pokemon catalog. Refreshed daily from PokéAPI and Limitless. Replaces bundled JS files.';
comment on column public.pokemon_catalog.evolves_from is
'Slug of the pre-evolution. Used by archetype identification to match pre-evolutions as evidence of their final form.';