diff --git a/settings/Settings.mjs b/settings/Settings.mjs index ee351ec..30bc00b 100644 --- a/settings/Settings.mjs +++ b/settings/Settings.mjs @@ -67,14 +67,23 @@ export class MySqlSettingsManager extends SettingsManager { } /** - * Check whether the `bot_id` column exists in the settings table. - * If it doesn't, auto-migrate by adding the column and updating the primary key. + * Check whether the `bot_id` column exists in the settings table AND is + * part of the primary key. If the column is missing, auto-migrate by + * adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id). + * If the column exists but isn't in the PK (previous failed migration), + * fix the NULL values and retry the PK update. + * + * Key detail: MySQL primary key columns CANNOT be NULL. The previous version + * used DEFAULT NULL which caused ALTER TABLE ... ADD PRIMARY KEY to fail + * silently, leaving the PK as just (id) and producing ER_DUP_ENTRY errors + * when two bots tried to INSERT rows for the same guild. */ async _ensureBotIdColumn() { if (this._hasBotIdColumn) return; + // Check if bot_id column exists and its properties const res = await this.query( - `SELECT COLUMN_NAME FROM information_schema.COLUMNS ` + `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS ` + `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'` ); @@ -83,36 +92,88 @@ export class MySqlSettingsManager extends SettingsManager { return; } - if (res.results.length > 0) { + if (res.results.length === 0) { + // ── Column doesn't exist: add it and update PK ───────────────────── + logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); + + // NOT NULL DEFAULT '' — primary key columns can't be NULL in MySQL. + // Existing rows get bot_id = '' which we'll claim for the current bot. + const alterRes = await this.query( + `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''` + ); + if (alterRes.error) { + logger.error("[Settings] Failed to add bot_id column:", alterRes.error); + return; + } + + // Claim all existing rows for the current bot before updating PK. + // This preserves existing settings (prefix, volume, etc.) instead of + // leaving them orphaned with bot_id = ''. + if (this.botId) { + await this.query( + `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` + ); + } + + // Update primary key from (id) to (id, bot_id) + const pkRes = await this.query( + `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` + ); + if (pkRes.error) { + logger.error("[Settings] Failed to update primary key:", pkRes.error); + return; // Don't set flag — bot_id features can't work without composite PK + } + + this._hasBotIdColumn = true; + logger.settings("[Settings] Auto-migration complete: bot_id column added."); + return; + } + + // ── Column already exists: verify it's in the primary key ───────────── + const colInfo = res.results[0]; + const isNullable = colInfo.IS_NULLABLE === 'YES'; + const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI'; + + if (isPrimaryKey) { + // Column exists and is part of composite PK — all good this._hasBotIdColumn = true; return; } - // Auto-migrate - logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); + // Column exists but is NOT in PK — the ALTER TABLE PK update must have + // failed previously (likely because the column had NULL values). + logger.settings("[Settings] Fixing bot_id column: adding to primary key..."); - const alterRes = await this.query( - `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) DEFAULT NULL` - ); - if (alterRes.error) { - logger.error("[Settings] Failed to add bot_id column:", alterRes.error); - return; + // Step 1: Replace NULLs with empty string (PK columns can't be Null) + if (isNullable) { + await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`); + await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`); } + // Step 2: Claim unclaimed rows (bot_id = '') for the current bot + if (this.botId) { + await this.query( + `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` + ); + } + + // Step 3: Update primary key const pkRes = await this.query( `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` ); if (pkRes.error) { logger.error("[Settings] Failed to update primary key:", pkRes.error); + return; // Don't set flag — can't use bot_id without composite PK } this._hasBotIdColumn = true; - logger.settings("[Settings] Auto-migration complete: bot_id column added."); + logger.settings("[Settings] Fix complete: bot_id column added to primary key."); } /** * Set or update the bot ID used for database row isolation. - * Ensures the bot_id column exists (auto-migrates if needed), then reloads. + * Ensures the bot_id column exists (auto-migrates if needed), claims any + * unclaimed legacy rows, then reloads guild data filtered by the bot's ID. * @param {string} id */ async setBotId(id) { @@ -121,6 +182,17 @@ export class MySqlSettingsManager extends SettingsManager { if (changed) { if (this._loadPromise) await this._loadPromise; await this._ensureBotIdColumn(); + + // Claim any unclaimed legacy rows (bot_id = '') for this bot. + if (this._hasBotIdColumn && this.botId) { + const claimRes = await this.query( + `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` + ); + if (claimRes.results?.affectedRows > 0) { + logger.settings(`[Settings] Claimed ${claimRes.results.affectedRows} legacy row(s) for bot ${this.botId}`); + } + } + this.guilds.clear(); this._loadPromise = this.load(); await this._loadPromise; @@ -222,8 +294,10 @@ export class MySqlSettingsManager extends SettingsManager { const escapedId = mysql.escape(id); const escapedData = mysql.escape(JSON.stringify(server.data)); const bi = this._botIdInsert(); + // INSERT IGNORE: if the row already exists (race condition or failed + // migration), silently skip instead of crashing with ER_DUP_ENTRY. const r = await this.query( - `INSERT INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})` + `INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})` ); if (r.error) logger.error("[Settings] create error:", r.error); } diff --git a/settings/migrate-add-bot-id.sql b/settings/migrate-add-bot-id.sql index a28b306..ed8c7a5 100644 --- a/settings/migrate-add-bot-id.sql +++ b/settings/migrate-add-bot-id.sql @@ -7,23 +7,35 @@ -- -- The auto-migration happens when setBotId() is called after Discord login: -- 1. Checks if bot_id column exists (via information_schema) --- 2. If not, adds the column and updates the primary key automatically +-- 2. If not, adds the column as NOT NULL DEFAULT '' and updates the PK +-- 3. If the column exists but isn't in the PK (broken migration from +-- previous version that used DEFAULT NULL), fixes the NULL values +-- and retries the PK update +-- 4. Claims all legacy rows (bot_id = '') for the current bot -- -- If you prefer to run it manually instead: -- mysql -u -p < settings/migrate-add-bot-id.sql -- -- After migration: --- - Existing rows have bot_id = NULL (legacy, works with both old and new code) --- - New rows created by bots will have bot_id set to the bot's user ID +-- - Existing rows are claimed by the first bot to start (bot_id set to that bot's ID) +-- - New rows created by other bots will have their own bot_id -- - The composite primary key (id, bot_id) allows the same guild to have -- separate settings per bot +-- +-- IMPORTANT: The bot_id column MUST be NOT NULL because MySQL does not allow +-- NULL values in primary key columns. The previous version used DEFAULT NULL +-- which caused ALTER TABLE ... ADD PRIMARY KEY to fail silently. --- Step 1: Add bot_id column if it doesn't exist +-- Step 1: Add bot_id column if it doesn't exist (NOT NULL DEFAULT '') ALTER TABLE settings - ADD COLUMN IF NOT EXISTS bot_id VARCHAR(32) DEFAULT NULL; + ADD COLUMN IF NOT EXISTS bot_id VARCHAR(32) NOT NULL DEFAULT ''; --- Step 2: Drop the old primary key (id) and create a composite one (id, bot_id) --- This allows the same guild ID to exist with different bot_id values. +-- Step 2: If the column exists from a previous (broken) migration with +-- DEFAULT NULL, fix the NULL values and make it NOT NULL +UPDATE settings SET bot_id = '' WHERE bot_id IS NULL; +ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''; + +-- Step 3: Drop the old primary key (id) and create a composite one (id, bot_id) -- We use a procedure because MySQL doesn't support IF EXISTS on ALTER TABLE ... DROP PRIMARY KEY -- and we want this migration to be idempotent (safe to run multiple times). @@ -55,11 +67,10 @@ DROP PROCEDURE IF EXISTS migrate_add_bot_id_pk // DELIMITER ; --- Step 3 (Optional): If you already know which bot owns which rows, +-- Step 4 (Optional): If you already know which bot owns which rows, -- you can set bot_id manually. For example, if the existing rows belong -- to a bot with ID "123456789012345678": --- UPDATE settings SET bot_id = '123456789012345678' WHERE bot_id IS NULL; +-- UPDATE settings SET bot_id = '123456789012345678' WHERE bot_id = ''; -- --- If you leave bot_id as NULL, those rows are treated as "shared" by the --- legacy code path (no bot_id filter applied). Once each bot starts up --- with the new code, it will create its own rows with bot_id set. +-- If you leave bot_id as '', the first bot to start will automatically +-- claim those rows via setBotId(). diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index 2a84b26..8664294 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -131,31 +131,75 @@ export class LastFmManager { /** * Auto-migrate: add bot_id column to lastfm_users and lastfm_stats if missing. + * Uses NOT NULL DEFAULT '' because MySQL primary key columns cannot be NULL. + * If the column exists but isn't in the PK (previous failed migration with + * DEFAULT NULL), fix the NULL values and retry the PK update. */ async _ensureBotIdColumn() { if (this._hasBotIdColumn) return; const pool = await this._getPool(); - // Check lastfm_users + // ── lastfm_users ────────────────────────────────────────────────────── const [cols] = await pool.execute( - `SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_users' AND COLUMN_NAME = 'bot_id'` + `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_users' AND COLUMN_NAME = 'bot_id'` ); if (cols.length === 0) { logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_users..."); - await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) DEFAULT NULL"); + // NOT NULL DEFAULT '' — PK columns can't be NULL in MySQL + await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); + // Claim existing rows for the current bot + if (this.botId) { + await pool.execute("UPDATE `lastfm_users` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); + } await pool.execute("ALTER TABLE `lastfm_users` DROP PRIMARY KEY, ADD PRIMARY KEY (user_id, bot_id)"); logger.settings("[LastFm] Auto-migration complete: lastfm_users.bot_id added."); + } else { + // Column exists — check if it's part of the PK + const colInfo = cols[0]; + const isNullable = colInfo.IS_NULLABLE === 'YES'; + const isPK = colInfo.COLUMN_KEY === 'PRI'; + if (!isPK) { + logger.settings("[LastFm] Fixing lastfm_users.bot_id: adding to primary key..."); + if (isNullable) { + await pool.execute("UPDATE `lastfm_users` SET `bot_id` = '' WHERE `bot_id` IS NULL"); + await pool.execute("ALTER TABLE `lastfm_users` MODIFY COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); + } + if (this.botId) { + await pool.execute("UPDATE `lastfm_users` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); + } + await pool.execute("ALTER TABLE `lastfm_users` DROP PRIMARY KEY, ADD PRIMARY KEY (user_id, bot_id)"); + logger.settings("[LastFm] Fix complete: lastfm_users.bot_id added to primary key."); + } } - // Check lastfm_stats + // ── lastfm_stats ────────────────────────────────────────────────────── const [statsCols] = await pool.execute( - `SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_stats' AND COLUMN_NAME = 'bot_id'` + `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_stats' AND COLUMN_NAME = 'bot_id'` ); if (statsCols.length === 0) { logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_stats..."); - await pool.execute("ALTER TABLE `lastfm_stats` ADD COLUMN `bot_id` VARCHAR(32) DEFAULT NULL"); + await pool.execute("ALTER TABLE `lastfm_stats` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); + if (this.botId) { + await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); + } await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)"); logger.settings("[LastFm] Auto-migration complete: lastfm_stats.bot_id added."); + } else { + const colInfo = statsCols[0]; + const isNullable = colInfo.IS_NULLABLE === 'YES'; + const isPK = colInfo.COLUMN_KEY === 'PRI'; + if (!isPK) { + logger.settings("[LastFm] Fixing lastfm_stats.bot_id: adding to primary key..."); + if (isNullable) { + await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = '' WHERE `bot_id` IS NULL"); + await pool.execute("ALTER TABLE `lastfm_stats` MODIFY COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); + } + if (this.botId) { + await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); + } + await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)"); + logger.settings("[LastFm] Fix complete: lastfm_stats.bot_id added to primary key."); + } } this._hasBotIdColumn = true; diff --git a/src/Settings.mjs b/src/Settings.mjs index 3bc4650..3e73b14 100644 --- a/src/Settings.mjs +++ b/src/Settings.mjs @@ -66,15 +66,23 @@ export class RemoteSettingsManager extends EventEmitter { } /** - * Check whether the `bot_id` column exists in the settings table. - * If it doesn't, auto-migrate by adding the column and updating the primary key. - * This ensures old databases work seamlessly with the new multi-bot code. + * Check whether the `bot_id` column exists in the settings table AND is + * part of the primary key. If the column is missing, auto-migrate by + * adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id). + * If the column exists but isn't in the PK (previous failed migration), + * fix the NULL values and retry the PK update. + * + * Key detail: MySQL primary key columns CANNOT be NULL. The previous version + * used DEFAULT NULL which caused ALTER TABLE ... ADD PRIMARY KEY to fail + * silently, leaving the PK as just (id) and producing ER_DUP_ENTRY errors + * when two bots tried to INSERT rows for the same guild. */ async _ensureBotIdColumn() { - if (this._hasBotIdColumn) return; // already checked, column exists + if (this._hasBotIdColumn) return; // already verified column + PK + // Check if bot_id column exists and its properties const res = await this.query( - `SELECT COLUMN_NAME FROM information_schema.COLUMNS ` + `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS ` + `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'` ); @@ -83,35 +91,82 @@ export class RemoteSettingsManager extends EventEmitter { return; } - if (res.results.length > 0) { - // Column already exists + if (res.results.length === 0) { + // ── Column doesn't exist: add it and update PK ───────────────────── + logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); + + // NOT NULL DEFAULT '' — primary key columns can't be NULL in MySQL. + // Existing rows get bot_id = '' which we'll claim for the current bot. + const alterRes = await this.query( + `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''` + ); + if (alterRes.error) { + logger.error("[Settings] Failed to add bot_id column:", alterRes.error); + return; + } + + // Claim all existing rows for the current bot before updating PK. + // This preserves existing settings (prefix, volume, etc.) instead of + // leaving them orphaned with bot_id = ''. + if (this.botId) { + await this.query( + `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` + ); + } + + // Update primary key from (id) to (id, bot_id) + const pkRes = await this.query( + `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` + ); + if (pkRes.error) { + logger.error("[Settings] Failed to update primary key:", pkRes.error); + return; // Don't set flag — bot_id features can't work without composite PK + } + + this._hasBotIdColumn = true; + logger.settings("[Settings] Auto-migration complete: bot_id column added."); + return; + } + + // ── Column already exists: verify it's in the primary key ───────────── + const colInfo = res.results[0]; + const isNullable = colInfo.IS_NULLABLE === 'YES'; + const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI'; + + if (isPrimaryKey) { + // Column exists and is part of composite PK — all good this._hasBotIdColumn = true; return; } - // Auto-migrate: add bot_id column and update primary key - logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); + // Column exists but is NOT in PK — the ALTER TABLE PK update must have + // failed previously (likely because the column had NULL values). + logger.settings("[Settings] Fixing bot_id column: adding to primary key..."); - const alterRes = await this.query( - `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) DEFAULT NULL` - ); - if (alterRes.error) { - logger.error("[Settings] Failed to add bot_id column:", alterRes.error); - return; + // Step 1: Replace NULLs with empty string (PK columns can't be NULL) + if (isNullable) { + await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`); + await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`); } - // Update primary key from (id) to (id, bot_id) + // Step 2: Claim unclaimed rows (bot_id = '') for the current bot + if (this.botId) { + await this.query( + `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` + ); + } + + // Step 3: Update primary key const pkRes = await this.query( `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` ); if (pkRes.error) { logger.error("[Settings] Failed to update primary key:", pkRes.error); - // Column was added but PK update failed — still mark as available - // since the column exists and queries will work + return; // Don't set flag — can't use bot_id without composite PK } this._hasBotIdColumn = true; - logger.settings("[Settings] Auto-migration complete: bot_id column added."); + logger.settings("[Settings] Fix complete: bot_id column added to primary key."); } /** @@ -129,6 +184,19 @@ export class RemoteSettingsManager extends EventEmitter { if (this._loadPromise) await this._loadPromise; // Ensure the DB schema supports bot_id before querying with it await this._ensureBotIdColumn(); + + // Claim any unclaimed legacy rows (bot_id = '') for this bot. + // This handles the case where the column was already properly set up + // (e.g. by another bot's migration) but legacy rows weren't claimed yet. + if (this._hasBotIdColumn && this.botId) { + const claimRes = await this.query( + `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` + ); + if (claimRes.results?.affectedRows > 0) { + logger.settings(`[Settings] Claimed ${claimRes.results.affectedRows} legacy row(s) for bot ${this.botId}`); + } + } + // Reload with the new botId so we pick up this bot's rows this.guilds.clear(); this._loadPromise = this.load(); @@ -248,7 +316,11 @@ export class RemoteSettingsManager extends EventEmitter { const escapedId = mysql.escape(id); const escapedData = mysql.escape(JSON.stringify(server.data)); const bi = this._botIdInsert(); - const r = await this.query(`INSERT INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})`); + // INSERT IGNORE: if the row already exists (race condition or failed + // migration), silently skip instead of crashing with ER_DUP_ENTRY. + const r = await this.query( + `INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})` + ); if (r.error) logger.error("[Settings] create error:", r.error); }