diff --git a/backend/src/db.ts b/backend/src/db.ts index d7ebe45..6132132 100644 --- a/backend/src/db.ts +++ b/backend/src/db.ts @@ -50,18 +50,20 @@ db.exec(` CREATE INDEX IF NOT EXISTS idx_memes_parent_id ON memes(parent_id); CREATE INDEX IF NOT EXISTS idx_memes_created_at ON memes(created_at DESC); - CREATE INDEX IF NOT EXISTS idx_memes_collection_id ON memes(collection_id); CREATE INDEX IF NOT EXISTS idx_meme_tags_meme_id ON meme_tags(meme_id); CREATE INDEX IF NOT EXISTS idx_meme_tags_tag_id ON meme_tags(tag_id); `); // Migration: add collection_id column if upgrading from earlier schema +// Must run BEFORE creating the index on that column const memesCols = db.prepare('PRAGMA table_info(memes)').all() as { name: string }[]; if (!memesCols.find((c) => c.name === 'collection_id')) { db.exec('ALTER TABLE memes ADD COLUMN collection_id INTEGER REFERENCES collections(id) ON DELETE SET NULL'); - db.exec('CREATE INDEX IF NOT EXISTS idx_memes_collection_id ON memes(collection_id)'); } +// Create index after the column is guaranteed to exist (handles both fresh and migrated DBs) +db.exec('CREATE INDEX IF NOT EXISTS idx_memes_collection_id ON memes(collection_id)'); + // Seed the default UNSORTED collection const defaultCollection = db .prepare('SELECT id FROM collections WHERE is_default = 1')