// Rôle : encapsule la base SQLite et les migrations du mini-jeu Sokko TCG. import { mkdirSync } from "node:fs"; import { dirname } from "node:path"; import { DatabaseSync } from "node:sqlite"; import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "./admin-seed.js"; import { DEFAULT_EXPEDITION_SETTINGS } from "./expedition-settings.js"; export const MIGRATIONS = [ ` CREATE TABLE players ( id TEXT PRIMARY KEY, discord_id TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, avatar_url TEXT NOT NULL DEFAULT '', is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)), created_at INTEGER NOT NULL, openings_balance INTEGER NOT NULL DEFAULT 1 CHECK (openings_balance BETWEEN 0 AND 5), recharge_anchor INTEGER, stardust INTEGER NOT NULL DEFAULT 0 CHECK (stardust >= 0), purchased_openings INTEGER NOT NULL DEFAULT 0 CHECK (purchased_openings >= 0) ) STRICT; CREATE TABLE sessions ( token_hash TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, csrf_token TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ) STRICT; CREATE INDEX sessions_player_idx ON sessions(player_id); CREATE TABLE openings ( id TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id), collection_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'completed')), created_at INTEGER NOT NULL, completed_at INTEGER ) STRICT; CREATE INDEX openings_player_idx ON openings(player_id, created_at DESC); -- Collection : une ligne par carte possédée, avec sa quantité. Un joueur garde toujours au moins un exemplaire de -- chaque carte obtenue (seuls les doublons s'échangent, se donnent ou se recyclent) : une ligne n'est jamais supprimée. CREATE TABLE collection_cards ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, edition_id TEXT NOT NULL, quantity INTEGER NOT NULL CHECK (quantity >= 1), acquired_at INTEGER NOT NULL, PRIMARY KEY (player_id, edition_id) ) STRICT; CREATE TABLE opening_cards ( opening_id TEXT NOT NULL REFERENCES openings(id) ON DELETE CASCADE, position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 2), edition_id TEXT NOT NULL, was_new_card INTEGER NOT NULL CHECK (was_new_card IN (0, 1)), was_new_edition INTEGER NOT NULL CHECK (was_new_edition IN (0, 1)), quantity_before INTEGER NOT NULL, PRIMARY KEY (opening_id, position) ) STRICT; CREATE TABLE favorites ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, edition_id TEXT NOT NULL, PRIMARY KEY (player_id, edition_id) ) STRICT; CREATE TABLE transfers ( id TEXT PRIMARY KEY, code TEXT NOT NULL UNIQUE, type TEXT NOT NULL CHECK (type IN ('trade', 'gift')), initiator_id TEXT NOT NULL REFERENCES players(id), recipient_id TEXT REFERENCES players(id), offered_edition_id TEXT NOT NULL, requested_edition_id TEXT, initiator_confirmed INTEGER NOT NULL DEFAULT 0 CHECK (initiator_confirmed IN (0, 1)), recipient_confirmed INTEGER NOT NULL DEFAULT 0 CHECK (recipient_confirmed IN (0, 1)), status TEXT NOT NULL CHECK (status IN ('open', 'joined', 'completed', 'cancelled', 'expired')), created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, completed_at INTEGER ) STRICT; CREATE INDEX transfers_participants_idx ON transfers(initiator_id, recipient_id, status); -- Un transfert en cours (open, joined) réserve un doublon de chaque carte engagée. CREATE TABLE campaigns ( id TEXT PRIMARY KEY, name TEXT NOT NULL, code TEXT NOT NULL UNIQUE, reward_json TEXT NOT NULL, max_claims INTEGER CHECK (max_claims IS NULL OR max_claims > 0), created_by TEXT NOT NULL REFERENCES players(id), created_at INTEGER NOT NULL, expires_at INTEGER, revoked_at INTEGER ) STRICT; CREATE TABLE campaign_claims ( id TEXT PRIMARY KEY, campaign_id TEXT NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, player_id TEXT NOT NULL REFERENCES players(id), claimed_at INTEGER NOT NULL, UNIQUE (campaign_id, player_id) ) STRICT; CREATE TABLE gift_packs ( id TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id), campaign_id TEXT NOT NULL REFERENCES campaigns(id), collection_id TEXT NOT NULL, options_json TEXT NOT NULL, created_at INTEGER NOT NULL, opening_id TEXT REFERENCES openings(id), opened_at INTEGER ) STRICT; CREATE INDEX gift_packs_player_idx ON gift_packs(player_id, opened_at); CREATE TABLE idempotency ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, scope TEXT NOT NULL, request_key TEXT NOT NULL, response_json TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (player_id, scope, request_key) ) STRICT; CREATE TABLE audit_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, player_id TEXT REFERENCES players(id), event_type TEXT NOT NULL, entity_id TEXT NOT NULL, details_json TEXT NOT NULL, created_at INTEGER NOT NULL ) STRICT; CREATE INDEX audit_player_idx ON audit_log(player_id, created_at DESC); `, // Contenu géré depuis l'administration : variations mythiques, réglages d'ouverture, état des paquets, // tables de tirage, recharge des ouvertures et boutique (barème de poussière d'étoiles, prix d'une ouverture). Ces données n'existent qu'ici ; la migration insère le contenu de départ (admin-seed.js). ` CREATE INDEX collection_cards_edition_idx ON collection_cards(edition_id); CREATE INDEX opening_cards_edition_idx ON opening_cards(edition_id); CREATE TABLE mythic_variations ( edition_id TEXT PRIMARY KEY, card_id TEXT NOT NULL, finish_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('active', 'retired')), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; CREATE TABLE mythic_opening_settings ( scope TEXT NOT NULL CHECK (scope IN ('collection', 'card')), target_id TEXT NOT NULL, particle_shape_id TEXT, particle_palette_id TEXT, updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id), PRIMARY KEY (scope, target_id) ) STRICT; CREATE TABLE collection_states ( collection_id TEXT PRIMARY KEY, active INTEGER NOT NULL CHECK (active IN (0, 1)), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; CREATE TABLE drop_rates ( collection_id TEXT PRIMARY KEY, rarity_weights_json TEXT NOT NULL, updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; CREATE TABLE recharge_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), interval_ms INTEGER NOT NULL CHECK (interval_ms >= 60000), max_openings INTEGER NOT NULL CHECK (max_openings BETWEEN 1 AND 5), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; CREATE TABLE shop_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), stardust_values_json TEXT NOT NULL, opening_price INTEGER NOT NULL CHECK (opening_price > 0), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; INSERT INTO shop_settings(id, stardust_values_json, opening_price, updated_at, updated_by) VALUES (1, '${JSON.stringify(INITIAL_SHOP_SETTING.stardustValues)}', ${INITIAL_SHOP_SETTING.openingPrice}, 0, NULL); INSERT INTO recharge_settings(id, interval_ms, max_openings, updated_at, updated_by) VALUES (1, ${INITIAL_RECHARGE_SETTING.intervalMs}, ${INITIAL_RECHARGE_SETTING.maxOpenings}, 0, NULL); ${INITIAL_COLLECTION_STATES.map(({ collectionId, active }) => `INSERT INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('${collectionId}', ${active ? 1 : 0}, 0, NULL);`).join("\n ")} ${INITIAL_DROP_RATES.map(({ collectionId, rarityWeights }) => `INSERT INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('${collectionId}', '${JSON.stringify(rarityWeights)}', 0, NULL);`).join("\n ")} `, // Propositions directes : plus de code à rejoindre. Les transferts en cours de l'ancien système sont annulés, // ce qui libère leurs doublons réservés. Les anciens statuts et colonnes restent pour relire l'historique. ` ALTER TABLE transfers ADD COLUMN declined INTEGER NOT NULL DEFAULT 0 CHECK (declined IN (0, 1)); UPDATE transfers SET status = 'cancelled' WHERE status IN ('open', 'joined'); `, // Paquet de la Boutique : la collection stardust s'ouvre avec les poids recommandés ; prix et part de ses cartes se règlent dans l'administration. ` ALTER TABLE shop_settings ADD COLUMN shop_pack_price INTEGER NOT NULL DEFAULT 60 CHECK (shop_pack_price >= 1); ALTER TABLE shop_settings ADD COLUMN shop_pack_share INTEGER NOT NULL DEFAULT 50 CHECK (shop_pack_share BETWEEN 0 AND 100); INSERT OR IGNORE INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('stardust', 1, 0, NULL); INSERT OR IGNORE INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('stardust', '{"common":64,"rare":24,"epic":8,"legendary":3,"mythic":1}', 0, NULL); `, // Suppression de compte : la ligne du joueur reste, anonymisée, car les ouvertures, échanges et journaux y font référence. ` ALTER TABLE players ADD COLUMN deleted_at INTEGER; `, // Dernière connexion Discord : un compte resté 24 mois sans connexion est anonymisé (runMaintenance). ` ALTER TABLE players ADD COLUMN last_login_at INTEGER; UPDATE players SET last_login_at = created_at; `, // Carte du jour : une carte commune à tous les joueurs par jour de Paris, la partie de chaque joueur et la récompense // d'une victoire, réglée avec la boutique. ` ALTER TABLE shop_settings ADD COLUMN daily_reward INTEGER NOT NULL DEFAULT 10 CHECK (daily_reward BETWEEN 0 AND 100000); CREATE TABLE daily_puzzles ( day TEXT PRIMARY KEY, card_id TEXT NOT NULL, focus_x INTEGER NOT NULL CHECK (focus_x BETWEEN 0 AND 100), focus_y INTEGER NOT NULL CHECK (focus_y BETWEEN 0 AND 100), created_at INTEGER NOT NULL ) STRICT; -- guesses_json : identifiants des cartes proposées, dans l'ordre ; reward : poussière créditée par la victoire. CREATE TABLE daily_attempts ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, day TEXT NOT NULL REFERENCES daily_puzzles(day), guesses_json TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('playing', 'won', 'lost')), reward INTEGER NOT NULL DEFAULT 0 CHECK (reward >= 0), updated_at INTEGER NOT NULL, PRIMARY KEY (player_id, day) ) STRICT; CREATE INDEX daily_attempts_day_idx ON daily_attempts(day, status); `, // Expéditions : Éclats d'étoile, réglages (un JSON validé par expedition-settings.js, Expéditions fermées au départ), destinations du jour, // expéditions, participants et places. Les CHECK prévoient déjà le groupe (mode, inscription, 5 ★, 4 places, rôles). // gift_packs est reconstruite : un paquet offert vient d'une campagne ou d'une expédition. ` ALTER TABLE players ADD COLUMN eclats INTEGER NOT NULL DEFAULT 0 CHECK (eclats >= 0); CREATE TABLE expedition_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), settings_json TEXT NOT NULL CHECK (json_valid(settings_json)), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; INSERT INTO expedition_settings(id, settings_json, updated_at, updated_by) VALUES (1, '${JSON.stringify(DEFAULT_EXPEDITION_SETTINGS)}', 0, NULL); -- draw_json : destinations tirées (identifiant, condition et dangers) ; les exigences chiffrées sont calculées à la lecture. CREATE TABLE expedition_days ( day TEXT PRIMARY KEY, draw_json TEXT NOT NULL CHECK (json_valid(draw_json)), created_at INTEGER NOT NULL ) STRICT; -- setup_json fige la destination, les exigences et les réglages du départ ; result_json n'est montré qu'au retour. CREATE TABLE expeditions ( id TEXT PRIMARY KEY, mode TEXT NOT NULL CHECK (mode IN ('solo', 'group')), day TEXT NOT NULL REFERENCES expedition_days(day), destination_id TEXT NOT NULL, difficulty INTEGER NOT NULL CHECK (difficulty BETWEEN 1 AND 5), duration_ms INTEGER NOT NULL CHECK (duration_ms > 0), creator_id TEXT NOT NULL REFERENCES players(id), status TEXT NOT NULL CHECK (status IN ('forming', 'running', 'completed', 'cancelled')), setup_json TEXT NOT NULL CHECK (json_valid(setup_json)), result_json TEXT CHECK (result_json IS NULL OR json_valid(result_json)), created_at INTEGER NOT NULL, departs_at INTEGER, returns_at INTEGER, completed_at INTEGER ) STRICT; CREATE INDEX expeditions_status_idx ON expeditions(status, returns_at); CREATE INDEX expeditions_day_idx ON expeditions(day, creator_id); CREATE TABLE expedition_members ( expedition_id TEXT NOT NULL REFERENCES expeditions(id) ON DELETE CASCADE, player_id TEXT NOT NULL REFERENCES players(id), reward_json TEXT CHECK (reward_json IS NULL OR json_valid(reward_json)), joined_at INTEGER NOT NULL, claimed_at INTEGER, PRIMARY KEY (expedition_id, player_id) ) STRICT; CREATE INDEX expedition_members_player_idx ON expedition_members(player_id, claimed_at); -- player_id nul : place tenue par le Veilleur de la Guilde, sans carte ni rôle. CREATE TABLE expedition_slots ( expedition_id TEXT NOT NULL REFERENCES expeditions(id) ON DELETE CASCADE, position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 3), role TEXT CHECK (role IS NULL OR role IN ('leader', 'guardian', 'seeker', 'navigator')), player_id TEXT REFERENCES players(id), edition_id TEXT, card_id TEXT, level INTEGER NOT NULL DEFAULT 0 CHECK (level >= 0), stats_json TEXT NOT NULL CHECK (json_valid(stats_json)), PRIMARY KEY (expedition_id, position) ) STRICT; CREATE INDEX expedition_slots_player_idx ON expedition_slots(player_id, edition_id); CREATE TABLE gift_packs_next ( id TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id), source TEXT NOT NULL DEFAULT 'campaign' CHECK (source IN ('campaign', 'expedition')), campaign_id TEXT REFERENCES campaigns(id), expedition_id TEXT REFERENCES expeditions(id), collection_id TEXT NOT NULL, options_json TEXT NOT NULL, created_at INTEGER NOT NULL, opening_id TEXT REFERENCES openings(id), opened_at INTEGER, CHECK ((source = 'campaign' AND campaign_id IS NOT NULL) OR (source = 'expedition' AND expedition_id IS NOT NULL)) ) STRICT; INSERT INTO gift_packs_next(id, player_id, source, campaign_id, collection_id, options_json, created_at, opening_id, opened_at) SELECT id, player_id, 'campaign', campaign_id, collection_id, options_json, created_at, opening_id, opened_at FROM gift_packs; DROP TABLE gift_packs; ALTER TABLE gift_packs_next RENAME TO gift_packs; CREATE INDEX gift_packs_player_idx ON gift_packs(player_id, opened_at); `, // Améliorations des Expéditions : niveau et expérience de terrain (en % du niveau suivant) de chaque édition possédée par un joueur. // La progression suit l'exemplaire gardé : seuls les doublons quittent une collection. ` CREATE TABLE card_progress ( player_id TEXT NOT NULL REFERENCES players(id), edition_id TEXT NOT NULL, level INTEGER NOT NULL DEFAULT 0 CHECK (level >= 0), field_xp INTEGER NOT NULL DEFAULT 0 CHECK (field_xp BETWEEN 0 AND 99), updated_at INTEGER NOT NULL, PRIMARY KEY (player_id, edition_id) ) STRICT; `, // Équipements et Grimoire des Expéditions : une commune possédée est posée sur un seul emplacement d'une carte à la fois // (l'exemplaire gardé, jamais détruit) ; le Grimoire gardait les paires et Résonances découvertes (retiré par la migration 17). ` CREATE TABLE card_equipment ( player_id TEXT NOT NULL REFERENCES players(id), edition_id TEXT NOT NULL, slot INTEGER NOT NULL CHECK (slot BETWEEN 0 AND 2), equipment_edition_id TEXT NOT NULL, equipped_at INTEGER NOT NULL, PRIMARY KEY (player_id, edition_id, slot), UNIQUE (player_id, equipment_edition_id) ) STRICT; CREATE TABLE grimoire_entries ( player_id TEXT NOT NULL REFERENCES players(id), entry_id TEXT NOT NULL, discovered_at INTEGER NOT NULL, PRIMARY KEY (player_id, entry_id) ) STRICT; `, // Alertes Discord des Expéditions : choix de chaque joueur (désactivées tant qu'il ne les active pas), file des messages // privés à envoyer par le bot, et marque des retours déjà annoncés. ` CREATE TABLE player_alerts ( player_id TEXT PRIMARY KEY REFERENCES players(id), group_opened INTEGER NOT NULL DEFAULT 0 CHECK (group_opened IN (0, 1)), expedition_returned INTEGER NOT NULL DEFAULT 0 CHECK (expedition_returned IN (0, 1)), updated_at INTEGER NOT NULL ) STRICT; CREATE TABLE alert_outbox ( id TEXT PRIMARY KEY, player_id TEXT NOT NULL REFERENCES players(id), kind TEXT NOT NULL CHECK (kind IN ('group_opened', 'expedition_returned')), content TEXT NOT NULL, created_at INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, sent_at INTEGER, failed_at INTEGER, last_error TEXT ) STRICT; CREATE INDEX alert_outbox_pending_idx ON alert_outbox(sent_at, failed_at, created_at); ALTER TABLE expedition_members ADD COLUMN alerted_at INTEGER; `, // Objets des Expéditions : inventaire de chaque joueur, gravures posées sur ses équipements (une par commune) et destinations // bonus ajoutées à sa journée (5e, 6e, ou une destination cachée ouverte par une carte au trésor). ` CREATE TABLE player_items ( player_id TEXT NOT NULL REFERENCES players(id), item_id TEXT NOT NULL, quantity INTEGER NOT NULL CHECK (quantity >= 0), PRIMARY KEY (player_id, item_id) ) STRICT; CREATE TABLE equipment_engravings ( player_id TEXT NOT NULL REFERENCES players(id), edition_id TEXT NOT NULL, tag TEXT NOT NULL, engraved_at INTEGER NOT NULL, PRIMARY KEY (player_id, edition_id) ) STRICT; CREATE TABLE player_bonus_destinations ( player_id TEXT NOT NULL REFERENCES players(id), day TEXT NOT NULL, slot TEXT NOT NULL CHECK (slot IN ('5', '6', 'hidden')), destination_id TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (player_id, day, slot) ) STRICT; `, // Pouvoirs des Carnets des Veilleurs portés par la carte d'une place, figés à l'inscription ou au départ. ` ALTER TABLE expedition_slots ADD COLUMN powers_json TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(powers_json)); `, // Tirage du jour personnel : chaque joueur tire ses destinations parmi celles qu'il a débloquées (cartes de destination). // expedition_days garde une ligne par jour, que les expéditions référencent. ` CREATE TABLE player_expedition_days ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, day TEXT NOT NULL, draw_json TEXT NOT NULL CHECK (json_valid(draw_json)), created_at INTEGER NOT NULL, PRIMARY KEY (player_id, day) ) STRICT; `, // Plan de progression d'une carte : comment ses points de niveau se répartissent (collection, vocation ou libre) et, // en libre, les points placés par le joueur. NULL : jamais choisi (le premier choix est gratuit). ` ALTER TABLE card_progress ADD COLUMN plan TEXT CHECK (plan IS NULL OR plan IN ('collection', 'leader', 'guardian', 'seeker', 'navigator', 'free')); ALTER TABLE card_progress ADD COLUMN allocation_json TEXT CHECK (allocation_json IS NULL OR json_valid(allocation_json)); `, // Rose des vents : dernier moment où le joueur a retiré ses destinations du jour. ` ALTER TABLE player_expedition_days ADD COLUMN rerolled_at INTEGER; `, // Le Grimoire (paires et Résonances découvertes) est retiré : il n'avait aucun effet sur le jeu. ` DROP TABLE IF EXISTS grimoire_entries; `, // Carte du jour personnelle : une carte commune incitait à se passer la réponse. Chaque joueur tire sa carte et son point // de zoom à sa première visite du jour, gardés avec sa partie. daily_days numérote les jours ; les parties passées gardent // la carte commune de leur jour. ` CREATE TABLE daily_days (day TEXT PRIMARY KEY, created_at INTEGER NOT NULL) STRICT; INSERT INTO daily_days(day, created_at) SELECT day, created_at FROM daily_puzzles; CREATE TABLE daily_attempts_next ( player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE, day TEXT NOT NULL REFERENCES daily_days(day), card_id TEXT NOT NULL, focus_x INTEGER NOT NULL CHECK (focus_x BETWEEN 0 AND 100), focus_y INTEGER NOT NULL CHECK (focus_y BETWEEN 0 AND 100), guesses_json TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('playing', 'won', 'lost')), reward INTEGER NOT NULL DEFAULT 0 CHECK (reward >= 0), created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, PRIMARY KEY (player_id, day) ) STRICT; INSERT INTO daily_attempts_next(player_id, day, card_id, focus_x, focus_y, guesses_json, status, reward, created_at, updated_at) SELECT attempt.player_id, attempt.day, puzzle.card_id, puzzle.focus_x, puzzle.focus_y, attempt.guesses_json, attempt.status, attempt.reward, attempt.updated_at, attempt.updated_at FROM daily_attempts AS attempt JOIN daily_puzzles AS puzzle ON puzzle.day = attempt.day; DROP TABLE daily_attempts; DROP TABLE daily_puzzles; ALTER TABLE daily_attempts_next RENAME TO daily_attempts; CREATE INDEX daily_attempts_day_idx ON daily_attempts(day, status); `, // Difficulté relevée (3 à 5 ★, hausse par joueur en plus) : les exigences déjà enregistrées par l'administration reprennent les // nouvelles valeurs par défaut. Personne n'avait encore joué d'expédition. ` UPDATE expedition_settings SET settings_json = json_remove(settings_json, '$.requirements') WHERE id = 1; `, // Groupes : un joueur qui rejoint choisit encore sa carte et son équipement, puis se déclare prêt (`ready_at`) ; ses stats se // figent alors. Le créateur est prêt dès l'ouverture ; les inscrits d'avant avaient déjà des stats figées : ils sont prêts. ` ALTER TABLE expedition_members ADD COLUMN ready_at INTEGER; UPDATE expedition_members SET ready_at = joined_at; `, // Réserve d'ouvertures réglable : players.openings_balance n'est plus plafonné à 5 (« positif ou nul ») et // recharge_settings.max_openings va jusqu'à 50, comme MAX_RESERVE_OPENINGS. SQLite ne modifie pas une contrainte : // les tables sont reconstruites, sans clés étrangères pendant la copie (sinon DROP TABLE viderait les tables qui référencent players). { withoutForeignKeys: true, sql: ` CREATE TABLE players_next ( id TEXT PRIMARY KEY, discord_id TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, avatar_url TEXT NOT NULL DEFAULT '', is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)), created_at INTEGER NOT NULL, openings_balance INTEGER NOT NULL DEFAULT 1 CHECK (openings_balance >= 0), recharge_anchor INTEGER, stardust INTEGER NOT NULL DEFAULT 0 CHECK (stardust >= 0), purchased_openings INTEGER NOT NULL DEFAULT 0 CHECK (purchased_openings >= 0), deleted_at INTEGER, last_login_at INTEGER, eclats INTEGER NOT NULL DEFAULT 0 CHECK (eclats >= 0) ) STRICT; INSERT INTO players_next(id, discord_id, display_name, avatar_url, is_admin, created_at, openings_balance, recharge_anchor, stardust, purchased_openings, deleted_at, last_login_at, eclats) SELECT id, discord_id, display_name, avatar_url, is_admin, created_at, openings_balance, recharge_anchor, stardust, purchased_openings, deleted_at, last_login_at, eclats FROM players; DROP TABLE players; ALTER TABLE players_next RENAME TO players; CREATE TABLE recharge_settings_next ( id INTEGER PRIMARY KEY CHECK (id = 1), interval_ms INTEGER NOT NULL CHECK (interval_ms >= 60000), max_openings INTEGER NOT NULL CHECK (max_openings BETWEEN 1 AND 50), updated_at INTEGER NOT NULL, updated_by TEXT REFERENCES players(id) ) STRICT; INSERT INTO recharge_settings_next(id, interval_ms, max_openings, updated_at, updated_by) SELECT id, interval_ms, max_openings, updated_at, updated_by FROM recharge_settings; DROP TABLE recharge_settings; ALTER TABLE recharge_settings_next RENAME TO recharge_settings; ` }, // La finition d'une variation mythique peut changer sans toucher à son identifiant (les exemplaires des joueurs restent) : // l'identifiant ne garantit donc plus qu'une carte a une seule variation par finition, cet index le fait. ` CREATE UNIQUE INDEX mythic_variations_card_finish_idx ON mythic_variations(card_id, finish_id); `, // Paliers d'une variation mythique, de 1 à 5 : intensité de la palette et palier propre à l'effet (vitesse, amplitude…). Le // palier central, 3, ne change rien au rendu : les variations existantes gardent exactement leur apparence. ` ALTER TABLE mythic_variations ADD COLUMN holo_intensity INTEGER NOT NULL DEFAULT 3 CHECK (holo_intensity BETWEEN 1 AND 5); ALTER TABLE mythic_variations ADD COLUMN holo_level INTEGER NOT NULL DEFAULT 3 CHECK (holo_level BETWEEN 1 AND 5); `, // Particules persistantes d'une variation mythique : animation (`flare_id`, NULL pour aucune), motif, palette (NULL pour celle // de la finition), zone (NULL pour l'illustration) et paliers de 1 à 5. Les identifiants viennent du catalogue versionné et // sont validés par le service ; des réglages que le catalogue ne connaît plus ne sont simplement pas publiés. ` ALTER TABLE mythic_variations ADD COLUMN flare_id TEXT; ALTER TABLE mythic_variations ADD COLUMN flare_motif_id TEXT; ALTER TABLE mythic_variations ADD COLUMN flare_palette_id TEXT; ALTER TABLE mythic_variations ADD COLUMN flare_scope TEXT; ALTER TABLE mythic_variations ADD COLUMN flare_intensity INTEGER NOT NULL DEFAULT 3 CHECK (flare_intensity BETWEEN 1 AND 5); ALTER TABLE mythic_variations ADD COLUMN flare_level INTEGER NOT NULL DEFAULT 3 CHECK (flare_level BETWEEN 1 AND 5); ALTER TABLE mythic_variations ADD COLUMN flare_count INTEGER NOT NULL DEFAULT 3 CHECK (flare_count BETWEEN 1 AND 5); `, // Cinq communes à stats portent désormais un pouvoir : elles sont retirées des cartes qui les portaient. Leur effet n'a plus rien // à voir avec celui que le joueur avait choisi, et une carte déjà porteuse d'un pouvoir en aurait eu deux. ` DELETE FROM card_equipment WHERE equipment_edition_id IN ( 'astronomers-notebook-standard', 'starry-snowflake-standard', 'clearing-chest-standard', 'red-moon-comb-standard', 'first-visitor-mask-standard'); `, // Indices au choix de la Carte du jour : ceux que le joueur a retournés, et s'il possédait la carte au tirage (NULL pour une // partie d'avant cette migration), pour qu'un paquet ouvert pendant la partie ne change pas l'indice. ` ALTER TABLE daily_attempts ADD COLUMN hints_json TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(hints_json)); ALTER TABLE daily_attempts ADD COLUMN owned INTEGER CHECK (owned IS NULL OR owned IN (0, 1)); `, // L'indice « Rareté » laisse la place au thème du nom : il est retiré des parties qui l'avaient retourné, ce qui rend leur indice. ` UPDATE daily_attempts SET hints_json = (SELECT json_group_array(hint.value) FROM json_each(daily_attempts.hints_json) AS hint WHERE hint.value <> 'rarity') WHERE EXISTS (SELECT 1 FROM json_each(daily_attempts.hints_json) AS hint WHERE hint.value = 'rarity'); ` ]; export class CardsDatabase { constructor(path) { if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true }); this.db = new DatabaseSync(path); this.db.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"); this.migrate(); } migrate() { this.db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at INTEGER NOT NULL) STRICT;"); const applied = new Set(this.db.prepare("SELECT version FROM schema_migrations").all().map((row) => row.version)); MIGRATIONS.forEach((migration, index) => { const version = index + 1; if (applied.has(version)) return; const { sql, withoutForeignKeys = false } = typeof migration === "string" ? { sql: migration } : migration; // Le pragma est sans effet dans une transaction : il est coupé avant, puis la cohérence est vérifiée avant de valider. if (withoutForeignKeys) this.db.exec("PRAGMA foreign_keys = OFF"); try { this.transaction(() => { this.db.exec(sql); if (withoutForeignKeys && this.db.prepare("PRAGMA foreign_key_check").all().length) throw new Error(`Migration ${version} left dangling foreign keys.`); this.db.prepare("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)").run(version, Date.now()); }); } finally { if (withoutForeignKeys) this.db.exec("PRAGMA foreign_keys = ON"); } }); } transaction(callback) { this.db.exec("BEGIN IMMEDIATE"); try { const result = callback(); this.db.exec("COMMIT"); return result; } catch (error) { this.db.exec("ROLLBACK"); throw error; } } close() { this.db.close(); } }