mirror of
https://github.com/jcreek/LivingDexTracker.git
synced 2026-07-12 18:43:45 +00:00
chore(*): Clean up migration artifacts and optimize data repository queries
This commit is contained in:
@@ -59,10 +59,6 @@
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// if (strippedPokedexNumber == '869') {
|
|
||||||
// console.log(sanitisedPokemonName, sanitisedForm);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// If the form is contained in the identifier, use that
|
// If the form is contained in the identifier, use that
|
||||||
if (
|
if (
|
||||||
pokeApiPokemon.find(
|
pokeApiPokemon.find(
|
||||||
|
|||||||
@@ -10,10 +10,11 @@
|
|||||||
export let showForms: boolean;
|
export let showForms: boolean;
|
||||||
export let showShiny: boolean;
|
export let showShiny: boolean;
|
||||||
|
|
||||||
// Create a working copy for editing
|
// Create a default catch record if none exists
|
||||||
$: workingCatchRecord = catchRecord || {
|
$: if (!catchRecord) {
|
||||||
_id: `temp-${Date.now()}-${pokedexEntry._id}`, // Generate temporary ID
|
catchRecord = {
|
||||||
userId: '', // TODO: Get from session context
|
_id: '', // Empty string, not temp ID - will be created by server
|
||||||
|
userId: '',
|
||||||
pokedexEntryId: pokedexEntry._id,
|
pokedexEntryId: pokedexEntry._id,
|
||||||
haveToEvolve: false,
|
haveToEvolve: false,
|
||||||
caught: false,
|
caught: false,
|
||||||
@@ -21,11 +22,12 @@
|
|||||||
hasGigantamaxed: false,
|
hasGigantamaxed: false,
|
||||||
personalNotes: ''
|
personalNotes: ''
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const dispatch = createEventDispatcher();
|
const dispatch = createEventDispatcher();
|
||||||
|
|
||||||
function updateCatchRecord() {
|
function updateCatchRecord() {
|
||||||
dispatch('updateCatch', { pokedexEntry, catchRecord: workingCatchRecord });
|
dispatch('updateCatch', { pokedexEntry, catchRecord });
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -87,7 +89,7 @@
|
|||||||
<span class="block font-bold mr-2">Caught:</span>
|
<span class="block font-bold mr-2">Caught:</span>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
bind:checked={workingCatchRecord.caught}
|
bind:checked={catchRecord.caught}
|
||||||
class="checkbox checkbox-primary border-black"
|
class="checkbox checkbox-primary border-black"
|
||||||
on:change={updateCatchRecord}
|
on:change={updateCatchRecord}
|
||||||
/>
|
/>
|
||||||
@@ -100,7 +102,7 @@
|
|||||||
<span class="block font-bold mr-2">Needs to evolve:</span>
|
<span class="block font-bold mr-2">Needs to evolve:</span>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
bind:checked={workingCatchRecord.haveToEvolve}
|
bind:checked={catchRecord.haveToEvolve}
|
||||||
class="checkbox checkbox-primary border-black"
|
class="checkbox checkbox-primary border-black"
|
||||||
on:change={updateCatchRecord}
|
on:change={updateCatchRecord}
|
||||||
/>
|
/>
|
||||||
@@ -113,7 +115,7 @@
|
|||||||
<span class="block font-bold mr-2">In home:</span>
|
<span class="block font-bold mr-2">In home:</span>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
bind:checked={workingCatchRecord.inHome}
|
bind:checked={catchRecord.inHome}
|
||||||
class="checkbox checkbox-primary border-black"
|
class="checkbox checkbox-primary border-black"
|
||||||
on:change={updateCatchRecord}
|
on:change={updateCatchRecord}
|
||||||
/>
|
/>
|
||||||
@@ -127,7 +129,7 @@
|
|||||||
<span class="block font-bold mr-2">Has Gigantamaxed:</span>
|
<span class="block font-bold mr-2">Has Gigantamaxed:</span>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
bind:checked={workingCatchRecord.hasGigantamaxed}
|
bind:checked={catchRecord.hasGigantamaxed}
|
||||||
class="checkbox checkbox-primary border-black"
|
class="checkbox checkbox-primary border-black"
|
||||||
on:change={updateCatchRecord}
|
on:change={updateCatchRecord}
|
||||||
/>
|
/>
|
||||||
@@ -141,7 +143,7 @@
|
|||||||
for={`personalNotesInput-${catchRecord?._id || pokedexEntry._id}`}>Notes:</label
|
for={`personalNotesInput-${catchRecord?._id || pokedexEntry._id}`}>Notes:</label
|
||||||
>
|
>
|
||||||
<textarea
|
<textarea
|
||||||
bind:value={workingCatchRecord.personalNotes}
|
bind:value={catchRecord.personalNotes}
|
||||||
id={`personalNotesInput-${catchRecord?._id || pokedexEntry._id}`}
|
id={`personalNotesInput-${catchRecord?._id || pokedexEntry._id}`}
|
||||||
class="form-textarea w-full p-2 border rounded"
|
class="form-textarea w-full p-2 border rounded"
|
||||||
on:change={updateCatchRecord}
|
on:change={updateCatchRecord}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
export let failedToLoad = false;
|
export let failedToLoad = false;
|
||||||
export let updateACatch = (event: any) => {};
|
export let updateACatch = (event: any) => {};
|
||||||
export let createCatchRecords = () => {};
|
export let createCatchRecords = () => {};
|
||||||
|
export let userId: string | null = null;
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<main class="flex-1 p-4 w-full">
|
<main class="flex-1 p-4 w-full">
|
||||||
|
|||||||
@@ -54,10 +54,7 @@ class CombinedDataRepository {
|
|||||||
region: string = '',
|
region: string = '',
|
||||||
game: string = ''
|
game: string = ''
|
||||||
): Promise<CombinedData[]> {
|
): Promise<CombinedData[]> {
|
||||||
let query = this.supabase.from('pokedex_entries').select(`
|
let query = this.supabase.from('pokedex_entries').select('*');
|
||||||
*,
|
|
||||||
catch_records(*)
|
|
||||||
`);
|
|
||||||
|
|
||||||
// Apply filters
|
// Apply filters
|
||||||
if (!enableForms) {
|
if (!enableForms) {
|
||||||
@@ -85,18 +82,36 @@ class CombinedDataRepository {
|
|||||||
.order('boxPlacementColumn', { ascending: true });
|
.order('boxPlacementColumn', { ascending: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { data, error } = await query;
|
const { data: entries, error: entriesError } = await query;
|
||||||
|
|
||||||
if (error) {
|
if (entriesError) {
|
||||||
console.error('Error finding combined data:', error);
|
console.error('Error finding combined data:', entriesError);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transform the data and filter catch records by user
|
if (!entries || entries.length === 0) {
|
||||||
return (data || []).map((entry) => {
|
return [];
|
||||||
const userCatchRecord = Array.isArray(entry.catch_records)
|
}
|
||||||
? entry.catch_records.find((record: CatchRecordDB) => record.userId === userId)
|
|
||||||
: null;
|
// Get catch records for all entries
|
||||||
|
let catchRecords: CatchRecordDB[] = [];
|
||||||
|
if (userId) {
|
||||||
|
const entryIds = entries.map((entry) => entry.id);
|
||||||
|
const { data: records, error: recordsError } = await this.supabase
|
||||||
|
.from('catch_records')
|
||||||
|
.select('*')
|
||||||
|
.eq('userId', userId)
|
||||||
|
.in('pokedexEntryId', entryIds);
|
||||||
|
|
||||||
|
if (!recordsError && records) {
|
||||||
|
catchRecords = records;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Combine the data exactly like master branch
|
||||||
|
return entries.map((entry) => {
|
||||||
|
const userCatchRecord =
|
||||||
|
catchRecords.find((record) => record.pokedexEntryId === entry.id) || null;
|
||||||
|
|
||||||
const transformedEntry = this.transformPokedexEntry(entry);
|
const transformedEntry = this.transformPokedexEntry(entry);
|
||||||
const transformedCatchRecord = userCatchRecord
|
const transformedCatchRecord = userCatchRecord
|
||||||
@@ -121,15 +136,7 @@ class CombinedDataRepository {
|
|||||||
const from = (page - 1) * limit;
|
const from = (page - 1) * limit;
|
||||||
const to = from + limit - 1;
|
const to = from + limit - 1;
|
||||||
|
|
||||||
let query = this.supabase
|
let query = this.supabase.from('pokedex_entries').select('*').range(from, to);
|
||||||
.from('pokedex_entries')
|
|
||||||
.select(
|
|
||||||
`
|
|
||||||
*,
|
|
||||||
catch_records(*)
|
|
||||||
`
|
|
||||||
)
|
|
||||||
.range(from, to);
|
|
||||||
|
|
||||||
// Apply filters
|
// Apply filters
|
||||||
if (!enableForms) {
|
if (!enableForms) {
|
||||||
@@ -157,18 +164,36 @@ class CombinedDataRepository {
|
|||||||
.order('boxPlacementColumn', { ascending: true });
|
.order('boxPlacementColumn', { ascending: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { data, error } = await query;
|
const { data: entries, error: entriesError } = await query;
|
||||||
|
|
||||||
if (error) {
|
if (entriesError) {
|
||||||
console.error('Error finding paginated combined data:', error);
|
console.error('Error finding paginated combined data:', entriesError);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transform the data and filter catch records by user
|
if (!entries || entries.length === 0) {
|
||||||
return (data || []).map((entry) => {
|
return [];
|
||||||
const userCatchRecord = Array.isArray(entry.catch_records)
|
}
|
||||||
? entry.catch_records.find((record: CatchRecordDB) => record.userId === userId)
|
|
||||||
: null;
|
// Get catch records for these entries
|
||||||
|
let catchRecords: CatchRecordDB[] = [];
|
||||||
|
if (userId) {
|
||||||
|
const entryIds = entries.map((entry) => entry.id);
|
||||||
|
const { data: records, error: recordsError } = await this.supabase
|
||||||
|
.from('catch_records')
|
||||||
|
.select('*')
|
||||||
|
.eq('userId', userId)
|
||||||
|
.in('pokedexEntryId', entryIds);
|
||||||
|
|
||||||
|
if (!recordsError && records) {
|
||||||
|
catchRecords = records;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Combine the data exactly like master branch
|
||||||
|
return entries.map((entry) => {
|
||||||
|
const userCatchRecord =
|
||||||
|
catchRecords.find((record) => record.pokedexEntryId === entry.id) || null;
|
||||||
|
|
||||||
const transformedEntry = this.transformPokedexEntry(entry);
|
const transformedEntry = this.transformPokedexEntry(entry);
|
||||||
const transformedCatchRecord = userCatchRecord
|
const transformedCatchRecord = userCatchRecord
|
||||||
|
|||||||
@@ -99,7 +99,6 @@
|
|||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Use enhanced fetch that includes authentication context
|
|
||||||
const response = await fetch('/api/catch-records', requestOptions);
|
const response = await fetch('/api/catch-records', requestOptions);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorText = await response.text();
|
const errorText = await response.text();
|
||||||
@@ -107,6 +106,9 @@
|
|||||||
alert('Failed to update catch record');
|
alert('Failed to update catch record');
|
||||||
throw new Error('Failed to update catch record');
|
throw new Error('Failed to update catch record');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Refresh the data to reflect changes from server
|
||||||
|
await getData(false);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error updating catch record:', error);
|
console.error('Error updating catch record:', error);
|
||||||
}
|
}
|
||||||
@@ -226,13 +228,11 @@
|
|||||||
|
|
||||||
const createdRecords = await response.json();
|
const createdRecords = await response.json();
|
||||||
totalRecordsCreated += createdRecords.length;
|
totalRecordsCreated += createdRecords.length;
|
||||||
console.log(`Created ${createdRecords.length} catch records`);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating catch records:', error);
|
console.error('Error creating catch records:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Created catch records for each pokedex entry');
|
|
||||||
creatingRecords = false;
|
creatingRecords = false;
|
||||||
failedToLoad = false;
|
failedToLoad = false;
|
||||||
await getData();
|
await getData();
|
||||||
@@ -292,6 +292,7 @@
|
|||||||
bind:creatingRecords
|
bind:creatingRecords
|
||||||
bind:totalRecordsCreated
|
bind:totalRecordsCreated
|
||||||
bind:failedToLoad
|
bind:failedToLoad
|
||||||
|
userId={localUser?.id}
|
||||||
{updateACatch}
|
{updateACatch}
|
||||||
{createCatchRecords}
|
{createCatchRecords}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -16,18 +16,22 @@
|
|||||||
onDestroy(unsubscribe);
|
onDestroy(unsubscribe);
|
||||||
|
|
||||||
async function getUser() {
|
async function getUser() {
|
||||||
|
try {
|
||||||
const {
|
const {
|
||||||
data: { session }
|
data: { session }
|
||||||
} = await supabase.auth.getSession();
|
} = await supabase.auth.getSession();
|
||||||
|
|
||||||
if (session) {
|
if (session) {
|
||||||
localUser = session.user;
|
localUser = session.user;
|
||||||
|
user.set(localUser);
|
||||||
|
await goto('/mydex', { replace: true });
|
||||||
} else {
|
} else {
|
||||||
localUser = null;
|
localUser = null;
|
||||||
}
|
|
||||||
|
|
||||||
user.set(localUser);
|
user.set(localUser);
|
||||||
goto('/mydex', { replace: true });
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting user session:', error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ schema_paths = []
|
|||||||
enabled = true
|
enabled = true
|
||||||
# Specifies an ordered list of seed files to load during db reset.
|
# Specifies an ordered list of seed files to load during db reset.
|
||||||
# Supports glob patterns relative to supabase directory: "./seeds/*.sql"
|
# Supports glob patterns relative to supabase directory: "./seeds/*.sql"
|
||||||
sql_paths = ["./seed.sql"]
|
sql_paths = []
|
||||||
|
|
||||||
[db.network_restrictions]
|
[db.network_restrictions]
|
||||||
# Enable management of network restrictions.
|
# Enable management of network restrictions.
|
||||||
|
|||||||
@@ -1,9 +1,3 @@
|
|||||||
-- Migration: Create PostgreSQL schema for Pokemon data
|
|
||||||
-- This replaces the MongoDB collections with proper PostgreSQL tables
|
|
||||||
|
|
||||||
-- Note: Using individual columns instead of composite types for simplicity
|
|
||||||
|
|
||||||
-- Pokemon entries table (replaces pokedexentries MongoDB collection)
|
|
||||||
CREATE TABLE pokedex_entries (
|
CREATE TABLE pokedex_entries (
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
"pokedexNumber" INTEGER NOT NULL,
|
"pokedexNumber" INTEGER NOT NULL,
|
||||||
@@ -11,10 +5,10 @@ CREATE TABLE pokedex_entries (
|
|||||||
form TEXT,
|
form TEXT,
|
||||||
"canGigantamax" BOOLEAN DEFAULT FALSE,
|
"canGigantamax" BOOLEAN DEFAULT FALSE,
|
||||||
"regionToCatchIn" TEXT,
|
"regionToCatchIn" TEXT,
|
||||||
"gamesToCatchIn" TEXT[], -- Array of games
|
"gamesToCatchIn" TEXT[],
|
||||||
"regionToEvolveIn" TEXT,
|
"regionToEvolveIn" TEXT,
|
||||||
"evolutionInformation" TEXT,
|
"evolutionInformation" TEXT,
|
||||||
"catchInformation" TEXT[], -- Array of catch info
|
"catchInformation" TEXT[],
|
||||||
|
|
||||||
-- Box placement for forms view
|
-- Box placement for forms view
|
||||||
"boxPlacementFormsBox" INTEGER,
|
"boxPlacementFormsBox" INTEGER,
|
||||||
@@ -34,7 +28,6 @@ CREATE TABLE pokedex_entries (
|
|||||||
ALTER TABLE pokedex_entries ADD CONSTRAINT unique_pokemon_form
|
ALTER TABLE pokedex_entries ADD CONSTRAINT unique_pokemon_form
|
||||||
UNIQUE("pokedexNumber", form);
|
UNIQUE("pokedexNumber", form);
|
||||||
|
|
||||||
-- Catch records table (replaces catchrecords MongoDB collection)
|
|
||||||
CREATE TABLE catch_records (
|
CREATE TABLE catch_records (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
"userId" UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
"userId" UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||||
@@ -54,7 +47,6 @@ CREATE TABLE catch_records (
|
|||||||
UNIQUE("userId", "pokedexEntryId")
|
UNIQUE("userId", "pokedexEntryId")
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Region-game mappings table for filtering
|
|
||||||
CREATE TABLE region_game_mappings (
|
CREATE TABLE region_game_mappings (
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
region TEXT NOT NULL,
|
region TEXT NOT NULL,
|
||||||
@@ -62,7 +54,6 @@ CREATE TABLE region_game_mappings (
|
|||||||
UNIQUE(region, game)
|
UNIQUE(region, game)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Metadata table for migration tracking
|
|
||||||
CREATE TABLE metadata (
|
CREATE TABLE metadata (
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
key TEXT UNIQUE NOT NULL,
|
key TEXT UNIQUE NOT NULL,
|
||||||
|
|||||||
@@ -1,130 +0,0 @@
|
|||||||
-- Migration: Create PostgreSQL schema for Pokemon data
|
|
||||||
-- This replaces the M-- Create indexes for better p$$ LANGUAGE plpgsql;
|
|
||||||
|
|
||||||
-- Create triggers for updated_at
|
|
||||||
CREATE TRIGGER update_pokedex_entries_updated_at
|
|
||||||
BEFORE UPDATE ON pokedex_entries
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
|
||||||
|
|
||||||
CREATE TRIGGER update_catch_records_updated_at
|
|
||||||
BEFORE UPDATE ON catch_records
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();ance
|
|
||||||
CREATE INDEX idx_pokedex_entries_pokedex_number ON pokedex_entries(pokedex_number);
|
|
||||||
CREATE INDEX idx_pokedex_entries_pokemon ON pokedex_entries(pokemon);
|
|
||||||
CREATE INDEX idx_pokedex_entries_box_placement_forms ON pokedex_entries(box_placement_forms_box, box_placement_forms_row, box_placement_forms_column);
|
|
||||||
CREATE INDEX idx_pokedex_entries_box_placement ON pokedex_entries(box_placement_box, box_placement_row, box_placement_column);
|
|
||||||
|
|
||||||
CREATE INDEX idx_catch_records_user_id ON catch_records("userId");
|
|
||||||
CREATE INDEX idx_catch_records_pokedex_entry_id ON catch_records("pokedexEntryId");
|
|
||||||
CREATE INDEX idx_catch_records_caught ON catch_records(caught);
|
|
||||||
CREATE INDEX idx_catch_records_in_home ON catch_records("inHome");
|
|
||||||
CREATE INDEX idx_catch_records_user_caught ON catch_records("userId", caught);lections with proper PostgreSQL tables
|
|
||||||
|
|
||||||
-- Note: Using individual columns instead of composite types for simplicity
|
|
||||||
|
|
||||||
-- Pokemon entries table (replaces pokedexentries MongoDB collection)
|
|
||||||
CREATE TABLE pokedex_entries (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
pokedexNumber INTEGER NOT NULL,
|
|
||||||
pokemon TEXT NOT NULL,
|
|
||||||
form TEXT,
|
|
||||||
canGigantamax BOOLEAN DEFAULT FALSE,
|
|
||||||
regionToCatchIn TEXT,
|
|
||||||
gamesToCatchIn TEXT[], -- Array of games
|
|
||||||
regionToEvolveIn TEXT,
|
|
||||||
evolutionInformation TEXT,
|
|
||||||
catchInformation TEXT[], -- Array of catch info
|
|
||||||
|
|
||||||
-- Box placement for forms view
|
|
||||||
boxPlacementFormsBox INTEGER,
|
|
||||||
boxPlacementFormsRow INTEGER,
|
|
||||||
boxPlacementFormsColumn INTEGER,
|
|
||||||
|
|
||||||
-- Box placement for no-forms view
|
|
||||||
boxPlacementBox INTEGER,
|
|
||||||
boxPlacementRow INTEGER,
|
|
||||||
boxPlacementColumn INTEGER,
|
|
||||||
|
|
||||||
createdAt TIMESTAMPTZ DEFAULT NOW(),
|
|
||||||
updatedAt TIMESTAMPTZ DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Catch records table (replaces catchrecords MongoDB collection)
|
|
||||||
CREATE TABLE catch_records (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
"userId" UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
|
||||||
"pokedexEntryId" BIGINT NOT NULL REFERENCES pokedex_entries(id) ON DELETE CASCADE,
|
|
||||||
|
|
||||||
-- Catch status fields
|
|
||||||
"haveToEvolve" BOOLEAN DEFAULT FALSE,
|
|
||||||
caught BOOLEAN DEFAULT FALSE,
|
|
||||||
"inHome" BOOLEAN DEFAULT FALSE,
|
|
||||||
"hasGigantamaxed" BOOLEAN DEFAULT FALSE,
|
|
||||||
"personalNotes" TEXT,
|
|
||||||
|
|
||||||
"createdAt" TIMESTAMPTZ DEFAULT NOW(),
|
|
||||||
"updatedAt" TIMESTAMPTZ DEFAULT NOW(),
|
|
||||||
|
|
||||||
-- Ensure one record per user per pokemon entry
|
|
||||||
UNIQUE("userId", "pokedexEntryId")
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Region/Game mappings table (replaces regiongamemappings MongoDB collection)
|
|
||||||
CREATE TABLE region_game_mappings (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
region TEXT NOT NULL,
|
|
||||||
games TEXT[] NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Pokedex metadata table (replaces pokedexmetadata MongoDB collection)
|
|
||||||
CREATE TABLE pokedex_metadata (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
key TEXT UNIQUE NOT NULL,
|
|
||||||
value JSONB NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
||||||
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Add unique constraint to prevent duplicate pokemon forms
|
|
||||||
ALTER TABLE pokedex_entries ADD CONSTRAINT unique_pokemon_form
|
|
||||||
UNIQUE(pokedex_number, form);
|
|
||||||
|
|
||||||
-- Enable Row Level Security (RLS) for user data isolation
|
|
||||||
ALTER TABLE catch_records ENABLE ROW LEVEL SECURITY;
|
|
||||||
|
|
||||||
-- RLS Policy: Users can only access their own catch records
|
|
||||||
CREATE POLICY "Users can only access their own catch records"
|
|
||||||
ON catch_records FOR ALL
|
|
||||||
USING (auth.uid() = userId)
|
|
||||||
WITH CHECK (auth.uid() = userId);
|
|
||||||
|
|
||||||
-- Create indexes for better performance
|
|
||||||
CREATE INDEX idx_pokedex_entries_pokedex_number ON pokedex_entries(pokedexNumber);
|
|
||||||
CREATE INDEX idx_pokedex_entries_pokemon ON pokedex_entries(pokemon);
|
|
||||||
CREATE INDEX idx_pokedex_entries_box_placement_forms ON pokedex_entries(boxPlacementFormsBox, boxPlacementFormsRow, boxPlacementFormsColumn);
|
|
||||||
CREATE INDEX idx_pokedex_entries_box_placement ON pokedex_entries(boxPlacementBox, boxPlacementRow, boxPlacementColumn);
|
|
||||||
|
|
||||||
CREATE INDEX idx_catch_records_user_id ON catch_records(userId);
|
|
||||||
CREATE INDEX idx_catch_records_pokedex_entry_id ON catch_records(pokedexEntryId);
|
|
||||||
CREATE INDEX idx_catch_records_caught ON catch_records(caught);
|
|
||||||
CREATE INDEX idx_catch_records_in_home ON catch_records(inHome);
|
|
||||||
|
|
||||||
-- Create updated_at trigger function
|
|
||||||
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
|
||||||
RETURNS TRIGGER AS $$
|
|
||||||
BEGIN
|
|
||||||
NEW.updated_at = NOW();
|
|
||||||
RETURN NEW;
|
|
||||||
END;
|
|
||||||
$$ language 'plpgsql';
|
|
||||||
|
|
||||||
-- Add updated_at triggers
|
|
||||||
CREATE TRIGGER update_pokedex_entries_updated_at BEFORE UPDATE ON pokedex_entries
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
|
||||||
|
|
||||||
CREATE TRIGGER update_catch_records_updated_at BEFORE UPDATE ON catch_records
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
|
||||||
|
|
||||||
CREATE TRIGGER update_pokedex_metadata_updated_at BEFORE UPDATE ON pokedex_metadata
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
-- Migration: Create PostgreSQL schema for Pokemon data
|
|
||||||
-- This replaces the MongoDB collections with proper PostgreSQL tables
|
|
||||||
|
|
||||||
-- Note: Using individual columns instead of composite types for simplicity
|
|
||||||
|
|
||||||
-- Pokemon entries table (replaces pokedexentries MongoDB collection)
|
|
||||||
CREATE TABLE pokedex_entries (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
"pokedexNumber" INTEGER NOT NULL,
|
|
||||||
pokemon TEXT NOT NULL,
|
|
||||||
form TEXT,
|
|
||||||
"canGigantamax" BOOLEAN DEFAULT FALSE,
|
|
||||||
"regionToCatchIn" TEXT,
|
|
||||||
"gamesToCatchIn" TEXT[], -- Array of games
|
|
||||||
"regionToEvolveIn" TEXT,
|
|
||||||
"evolutionInformation" TEXT,
|
|
||||||
"catchInformation" TEXT[], -- Array of catch info
|
|
||||||
|
|
||||||
-- Box placement for forms view
|
|
||||||
"boxPlacementFormsBox" INTEGER,
|
|
||||||
"boxPlacementFormsRow" INTEGER,
|
|
||||||
"boxPlacementFormsColumn" INTEGER,
|
|
||||||
|
|
||||||
-- Box placement for no-forms view
|
|
||||||
"boxPlacementBox" INTEGER,
|
|
||||||
"boxPlacementRow" INTEGER,
|
|
||||||
"boxPlacementColumn" INTEGER,
|
|
||||||
|
|
||||||
"createdAt" TIMESTAMPTZ DEFAULT NOW(),
|
|
||||||
"updatedAt" TIMESTAMPTZ DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Add unique constraint to prevent duplicate pokemon forms
|
|
||||||
ALTER TABLE pokedex_entries ADD CONSTRAINT unique_pokemon_form
|
|
||||||
UNIQUE("pokedexNumber", form);
|
|
||||||
|
|
||||||
-- Catch records table (replaces catchrecords MongoDB collection)
|
|
||||||
CREATE TABLE catch_records (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
"userId" UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
|
||||||
"pokedexEntryId" BIGINT NOT NULL REFERENCES pokedex_entries(id) ON DELETE CASCADE,
|
|
||||||
|
|
||||||
-- Catch status fields
|
|
||||||
"haveToEvolve" BOOLEAN DEFAULT FALSE,
|
|
||||||
caught BOOLEAN DEFAULT FALSE,
|
|
||||||
"inHome" BOOLEAN DEFAULT FALSE,
|
|
||||||
"hasGigantamaxed" BOOLEAN DEFAULT FALSE,
|
|
||||||
"personalNotes" TEXT,
|
|
||||||
|
|
||||||
"createdAt" TIMESTAMPTZ DEFAULT NOW(),
|
|
||||||
"updatedAt" TIMESTAMPTZ DEFAULT NOW(),
|
|
||||||
|
|
||||||
-- Ensure one record per user per pokemon entry
|
|
||||||
UNIQUE("userId", "pokedexEntryId")
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Region-game mappings table for filtering
|
|
||||||
CREATE TABLE region_game_mappings (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
region TEXT NOT NULL,
|
|
||||||
game TEXT NOT NULL,
|
|
||||||
UNIQUE(region, game)
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Metadata table for migration tracking
|
|
||||||
CREATE TABLE metadata (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
key TEXT UNIQUE NOT NULL,
|
|
||||||
value TEXT,
|
|
||||||
"createdAt" TIMESTAMPTZ DEFAULT NOW(),
|
|
||||||
"updatedAt" TIMESTAMPTZ DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Create indexes for better performance
|
|
||||||
CREATE INDEX idx_pokedex_entries_pokedex_number ON pokedex_entries("pokedexNumber");
|
|
||||||
CREATE INDEX idx_pokedex_entries_pokemon ON pokedex_entries(pokemon);
|
|
||||||
CREATE INDEX idx_pokedex_entries_box_placement_forms ON pokedex_entries("boxPlacementFormsBox", "boxPlacementFormsRow", "boxPlacementFormsColumn");
|
|
||||||
CREATE INDEX idx_pokedex_entries_box_placement ON pokedex_entries("boxPlacementBox", "boxPlacementRow", "boxPlacementColumn");
|
|
||||||
|
|
||||||
CREATE INDEX idx_catch_records_user_id ON catch_records("userId");
|
|
||||||
CREATE INDEX idx_catch_records_pokedex_entry_id ON catch_records("pokedexEntryId");
|
|
||||||
CREATE INDEX idx_catch_records_caught ON catch_records(caught);
|
|
||||||
CREATE INDEX idx_catch_records_in_home ON catch_records("inHome");
|
|
||||||
CREATE INDEX idx_catch_records_user_caught ON catch_records("userId", caught);
|
|
||||||
|
|
||||||
-- Function to automatically update updated_at timestamp
|
|
||||||
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
|
||||||
RETURNS TRIGGER AS $$
|
|
||||||
BEGIN
|
|
||||||
NEW."updatedAt" = NOW();
|
|
||||||
RETURN NEW;
|
|
||||||
END;
|
|
||||||
$$ LANGUAGE plpgsql;
|
|
||||||
|
|
||||||
-- Create triggers for updated_at
|
|
||||||
CREATE TRIGGER update_pokedex_entries_updated_at
|
|
||||||
BEFORE UPDATE ON pokedex_entries
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
|
||||||
|
|
||||||
CREATE TRIGGER update_catch_records_updated_at
|
|
||||||
BEFORE UPDATE ON catch_records
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
|
||||||
|
|
||||||
-- Enable RLS on all tables
|
|
||||||
ALTER TABLE pokedex_entries ENABLE ROW LEVEL SECURITY;
|
|
||||||
ALTER TABLE catch_records ENABLE ROW LEVEL SECURITY;
|
|
||||||
ALTER TABLE region_game_mappings ENABLE ROW LEVEL SECURITY;
|
|
||||||
ALTER TABLE metadata ENABLE ROW LEVEL SECURITY;
|
|
||||||
|
|
||||||
-- RLS policies for pokedex_entries (public read)
|
|
||||||
CREATE POLICY "Anyone can view pokemon entries" ON pokedex_entries
|
|
||||||
FOR SELECT USING (true);
|
|
||||||
|
|
||||||
-- RLS policies for catch_records (user-specific)
|
|
||||||
CREATE POLICY "Users can view own catch records" ON catch_records
|
|
||||||
FOR SELECT USING (auth.uid() = "userId");
|
|
||||||
|
|
||||||
CREATE POLICY "Users can insert own catch records" ON catch_records
|
|
||||||
FOR INSERT WITH CHECK (auth.uid() = "userId");
|
|
||||||
|
|
||||||
CREATE POLICY "Users can update own catch records" ON catch_records
|
|
||||||
FOR UPDATE USING (auth.uid() = "userId");
|
|
||||||
|
|
||||||
CREATE POLICY "Users can delete own catch records" ON catch_records
|
|
||||||
FOR DELETE USING (auth.uid() = "userId");
|
|
||||||
|
|
||||||
-- RLS policies for region_game_mappings (public read)
|
|
||||||
CREATE POLICY "Anyone can view region game mappings" ON region_game_mappings
|
|
||||||
FOR SELECT USING (true);
|
|
||||||
|
|
||||||
-- RLS policies for metadata (public read)
|
|
||||||
CREATE POLICY "Anyone can view metadata" ON metadata
|
|
||||||
FOR SELECT USING (true);
|
|
||||||
@@ -1,10 +1,3 @@
|
|||||||
-- Auto-generated migration: Full Pokemon data from TSV
|
|
||||||
-- This replaces the MongoDB seeding and tsv-parser project
|
|
||||||
|
|
||||||
-- Clear existing data (for development)
|
|
||||||
DELETE FROM catch_records;
|
|
||||||
DELETE FROM pokedex_entries;
|
|
||||||
|
|
||||||
-- Insert full Pokemon dataset
|
-- Insert full Pokemon dataset
|
||||||
INSERT INTO pokedex_entries (
|
INSERT INTO pokedex_entries (
|
||||||
"pokedexNumber",
|
"pokedexNumber",
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
const fs = require('fs');
|
|
||||||
const csv = require('csv-parser');
|
|
||||||
|
|
||||||
const inputFilePath = 'seed-data.tsv'; // Replace with the path to your TSV file
|
|
||||||
const outputFilePath = 'pokedex.json';
|
|
||||||
|
|
||||||
const results = [];
|
|
||||||
|
|
||||||
fs.createReadStream(inputFilePath)
|
|
||||||
.pipe(csv({ separator: '\t' }))
|
|
||||||
.on('data', (data) => {
|
|
||||||
const entry = {
|
|
||||||
pokedexNumber: parseInt(data['Dex #']),
|
|
||||||
boxPlacement: {
|
|
||||||
box: parseInt(data['No Form Box']),
|
|
||||||
row: parseInt(data['No Form Row']),
|
|
||||||
column: parseInt(data['No Form Column'])
|
|
||||||
},
|
|
||||||
boxPlacementForms: {
|
|
||||||
box: parseInt(data['Home Box']),
|
|
||||||
row: parseInt(data['Home Row']),
|
|
||||||
column: parseInt(data['Home Column'])
|
|
||||||
},
|
|
||||||
pokemon: data['Pokemon'],
|
|
||||||
form: data['Form'],
|
|
||||||
canGigantamax: data['Can Gigantamax'].toLowerCase(),
|
|
||||||
regionToCatchIn: data['Region'],
|
|
||||||
gamesToCatchIn: data['Catch In These Games'].split(',').map((game) => game.trim()),
|
|
||||||
regionToEvolveIn: data['Evolve In Region'],
|
|
||||||
evolutionInformation: data['Evolution Info'],
|
|
||||||
catchInformation: []
|
|
||||||
};
|
|
||||||
results.push(entry);
|
|
||||||
})
|
|
||||||
.on('end', () => {
|
|
||||||
fs.writeFile(outputFilePath, JSON.stringify(results, null, 2), (err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error('Error writing to JSON file', err);
|
|
||||||
} else {
|
|
||||||
console.log('JSON file has been successfully created');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
Generated
-47
@@ -1,47 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "tsv-parser",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"lockfileVersion": 3,
|
|
||||||
"requires": true,
|
|
||||||
"packages": {
|
|
||||||
"": {
|
|
||||||
"name": "tsv-parser",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"license": "ISC",
|
|
||||||
"dependencies": {
|
|
||||||
"csv-parser": "^3.0.0",
|
|
||||||
"fs": "^0.0.1-security"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/csv-parser": {
|
|
||||||
"version": "3.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/csv-parser/-/csv-parser-3.0.0.tgz",
|
|
||||||
"integrity": "sha512-s6OYSXAK3IdKqYO33y09jhypG/bSDHPuyCme/IdEHfWpLf/jKcpitVFyOC6UemgGk8v7Q5u2XE0vvwmanxhGlQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"minimist": "^1.2.0"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"csv-parser": "bin/csv-parser"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 10"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/fs": {
|
|
||||||
"version": "0.0.1-security",
|
|
||||||
"resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz",
|
|
||||||
"integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==",
|
|
||||||
"license": "ISC"
|
|
||||||
},
|
|
||||||
"node_modules/minimist": {
|
|
||||||
"version": "1.2.8",
|
|
||||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
|
||||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/ljharb"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "tsv-parser",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"main": "index.js",
|
|
||||||
"scripts": {
|
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
|
||||||
},
|
|
||||||
"keywords": [],
|
|
||||||
"author": "",
|
|
||||||
"license": "ISC",
|
|
||||||
"description": "",
|
|
||||||
"dependencies": {
|
|
||||||
"csv-parser": "^3.0.0",
|
|
||||||
"fs": "^0.0.1-security"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-35491
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user