feat: script de migration des données SQLite vers MySQL/MariaDB

Copie toutes les tables en conservant les ids, dans une seule transaction,
avec rapport de lignes par table. Refuse une cible non vide sauf --force.
Ajoute les scripts npm migrate:sqlite et test:mysql.
This commit is contained in:
Tony AVERTY 2026-10-22 13:01:53 +02:00
parent 637ac8ccb6
commit a7bcbcdc33
3 changed files with 230 additions and 0 deletions

View file

@ -12,6 +12,8 @@
"dev": "node --env-file=.env --watch --no-warnings=ExperimentalWarning src/server.js", "dev": "node --env-file=.env --watch --no-warnings=ExperimentalWarning src/server.js",
"lint": "node scripts/check-syntax.js", "lint": "node scripts/check-syntax.js",
"test": "node --no-warnings=ExperimentalWarning --test 'test/**/*.test.js'", "test": "node --no-warnings=ExperimentalWarning --test 'test/**/*.test.js'",
"test:mysql": "node --no-warnings=ExperimentalWarning --test --test-concurrency=1 'test/**/*.test.js'",
"migrate:sqlite": "node --env-file=.env --no-warnings=ExperimentalWarning scripts/migrate-sqlite-to-mysql.js",
"check": "npm run lint && npm run test", "check": "npm run lint && npm run test",
"hooks": "git config core.hooksPath .githooks" "hooks": "git config core.hooksPath .githooks"
}, },

View file

@ -0,0 +1,123 @@
// Copie une ancienne base SQLite (data/aitools.sqlite) vers la base MySQL/MariaDB, ids conservés.
//
// node --env-file=.env scripts/migrate-sqlite-to-mysql.js data/aitools.sqlite [--force]
//
// - cible = variables DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME (les migrations sont appliquées avant la copie) ;
// - tout se passe dans UNE transaction : en cas d'erreur ou de comptes différents, rien n'est écrit ;
// - refuse si la cible contient déjà des données, sauf --force (qui VIDE alors les tables cibles avant la copie) ;
// - la source est ouverte en lecture seule. Arrête l'ancien service avant, pour copier une base figée.
import { DatabaseSync } from 'node:sqlite';
import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { openDb, dbConfigFromEnv, MIGRATIONS } from '../src/db.js';
// Ordre de copie : parents avant enfants (clés étrangères). La suppression (--force) suit l'ordre inverse.
export const TABLES = [
'settings', 'sessions', 'oauth_states', 'projects', 'templates', 'prospects', 'blacklist',
'jobs', 'mail_log', 'prospect_notes', 'metrics_daily',
];
const LEGACY_USER_VERSION = 8; // dernière version du schéma de l'ancienne base SQLite à user_version
const BATCH = 200;
const q = (name) => `\`${name}\``;
// Vérifie que la source est au schéma attendu (sinon des colonnes manqueraient en silence)
function checkSourceVersion(src) {
const hasTable = (n) => src.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(n);
if (hasTable('schema_migrations')) {
const v = src.prepare('SELECT MAX(version) v FROM schema_migrations').get().v;
if (v !== MIGRATIONS.length) throw new Error(`Schéma source en version ${v}, attendu ${MIGRATIONS.length}`);
return;
}
const { user_version: uv } = src.prepare('PRAGMA user_version').get();
if (uv !== LEGACY_USER_VERSION) {
throw new Error(`Base SQLite en version ${uv}, attendue ${LEGACY_USER_VERSION} : lance d'abord l'ancienne version de l'application pour la mettre à jour.`);
}
}
async function targetColumns(dialect, db, table) {
if (dialect === 'sqlite') return (await db.query(`PRAGMA table_info(${table})`)).map((c) => c.name);
const rows = await db.query('SELECT column_name c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ?', [table]);
return rows.map((r) => r.c ?? r.COLUMN_NAME);
}
/**
* @param {{ sourcePath: string, db: object, force?: boolean, log?: (line: string) => void }} o
* @returns {Promise<{ tables: {table: string, source: number, copied: number, target: number}[], total: number }>}
*/
export async function migrateSqliteToMysql({ sourcePath, db, force = false, log = () => {} }) {
if (!existsSync(sourcePath)) throw new Error(`Fichier introuvable : ${sourcePath}`);
const src = new DatabaseSync(sourcePath, { readOnly: true });
try {
checkSourceVersion(src);
// Cible vide ?
const filled = [];
for (const t of TABLES) {
const n = (await db.prepare(`SELECT COUNT(*) n FROM ${q(t)}`).get()).n;
if (n > 0) filled.push(`${t} (${n})`);
}
if (filled.length && !force) {
throw new Error(`La base cible n'est pas vide : ${filled.join(', ')}. Relance avec --force pour la vider avant la copie.`);
}
const report = [];
await db.transaction(async (tx) => {
if (filled.length) {
log(`--force : vidage de la cible (${filled.join(', ')})`);
for (const t of [...TABLES].reverse()) await tx.prepare(`DELETE FROM ${q(t)}`).run();
}
for (const table of TABLES) {
const srcCols = src.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name);
if (!srcCols.length) throw new Error(`Table source absente : ${table}`);
const dstCols = new Set(await targetColumns(db.dialect, tx, table));
const lost = srcCols.filter((c) => !dstCols.has(c));
if (lost.length) throw new Error(`${table} : colonnes sans équivalent dans la cible (${lost.join(', ')})`);
const rows = src.prepare(`SELECT ${srcCols.map(q).join(', ')} FROM ${q(table)}`).all();
const sqlHead = `INSERT INTO ${q(table)} (${srcCols.map(q).join(', ')}) VALUES `;
const one = `(${srcCols.map(() => '?').join(', ')})`;
let copied = 0;
for (let i = 0; i < rows.length; i += BATCH) {
const chunk = rows.slice(i, i + BATCH);
const res = await tx.prepare(sqlHead + chunk.map(() => one).join(', ')).run(...chunk.flatMap((r) => srcCols.map((c) => r[c])));
copied += res.changes;
}
const target = (await tx.prepare(`SELECT COUNT(*) n FROM ${q(table)}`).get()).n;
report.push({ table, source: rows.length, copied, target });
log(`${table.padEnd(16)} source ${String(rows.length).padStart(6)} copiées ${String(copied).padStart(6)} cible ${String(target).padStart(6)}`);
// Toute différence annule la transaction : on ne laisse jamais une copie partielle
if (copied !== rows.length || target !== rows.length) {
throw new Error(`${table} : ${rows.length} lignes en source, ${copied} copiées, ${target} en cible. Copie annulée.`);
}
}
});
return { tables: report, total: report.reduce((t, r) => t + r.copied, 0) };
} finally {
src.close();
}
}
async function main() {
const args = process.argv.slice(2);
const force = args.includes('--force');
const sourcePath = args.find((a) => !a.startsWith('--'));
if (!sourcePath) {
console.error('Usage : node --env-file=.env scripts/migrate-sqlite-to-mysql.js <chemin/aitools.sqlite> [--force]');
process.exit(2);
}
const cfg = dbConfigFromEnv();
if (cfg.driver !== 'mysql') throw new Error('La cible doit être MySQL/MariaDB (DB_HOST, DB_USER, DB_NAME).');
console.log(`Source : ${sourcePath}\nCible : ${cfg.user}@${cfg.host}:${cfg.port}/${cfg.database}${force ? ' (--force)' : ''}\n`);
const db = await openDb(cfg);
try {
const { total } = await migrateSqliteToMysql({ sourcePath, db, force, log: console.log });
console.log(`\nTerminé : ${total} lignes copiées, comptes identiques entre source et cible.`);
} finally {
await db.close();
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main().catch((e) => { console.error(`\nÉchec : ${e.message}`); process.exit(1); });
}

105
test/migrate-sqlite.test.js Normal file
View file

@ -0,0 +1,105 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { DatabaseSync } from 'node:sqlite';
import { openDb, now } from '../src/db.js';
import { migrateSqliteToMysql, TABLES } from '../scripts/migrate-sqlite-to-mysql.js';
import { testDb } from './helpers/db.js';
// Fabrique une "ancienne" base : schéma à jour, ids non contigus, accents, puis marquée user_version 8
async function legacyFile(dir) {
const file = join(dir, 'aitools.sqlite');
const db = await openDb({ driver: 'sqlite', file });
const t = now();
await db.prepare('INSERT INTO projects(id, name, git_url, daily_mail_cap, created_at) VALUES(?, ?, ?, ?, ?)').run(7, 'Café Été', 'https://git.x/a.git', 12, t);
await db.prepare('INSERT INTO projects(id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(42, 'Autre', 'https://git.x/b.git', t);
await db.prepare('INSERT INTO prospects(id, project_id, company, email, score, created_at) VALUES(?, ?, ?, ?, ?, ?)').run(1001, 7, 'Boulangerie Léa', 'lea@x.fr', 8, t);
await db.prepare('INSERT INTO prospects(id, project_id, company, email, created_at) VALUES(?, ?, ?, ?, ?)').run(1002, 7, 'Garage', 'g@x.fr', t);
await db.prepare('INSERT INTO prospect_notes(id, prospect_id, body, created_at) VALUES(?, ?, ?, ?)').run(5, 1001, 'à rappeler 🙂', t);
await db.prepare('INSERT INTO templates(project_id, kind, subject, body, updated_at) VALUES(?, ?, ?, ?, ?)').run(7, 'initial', 'Objet', 'Corps', t);
await db.prepare('INSERT INTO jobs(id, project_id, type, status, cost_usd, created_at) VALUES(?, ?, ?, ?, ?, ?)').run(300, 7, 'analyze', 'done', 0.0123, t);
await db.prepare('INSERT INTO mail_log(id, project_id, prospect_id, email, sent_at, message_id) VALUES(?, ?, ?, ?, ?, ?)').run(9, 7, 1001, 'lea@x.fr', t, '<a@b>');
await db.prepare('INSERT INTO blacklist(email, reason, created_at) VALUES(?, ?, ?)').run('no@x.fr', 'unsubscribe', t);
await db.prepare('INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, ?, ?, ?)').run(7, '2026-10-21', 10, 2, 99.5);
await db.prepare('INSERT INTO settings(`key`, value) VALUES(?, ?)').run('notify_email', 'tony@x.fr');
await db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)').run('AbC_d-1', 'tony@x.fr', t, t + 100);
await db.close();
// Ancien format : pas de schema_migrations, version dans user_version
const raw = new DatabaseSync(file);
raw.exec('DROP TABLE schema_migrations; PRAGMA user_version = 8;');
raw.close();
return file;
}
test('migration SQLite → cible : ids conservés, comptes identiques, rapport par table', async () => {
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
try {
const sourcePath = await legacyFile(dir);
const db = await testDb();
const lines = [];
const r = await migrateSqliteToMysql({ sourcePath, db, log: (l) => lines.push(l) });
assert.deepEqual(r.tables.map((x) => x.table), TABLES);
for (const x of r.tables) assert.equal(x.source, x.target, x.table);
assert.equal(r.tables.find((x) => x.table === 'prospects').copied, 2);
assert.equal(r.total, 12);
assert.equal(lines.length, TABLES.length);
assert.deepEqual((await db.prepare('SELECT id, name FROM projects ORDER BY id').all()).map((p) => [p.id, p.name]), [[7, 'Café Été'], [42, 'Autre']]);
assert.equal((await db.prepare('SELECT company FROM prospects WHERE id = ?').get(1001)).company, 'Boulangerie Léa');
assert.equal((await db.prepare('SELECT body FROM prospect_notes WHERE id = 5').get()).body, 'à rappeler 🙂');
assert.equal((await db.prepare('SELECT cost_usd FROM jobs WHERE id = 300').get()).cost_usd, 0.0123);
assert.equal((await db.prepare('SELECT daily_mail_cap FROM projects WHERE id = 7').get()).daily_mail_cap, 12);
assert.equal((await db.prepare('SELECT revenue FROM metrics_daily').get()).revenue, 99.5);
assert.equal((await db.prepare('SELECT id FROM sessions').get()).id, 'AbC_d-1');
// Les relations survivent à la copie : suppression en cascade
await db.prepare('DELETE FROM projects WHERE id = 7').run();
assert.equal((await db.prepare('SELECT COUNT(*) n FROM prospects').get()).n, 0);
// Les nouvelles lignes continuent après le plus grand id copié
const next = await db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('Neuf', 'https://git.x/c.git', now());
assert.ok(next.lastInsertRowid > 42);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('migration : refuse une cible non vide, --force la vide puis copie', async () => {
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
try {
const sourcePath = await legacyFile(dir);
const db = await testDb();
await db.prepare('INSERT INTO projects(id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(1, 'Déjà là', 'https://git.x/z.git', now());
await assert.rejects(migrateSqliteToMysql({ sourcePath, db }), /pas vide.*projects \(1\).*--force/s);
assert.equal((await db.prepare('SELECT COUNT(*) n FROM projects').get()).n, 1, 'rien n\'a été touché');
const r = await migrateSqliteToMysql({ sourcePath, db, force: true });
assert.equal(r.total, 12);
assert.deepEqual((await db.prepare('SELECT id FROM projects ORDER BY id').all()).map((p) => p.id), [7, 42]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('migration : une erreur en cours de copie annule tout (transaction)', async () => {
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
try {
const sourcePath = await legacyFile(dir);
// Source corrompue après coup : un prospect pointe vers un projet qui n'existe pas
const raw = new DatabaseSync(sourcePath);
raw.exec('PRAGMA foreign_keys = OFF; UPDATE prospects SET project_id = 999 WHERE id = 1002;');
raw.close();
const db = await testDb();
await assert.rejects(migrateSqliteToMysql({ sourcePath, db }), /FOREIGN KEY|child row/i);
for (const t of TABLES) assert.equal((await db.prepare(`SELECT COUNT(*) n FROM \`${t}\``).get()).n, 0, `${t} doit rester vide`);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('migration : refuse une source dans une mauvaise version ou absente', async () => {
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
try {
const sourcePath = await legacyFile(dir);
const raw = new DatabaseSync(sourcePath);
raw.exec('PRAGMA user_version = 5;');
raw.close();
const db = await testDb();
await assert.rejects(migrateSqliteToMysql({ sourcePath, db }), /version 5/);
await assert.rejects(migrateSqliteToMysql({ sourcePath: join(dir, 'nope.sqlite'), db }), /introuvable/);
} finally { rmSync(dir, { recursive: true, force: true }); }
});