feat(migration): rattache les données de l'ancienne base SQLite au propriétaire
Le script crée (ou retrouve) le compte propriétaire depuis ADMIN_EMAILS, lui rattache projets et jobs, convertit les anciens réglages en réglages de ce compte et ne copie plus les sessions. Il refuse une source déjà au schéma multi-utilisateur.
This commit is contained in:
parent
2fa90072dc
commit
abfbf02199
2 changed files with 94 additions and 37 deletions
|
|
@ -3,20 +3,28 @@
|
|||
// 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) ;
|
||||
// - l'ancienne base est mono-utilisateur : toutes ses données sont rattachées au propriétaire, c'est-à-dire la
|
||||
// première adresse de ADMIN_EMAILS (compte créé s'il n'existe pas) ; les anciens réglages deviennent ses réglages ;
|
||||
// - les sessions et les états OAuth de l'ancienne base ne sont pas copiés (éphémères, liés à l'ancien modèle) ;
|
||||
// - 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';
|
||||
import { openDb, dbConfigFromEnv, now } from '../src/db.js';
|
||||
|
||||
// Ordre de copie : parents avant enfants (clés étrangères). La suppression (--force) suit l'ordre inverse.
|
||||
// `settings` (clé/valeur globale) devient `user_settings` du propriétaire.
|
||||
export const TABLES = [
|
||||
'settings', 'sessions', 'oauth_states', 'projects', 'templates', 'prospects', 'blacklist',
|
||||
'settings', 'projects', 'templates', 'prospects', 'blacklist',
|
||||
'jobs', 'mail_log', 'prospect_notes', 'metrics_daily',
|
||||
];
|
||||
export const SKIPPED = ['sessions', 'oauth_states'];
|
||||
const TARGET_TABLE = { settings: 'user_settings' };
|
||||
const OWNED = new Set(['settings', 'projects', 'jobs']); // tables de la cible qui portent un user_id
|
||||
const LEGACY_USER_VERSION = 8; // dernière version du schéma de l'ancienne base SQLite à user_version
|
||||
const LEGACY_MIGRATION = 1; // schéma consolidé de la migration 1 (avant les comptes)
|
||||
const BATCH = 200;
|
||||
|
||||
const q = (name) => `\`${name}\``;
|
||||
|
|
@ -26,7 +34,9 @@ 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}`);
|
||||
if (v !== LEGACY_MIGRATION) {
|
||||
throw new Error(`Schéma source en version ${v}, attendu ${LEGACY_MIGRATION} (base d'avant les comptes). Une base déjà au schéma multi-utilisateur ne se copie pas avec ce script.`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const { user_version: uv } = src.prepare('PRAGMA user_version').get();
|
||||
|
|
@ -42,10 +52,12 @@ async function targetColumns(dialect, db, table) {
|
|||
}
|
||||
|
||||
/**
|
||||
* @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 }>}
|
||||
* @param {{ sourcePath: string, db: object, ownerEmail: string, force?: boolean, log?: (line: string) => void }} o
|
||||
* @returns {Promise<{ tables: {table: string, source: number, copied: number, target: number}[], total: number, ownerId: number }>}
|
||||
*/
|
||||
export async function migrateSqliteToMysql({ sourcePath, db, force = false, log = () => {} }) {
|
||||
export async function migrateSqliteToMysql({ sourcePath, db, ownerEmail, force = false, log = () => {} }) {
|
||||
const owner = String(ownerEmail || '').trim().toLowerCase();
|
||||
if (!owner) throw new Error('Propriétaire des données manquant : définis ADMIN_EMAILS (la première adresse est utilisée).');
|
||||
if (!existsSync(sourcePath)) throw new Error(`Fichier introuvable : ${sourcePath}`);
|
||||
const src = new DatabaseSync(sourcePath, { readOnly: true });
|
||||
try {
|
||||
|
|
@ -54,36 +66,49 @@ export async function migrateSqliteToMysql({ sourcePath, db, force = false, log
|
|||
// 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})`);
|
||||
const target = TARGET_TABLE[t] || t;
|
||||
const n = (await db.prepare(`SELECT COUNT(*) n FROM ${q(target)}`).get()).n;
|
||||
if (n > 0) filled.push(`${target} (${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 = [];
|
||||
let ownerId;
|
||||
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 t of [...TABLES].reverse()) await tx.prepare(`DELETE FROM ${q(TARGET_TABLE[t] || t)}`).run();
|
||||
}
|
||||
// Le propriétaire : compte existant (même email) ou créé ici, administrateur
|
||||
const found = await tx.prepare('SELECT id FROM users WHERE email = ?').get(owner);
|
||||
ownerId = found
|
||||
? Number(found.id)
|
||||
: Number((await tx.prepare("INSERT INTO users(email, status, is_admin, plan, created_at) VALUES(?, 'active', 1, 'free', ?)").run(owner, now())).lastInsertRowid);
|
||||
log(`propriétaire ${owner} (id ${ownerId})`);
|
||||
|
||||
for (const table of TABLES) {
|
||||
const targetTable = TARGET_TABLE[table] || table;
|
||||
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 dstCols = new Set(await targetColumns(db.dialect, tx, targetTable));
|
||||
const lost = srcCols.filter((c) => !dstCols.has(c));
|
||||
if (lost.length) throw new Error(`${table} : colonnes sans équivalent dans la cible (${lost.join(', ')})`);
|
||||
|
||||
const owned = OWNED.has(table);
|
||||
const cols = owned ? ['user_id', ...srcCols] : srcCols;
|
||||
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(', ')})`;
|
||||
const sqlHead = `INSERT INTO ${q(targetTable)} (${cols.map(q).join(', ')}) VALUES `;
|
||||
const one = `(${cols.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])));
|
||||
const values = chunk.flatMap((r) => (owned ? [ownerId] : []).concat(srcCols.map((c) => r[c])));
|
||||
const res = await tx.prepare(sqlHead + chunk.map(() => one).join(', ')).run(...values);
|
||||
copied += res.changes;
|
||||
}
|
||||
const target = (await tx.prepare(`SELECT COUNT(*) n FROM ${q(table)}`).get()).n;
|
||||
const target = (await tx.prepare(`SELECT COUNT(*) n FROM ${q(targetTable)}${owned ? ' WHERE user_id = ?' : ''}`).get(...(owned ? [ownerId] : []))).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
|
||||
|
|
@ -92,7 +117,7 @@ export async function migrateSqliteToMysql({ sourcePath, db, force = false, log
|
|||
}
|
||||
}
|
||||
});
|
||||
return { tables: report, total: report.reduce((t, r) => t + r.copied, 0) };
|
||||
return { tables: report, total: report.reduce((t, r) => t + r.copied, 0), ownerId };
|
||||
} finally {
|
||||
src.close();
|
||||
}
|
||||
|
|
@ -108,11 +133,12 @@ async function main() {
|
|||
}
|
||||
const cfg = dbConfigFromEnv();
|
||||
if (cfg.driver !== 'mysql') throw new Error('La cible doit être MySQL/MariaDB (DB_HOST, DB_USER, DB_NAME).');
|
||||
const adminEmails = (process.env.ADMIN_EMAILS || '').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean);
|
||||
console.log(`Source : ${sourcePath}\nCible : ${cfg.user}@${cfg.host}:${cfg.port}/${cfg.database}${force ? ' (--force)' : ''}\n`);
|
||||
const db = await openDb(cfg);
|
||||
const db = await openDb(cfg, { adminEmails });
|
||||
try {
|
||||
const { total } = await migrateSqliteToMysql({ sourcePath, db, force, log: console.log });
|
||||
console.log(`\nTerminé : ${total} lignes copiées, comptes identiques entre source et cible.`);
|
||||
const { total } = await migrateSqliteToMysql({ sourcePath, db, ownerEmail: adminEmails[0], force, log: console.log });
|
||||
console.log(`\nTerminé : ${total} lignes copiées, comptes identiques entre source et cible. Sessions de l'ancienne base non copiées : reconnecte-toi.`);
|
||||
} finally {
|
||||
await db.close();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,11 +7,15 @@ 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';
|
||||
import { addUser } from './helpers/users.js';
|
||||
|
||||
// Fabrique une "ancienne" base : schéma à jour, ids non contigus, accents, puis marquée user_version 8
|
||||
const OWNER = 'tony@x.fr';
|
||||
|
||||
// Fabrique une "ancienne" base mono-utilisateur : schéma d'avant les comptes (migration 1), ids non contigus,
|
||||
// accents, puis marquée user_version 8 (ancien format sans schema_migrations)
|
||||
async function legacyFile(dir) {
|
||||
const file = join(dir, 'aitools.sqlite');
|
||||
const db = await openDb({ driver: 'sqlite', file });
|
||||
const db = await openDb({ driver: 'sqlite', file }, { upTo: 1 });
|
||||
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);
|
||||
|
|
@ -33,51 +37,73 @@ async function legacyFile(dir) {
|
|||
return file;
|
||||
}
|
||||
|
||||
test('migration SQLite → cible : ids conservés, comptes identiques, rapport par table', async () => {
|
||||
test('migration SQLite → cible : ids conservés, tout rattaché au propriétaire, comptes identiques', 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) });
|
||||
const r = await migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER, 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.equal(r.total, 11, 'les sessions de l\'ancienne base ne sont pas copiées');
|
||||
assert.equal(lines.length, TABLES.length + 1, 'une ligne par table + le propriétaire');
|
||||
|
||||
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']]);
|
||||
const owner = await db.prepare('SELECT id, is_admin, status FROM users WHERE email = ?').get(OWNER);
|
||||
assert.equal(owner.is_admin, 1);
|
||||
assert.equal(owner.id, r.ownerId);
|
||||
assert.equal((await db.prepare('SELECT COUNT(*) n FROM users').get()).n, 1);
|
||||
assert.deepEqual((await db.prepare('SELECT id, name, user_id FROM projects ORDER BY id').all()).map((p) => [p.id, p.name, Number(p.user_id)]),
|
||||
[[7, 'Café Été', owner.id], [42, 'Autre', owner.id]]);
|
||||
assert.equal((await db.prepare('SELECT user_id FROM jobs WHERE id = 300').get()).user_id, owner.id);
|
||||
assert.deepEqual({ ...(await db.prepare('SELECT user_id, `key`, value FROM user_settings').get()) }, { user_id: owner.id, key: 'notify_email', value: 'tony@x.fr' });
|
||||
assert.equal((await db.prepare('SELECT COUNT(*) n FROM sessions').get()).n, 0);
|
||||
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());
|
||||
const next = await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(owner.id, 'Neuf', 'https://git.x/c.git', now());
|
||||
assert.ok(next.lastInsertRowid > 42);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('migration : le propriétaire existant (même email) est réutilisé, l\'email est obligatoire', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||
try {
|
||||
const sourcePath = await legacyFile(dir);
|
||||
const db = await testDb();
|
||||
const id = await addUser(db, { email: OWNER, admin: false });
|
||||
await assert.rejects(migrateSqliteToMysql({ sourcePath, db, ownerEmail: '' }), /ADMIN_EMAILS/);
|
||||
const r = await migrateSqliteToMysql({ sourcePath, db, ownerEmail: 'Tony@X.fr' });
|
||||
assert.equal(r.ownerId, id);
|
||||
assert.equal((await db.prepare('SELECT COUNT(*) n FROM users').get()).n, 1);
|
||||
assert.equal((await db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(id)).n, 2);
|
||||
} 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);
|
||||
const u = await addUser(db, { email: OWNER });
|
||||
await db.prepare('INSERT INTO projects(id, user_id, name, git_url, created_at) VALUES(?, ?, ?, ?, ?)').run(1, u, 'Déjà là', 'https://git.x/z.git', now());
|
||||
await assert.rejects(migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER }), /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);
|
||||
const r = await migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER, force: true });
|
||||
assert.equal(r.total, 11);
|
||||
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 () => {
|
||||
test('migration : une erreur en cours de copie annule tout (transaction), propriétaire compris', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||
try {
|
||||
const sourcePath = await legacyFile(dir);
|
||||
|
|
@ -86,12 +112,13 @@ test('migration : une erreur en cours de copie annule tout (transaction)', async
|
|||
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`);
|
||||
await assert.rejects(migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER }), /FOREIGN KEY|child row/i);
|
||||
for (const t of TABLES) assert.equal((await db.prepare(`SELECT COUNT(*) n FROM \`${t === 'settings' ? 'user_settings' : t}\``).get()).n, 0, `${t} doit rester vide`);
|
||||
assert.equal((await db.prepare('SELECT COUNT(*) n FROM users').get()).n, 0, 'le propriétaire n\'est pas créé non plus');
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('migration : refuse une source dans une mauvaise version ou absente', async () => {
|
||||
test('migration : refuse une source dans une mauvaise version, déjà multi-utilisateur, ou absente', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||
try {
|
||||
const sourcePath = await legacyFile(dir);
|
||||
|
|
@ -99,7 +126,11 @@ test('migration : refuse une source dans une mauvaise version ou absente', async
|
|||
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/);
|
||||
await assert.rejects(migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER }), /version 5/);
|
||||
await assert.rejects(migrateSqliteToMysql({ sourcePath: join(dir, 'nope.sqlite'), db, ownerEmail: OWNER }), /introuvable/);
|
||||
|
||||
const current = join(dir, 'current.sqlite');
|
||||
await (await openDb({ driver: 'sqlite', file: current })).close();
|
||||
await assert.rejects(migrateSqliteToMysql({ sourcePath: current, db, ownerEmail: OWNER }), /multi-utilisateur/);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue