mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
hotfix
This commit is contained in:
1 parent
db0ca569ee
commit
685c8a9215
4 files changed
+247
-46
No files matched your search
+86
-12
@@ -67,14 +67,23 @@ export class MySqlSettingsManager extends SettingsManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check whether the `bot_id` column exists in the settings table.
|
* Check whether the `bot_id` column exists in the settings table AND is
|
||||||
* If it doesn't, auto-migrate by adding the column and updating the primary key.
|
* 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() {
|
async _ensureBotIdColumn() {
|
||||||
if (this._hasBotIdColumn) return;
|
if (this._hasBotIdColumn) return;
|
||||||
|
|
||||||
|
// Check if bot_id column exists and its properties
|
||||||
const res = await this.query(
|
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'`
|
+ `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'`
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -83,36 +92,88 @@ export class MySqlSettingsManager extends SettingsManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (res.results.length > 0) {
|
if (res.results.length === 0) {
|
||||||
this._hasBotIdColumn = true;
|
// ── Column doesn't exist: add it and update PK ─────────────────────
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Auto-migrate
|
|
||||||
logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table...");
|
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(
|
const alterRes = await this.query(
|
||||||
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) DEFAULT NULL`
|
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`
|
||||||
);
|
);
|
||||||
if (alterRes.error) {
|
if (alterRes.error) {
|
||||||
logger.error("[Settings] Failed to add bot_id column:", alterRes.error);
|
logger.error("[Settings] Failed to add bot_id column:", alterRes.error);
|
||||||
return;
|
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(
|
const pkRes = await this.query(
|
||||||
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
||||||
);
|
);
|
||||||
if (pkRes.error) {
|
if (pkRes.error) {
|
||||||
logger.error("[Settings] Failed to update primary key:", 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;
|
this._hasBotIdColumn = true;
|
||||||
logger.settings("[Settings] Auto-migration complete: bot_id column added.");
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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...");
|
||||||
|
|
||||||
|
// 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] Fix complete: bot_id column added to primary key.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set or update the bot ID used for database row isolation.
|
* 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
|
* @param {string} id
|
||||||
*/
|
*/
|
||||||
async setBotId(id) {
|
async setBotId(id) {
|
||||||
@@ -121,6 +182,17 @@ export class MySqlSettingsManager extends SettingsManager {
|
|||||||
if (changed) {
|
if (changed) {
|
||||||
if (this._loadPromise) await this._loadPromise;
|
if (this._loadPromise) await this._loadPromise;
|
||||||
await this._ensureBotIdColumn();
|
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.guilds.clear();
|
||||||
this._loadPromise = this.load();
|
this._loadPromise = this.load();
|
||||||
await this._loadPromise;
|
await this._loadPromise;
|
||||||
@@ -222,8 +294,10 @@ export class MySqlSettingsManager extends SettingsManager {
|
|||||||
const escapedId = mysql.escape(id);
|
const escapedId = mysql.escape(id);
|
||||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
const escapedData = mysql.escape(JSON.stringify(server.data));
|
||||||
const bi = this._botIdInsert();
|
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(
|
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);
|
if (r.error) logger.error("[Settings] create error:", r.error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,23 +7,35 @@
|
|||||||
--
|
--
|
||||||
-- The auto-migration happens when setBotId() is called after Discord login:
|
-- The auto-migration happens when setBotId() is called after Discord login:
|
||||||
-- 1. Checks if bot_id column exists (via information_schema)
|
-- 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:
|
-- If you prefer to run it manually instead:
|
||||||
-- mysql -u <user> -p <database> < settings/migrate-add-bot-id.sql
|
-- mysql -u <user> -p <database> < settings/migrate-add-bot-id.sql
|
||||||
--
|
--
|
||||||
-- After migration:
|
-- After migration:
|
||||||
-- - Existing rows have bot_id = NULL (legacy, works with both old and new code)
|
-- - Existing rows are claimed by the first bot to start (bot_id set to that bot's ID)
|
||||||
-- - New rows created by bots will have bot_id set to the bot's user 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
|
-- - The composite primary key (id, bot_id) allows the same guild to have
|
||||||
-- separate settings per bot
|
-- 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
|
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)
|
-- Step 2: If the column exists from a previous (broken) migration with
|
||||||
-- This allows the same guild ID to exist with different bot_id values.
|
-- 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
|
-- 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).
|
-- 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 ;
|
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
|
-- you can set bot_id manually. For example, if the existing rows belong
|
||||||
-- to a bot with ID "123456789012345678":
|
-- 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
|
-- If you leave bot_id as '', the first bot to start will automatically
|
||||||
-- legacy code path (no bot_id filter applied). Once each bot starts up
|
-- claim those rows via setBotId().
|
||||||
-- with the new code, it will create its own rows with bot_id set.
|
|
||||||
+50
-6
@@ -131,31 +131,75 @@ export class LastFmManager {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto-migrate: add bot_id column to lastfm_users and lastfm_stats if missing.
|
* 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() {
|
async _ensureBotIdColumn() {
|
||||||
if (this._hasBotIdColumn) return;
|
if (this._hasBotIdColumn) return;
|
||||||
const pool = await this._getPool();
|
const pool = await this._getPool();
|
||||||
|
|
||||||
// Check lastfm_users
|
// ── lastfm_users ──────────────────────────────────────────────────────
|
||||||
const [cols] = await pool.execute(
|
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) {
|
if (cols.length === 0) {
|
||||||
logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_users...");
|
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)");
|
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.");
|
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(
|
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) {
|
if (statsCols.length === 0) {
|
||||||
logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_stats...");
|
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)");
|
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.");
|
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;
|
this._hasBotIdColumn = true;
|
||||||
|
|||||||
+88
-16
@@ -66,15 +66,23 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check whether the `bot_id` column exists in the settings table.
|
* Check whether the `bot_id` column exists in the settings table AND is
|
||||||
* If it doesn't, auto-migrate by adding the column and updating the primary key.
|
* part of the primary key. If the column is missing, auto-migrate by
|
||||||
* This ensures old databases work seamlessly with the new multi-bot code.
|
* 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() {
|
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(
|
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'`
|
+ `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'`
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -83,35 +91,82 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (res.results.length > 0) {
|
if (res.results.length === 0) {
|
||||||
// Column already exists
|
// ── Column doesn't exist: add it and update PK ─────────────────────
|
||||||
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...");
|
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(
|
const alterRes = await this.query(
|
||||||
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) DEFAULT NULL`
|
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`
|
||||||
);
|
);
|
||||||
if (alterRes.error) {
|
if (alterRes.error) {
|
||||||
logger.error("[Settings] Failed to add bot_id column:", alterRes.error);
|
logger.error("[Settings] Failed to add bot_id column:", alterRes.error);
|
||||||
return;
|
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)
|
// Update primary key from (id) to (id, bot_id)
|
||||||
const pkRes = await this.query(
|
const pkRes = await this.query(
|
||||||
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
||||||
);
|
);
|
||||||
if (pkRes.error) {
|
if (pkRes.error) {
|
||||||
logger.error("[Settings] Failed to update primary key:", pkRes.error);
|
logger.error("[Settings] Failed to update primary key:", pkRes.error);
|
||||||
// Column was added but PK update failed — still mark as available
|
return; // Don't set flag — bot_id features can't work without composite PK
|
||||||
// since the column exists and queries will work
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this._hasBotIdColumn = true;
|
this._hasBotIdColumn = true;
|
||||||
logger.settings("[Settings] Auto-migration complete: bot_id column added.");
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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...");
|
||||||
|
|
||||||
|
// 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] Fix complete: bot_id column added to primary key.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -129,6 +184,19 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
if (this._loadPromise) await this._loadPromise;
|
if (this._loadPromise) await this._loadPromise;
|
||||||
// Ensure the DB schema supports bot_id before querying with it
|
// Ensure the DB schema supports bot_id before querying with it
|
||||||
await this._ensureBotIdColumn();
|
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
|
// Reload with the new botId so we pick up this bot's rows
|
||||||
this.guilds.clear();
|
this.guilds.clear();
|
||||||
this._loadPromise = this.load();
|
this._loadPromise = this.load();
|
||||||
@@ -248,7 +316,11 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
const escapedId = mysql.escape(id);
|
const escapedId = mysql.escape(id);
|
||||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
const escapedData = mysql.escape(JSON.stringify(server.data));
|
||||||
const bi = this._botIdInsert();
|
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);
|
if (r.error) logger.error("[Settings] create error:", r.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user