feat(db): table users, user_id sur projets et jobs, réglages par utilisateur
Migration 2 « comptes_multi_tenant » (SQLite et MySQL maintenus ensemble, test de parité adapté) : - users : email unique insensible à la casse, fournisseur + sub, statut active|suspended, is_admin, plan, dates, champ de liaison de compte réservé ; - projects.user_id (dépôt unique par utilisateur) et jobs.user_id ; settings global remplacé par user_settings ; - sessions et états OAuth recréés (liés à un compte, avec cookie de liaison) ; - les données existantes sont rattachées au propriétaire, première adresse de ADMIN_EMAILS (refus clair si elle manque) ; - getSetting / setSetting prennent l'utilisateur ; src/users.js : inscription à la première connexion, rôle admin, suppression. Côté MySQL les ALTER TABLE sont gardés par information_schema pour rester rejouables.
This commit is contained in:
parent
65158b0ca7
commit
2fa90072dc
8 changed files with 583 additions and 47 deletions
89
src/db.js
89
src/db.js
|
|
@ -72,6 +72,9 @@ class MysqlExecutor extends Executor {
|
||||||
class MysqlDb extends MysqlExecutor {
|
class MysqlDb extends MysqlExecutor {
|
||||||
constructor(pool) { super(pool); this.pool = pool; this.dialect = 'mysql'; }
|
constructor(pool) { super(pool); this.pool = pool; this.dialect = 'mysql'; }
|
||||||
|
|
||||||
|
/** Applique les migrations en attente (jusqu'à `upTo`), avec le contexte { adminEmails }. */
|
||||||
|
migrate(opts = {}) { return migrateMysql(this, opts); }
|
||||||
|
|
||||||
/** fn(tx) reçoit un exécuteur lié à UNE connexion ; commit si tout va bien, rollback sinon. */
|
/** fn(tx) reçoit un exécuteur lié à UNE connexion ; commit si tout va bien, rollback sinon. */
|
||||||
async transaction(fn) {
|
async transaction(fn) {
|
||||||
const conn = await this.pool.getConnection();
|
const conn = await this.pool.getConnection();
|
||||||
|
|
@ -91,7 +94,7 @@ class MysqlDb extends MysqlExecutor {
|
||||||
close() { return this.pool.end(); }
|
close() { return this.pool.end(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openMysql(cfg) {
|
async function openMysql(cfg, opts) {
|
||||||
const { default: mysql } = await import('mysql2/promise');
|
const { default: mysql } = await import('mysql2/promise');
|
||||||
const pool = mysql.createPool({
|
const pool = mysql.createPool({
|
||||||
host: cfg.host, port: cfg.port || 3306, user: cfg.user, password: cfg.password, database: cfg.database,
|
host: cfg.host, port: cfg.port || 3306, user: cfg.user, password: cfg.password, database: cfg.database,
|
||||||
|
|
@ -103,15 +106,17 @@ async function openMysql(cfg) {
|
||||||
timezone: 'Z',
|
timezone: 'Z',
|
||||||
});
|
});
|
||||||
const db = new MysqlDb(pool);
|
const db = new MysqlDb(pool);
|
||||||
try { await migrateMysql(db); }
|
try { await db.migrate(opts); }
|
||||||
catch (e) { await pool.end().catch(() => {}); throw e; }
|
catch (e) { await pool.end().catch(() => {}); throw e; }
|
||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verrou applicatif (GET_LOCK) : deux instances qui démarrent en même temps ne migrent pas en parallèle.
|
// Verrou applicatif (GET_LOCK) : deux instances qui démarrent en même temps ne migrent pas en parallèle.
|
||||||
// Le verrou est lié à la connexion : on garde la même du début à la fin.
|
// Le verrou est lié à la connexion : on garde la même du début à la fin.
|
||||||
async function migrateMysql(db) {
|
async function migrateMysql(db, opts = {}) {
|
||||||
const conn = await db.pool.getConnection();
|
const conn = await db.pool.getConnection();
|
||||||
|
const ctx = migrationContext(opts);
|
||||||
|
const q = async (sql, params = []) => (await conn.query(sql, params))[0];
|
||||||
const LOCK = 'aitools_migrate';
|
const LOCK = 'aitools_migrate';
|
||||||
try {
|
try {
|
||||||
const [[lock]] = await conn.query('SELECT GET_LOCK(?, 60) ok', [LOCK]);
|
const [[lock]] = await conn.query('SELECT GET_LOCK(?, 60) ok', [LOCK]);
|
||||||
|
|
@ -122,10 +127,11 @@ async function migrateMysql(db) {
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`);
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`);
|
||||||
const [rows] = await conn.query('SELECT version FROM schema_migrations');
|
const [rows] = await conn.query('SELECT version FROM schema_migrations');
|
||||||
const done = new Set(rows.map((r) => r.version));
|
const done = new Set(rows.map((r) => r.version));
|
||||||
for (let i = 0; i < MIGRATIONS.length; i++) {
|
for (let i = 0; i < Math.min(MIGRATIONS.length, opts.upTo ?? Infinity); i++) {
|
||||||
const version = i + 1;
|
const version = i + 1;
|
||||||
if (done.has(version)) continue;
|
if (done.has(version)) continue;
|
||||||
for (const sql of MIGRATIONS[i].mysql) await conn.query(sql);
|
await MIGRATIONS[i].check?.(q, ctx);
|
||||||
|
for (const st of MIGRATIONS[i].mysql) await runStatement(st, q, ctx);
|
||||||
await conn.query('INSERT INTO schema_migrations(version, name, applied_at) VALUES(?, ?, ?)',
|
await conn.query('INSERT INTO schema_migrations(version, name, applied_at) VALUES(?, ?, ?)',
|
||||||
[version, MIGRATIONS[i].name, now()]);
|
[version, MIGRATIONS[i].name, now()]);
|
||||||
}
|
}
|
||||||
|
|
@ -162,6 +168,9 @@ class SqliteExecutor extends Executor {
|
||||||
class SqliteDb extends SqliteExecutor {
|
class SqliteDb extends SqliteExecutor {
|
||||||
constructor(raw) { super(raw); this.dialect = 'sqlite'; this.txLock = null; }
|
constructor(raw) { super(raw); this.dialect = 'sqlite'; this.txLock = null; }
|
||||||
|
|
||||||
|
/** Applique les migrations en attente (jusqu'à `upTo`), avec le contexte { adminEmails }. */
|
||||||
|
migrate(opts = {}) { return migrateSqlite(this.raw, opts); }
|
||||||
|
|
||||||
// Une seule connexion : pendant une transaction, les autres requêtes attendent sa fin
|
// Une seule connexion : pendant une transaction, les autres requêtes attendent sa fin
|
||||||
// (sinon elles s'exécuteraient DANS la transaction). Ne pas appeler db.* depuis le callback : utiliser tx.*.
|
// (sinon elles s'exécuteraient DANS la transaction). Ne pas appeler db.* depuis le callback : utiliser tx.*.
|
||||||
async _exec(sql, params, mode) {
|
async _exec(sql, params, mode) {
|
||||||
|
|
@ -190,51 +199,91 @@ class SqliteDb extends SqliteExecutor {
|
||||||
async close() { this.raw.close(); }
|
async close() { this.raw.close(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
function openSqlite(file = ':memory:') {
|
async function openSqlite(file = ':memory:', opts = {}) {
|
||||||
if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true });
|
if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true });
|
||||||
const raw = new DatabaseSync(file);
|
const raw = new DatabaseSync(file);
|
||||||
raw.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
|
raw.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
|
||||||
const db = new SqliteDb(raw);
|
const db = new SqliteDb(raw);
|
||||||
|
try { await db.migrate(opts); }
|
||||||
|
catch (e) { raw.close(); throw e; }
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function migrateSqlite(raw, opts = {}) {
|
||||||
raw.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
raw.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL
|
version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL
|
||||||
)`);
|
)`);
|
||||||
|
const ctx = migrationContext(opts);
|
||||||
|
const q = async (sql, params = []) => raw.prepare(sql).all(...params);
|
||||||
const done = new Set(raw.prepare('SELECT version FROM schema_migrations').all().map((r) => r.version));
|
const done = new Set(raw.prepare('SELECT version FROM schema_migrations').all().map((r) => r.version));
|
||||||
for (let i = 0; i < MIGRATIONS.length; i++) {
|
for (let i = 0; i < Math.min(MIGRATIONS.length, opts.upTo ?? Infinity); i++) {
|
||||||
const version = i + 1;
|
const version = i + 1;
|
||||||
if (done.has(version)) continue;
|
if (done.has(version)) continue;
|
||||||
|
const m = MIGRATIONS[i];
|
||||||
|
// PRAGMA foreign_keys est sans effet dans une transaction : on le règle avant BEGIN
|
||||||
|
if (m.sqliteForeignKeysOff) raw.exec('PRAGMA foreign_keys = OFF');
|
||||||
|
try {
|
||||||
raw.exec('BEGIN');
|
raw.exec('BEGIN');
|
||||||
try {
|
try {
|
||||||
for (const sql of MIGRATIONS[i].sqlite) raw.exec(sql);
|
await m.check?.(q, ctx);
|
||||||
raw.prepare('INSERT INTO schema_migrations(version, name, applied_at) VALUES(?, ?, ?)').run(version, MIGRATIONS[i].name, now());
|
for (const st of m.sqlite) await runStatement(st, q, ctx, (sql, params) => raw.prepare(sql).run(...params));
|
||||||
|
if (m.sqliteForeignKeysOff) {
|
||||||
|
const bad = raw.prepare('PRAGMA foreign_key_check').all();
|
||||||
|
if (bad.length) throw new Error(`Migration ${version} : clés étrangères violées (${bad[0].table} → ${bad[0].parent})`);
|
||||||
|
}
|
||||||
|
raw.prepare('INSERT INTO schema_migrations(version, name, applied_at) VALUES(?, ?, ?)').run(version, m.name, now());
|
||||||
raw.exec('COMMIT');
|
raw.exec('COMMIT');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
raw.exec('ROLLBACK');
|
raw.exec('ROLLBACK');
|
||||||
raw.close();
|
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
if (m.sqliteForeignKeysOff) raw.exec('PRAGMA foreign_keys = ON');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return db;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ouvre la base et applique les migrations en attente.
|
* Ouvre la base et applique les migrations en attente.
|
||||||
* cfg = { driver: 'mysql', host, port, user, password, database } ou { driver: 'sqlite', file } ;
|
* cfg = { driver: 'mysql', host, port, user, password, database } ou { driver: 'sqlite', file } ;
|
||||||
* sans argument (ou ':memory:') : SQLite en mémoire.
|
* sans argument (ou ':memory:') : SQLite en mémoire.
|
||||||
|
* opts = { adminEmails } (propriétaire des données existantes, voir migration 2) ; { upTo } limite la version
|
||||||
|
* migrée (tests de migration), db.migrate() applique ensuite le reste.
|
||||||
*/
|
*/
|
||||||
export async function openDb(cfg = ':memory:') {
|
export async function openDb(cfg = ':memory:', opts = {}) {
|
||||||
if (typeof cfg === 'string') return openSqlite(cfg);
|
if (typeof cfg === 'string') return openSqlite(cfg, opts);
|
||||||
if (cfg.driver === 'sqlite') return openSqlite(cfg.file);
|
if (cfg.driver === 'sqlite') return openSqlite(cfg.file, opts);
|
||||||
return openMysql(cfg);
|
return openMysql(cfg, opts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contexte des migrations : le propriétaire des données existantes est la première adresse de ADMIN_EMAILS
|
||||||
|
function migrationContext({ adminEmails } = {}) {
|
||||||
|
const list = (Array.isArray(adminEmails) ? adminEmails : String(adminEmails || '').split(','))
|
||||||
|
.map((e) => String(e).trim().toLowerCase()).filter(Boolean);
|
||||||
|
return { ownerEmail: list[0] || null, now: now() };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Instruction de migration : chaîne SQL ou { sql, params(ctx), when(q, ctx) }
|
||||||
|
async function runStatement(st, q, ctx, exec = q) {
|
||||||
|
if (typeof st === 'string') return exec(st, []);
|
||||||
|
if (st.when && !(await st.when(q, ctx))) return undefined;
|
||||||
|
return exec(st.sql, st.params ? st.params(ctx) : []);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const now = () => Math.floor(Date.now() / 1000);
|
export const now = () => Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
export async function getSetting(db, key, fallback = null) {
|
// Réglages par utilisateur (aucun réglage global : chaque compte a les siens)
|
||||||
const row = await db.prepare('SELECT value FROM settings WHERE `key` = ?').get(key);
|
function uid(userId) {
|
||||||
|
if (!Number.isInteger(Number(userId)) || Number(userId) <= 0) throw new Error('Réglage : utilisateur requis');
|
||||||
|
return Number(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSetting(db, userId, key, fallback = null) {
|
||||||
|
const row = await db.prepare('SELECT value FROM user_settings WHERE user_id = ? AND `key` = ?').get(uid(userId), key);
|
||||||
return row ? row.value : fallback;
|
return row ? row.value : fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setSetting(db, key, value) {
|
export async function setSetting(db, userId, key, value) {
|
||||||
await db.prepare('INSERT INTO settings(`key`, value) VALUES(?, ?) ON CONFLICT(`key`) DO UPDATE SET value = excluded.value')
|
await db.prepare('INSERT INTO user_settings(user_id, `key`, value) VALUES(?, ?, ?) ON CONFLICT(user_id, `key`) DO UPDATE SET value = excluded.value')
|
||||||
.run(key, value);
|
.run(uid(userId), key, value);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,14 @@
|
||||||
// des deux côtés (test/schema.test.js le vérifie). Ne jamais modifier une migration déjà livrée,
|
// des deux côtés (test/schema.test.js le vérifie). Ne jamais modifier une migration déjà livrée,
|
||||||
// en ajouter une. Côté MySQL, chaque instruction est idempotente (CREATE ... IF NOT EXISTS) : MySQL
|
// en ajouter une. Côté MySQL, chaque instruction est idempotente (CREATE ... IF NOT EXISTS) : MySQL
|
||||||
// valide implicitement chaque DDL, une migration interrompue peut donc être rejouée.
|
// valide implicitement chaque DDL, une migration interrompue peut donc être rejouée.
|
||||||
|
//
|
||||||
|
// Une instruction est soit une chaîne SQL, soit { sql, params?(ctx), when?(q, ctx) } :
|
||||||
|
// - params(ctx) fournit les paramètres liés (ctx = { ownerEmail, now }) ;
|
||||||
|
// - when(q, ctx) décide si l'instruction s'applique (q(sql, params) renvoie les lignes) : c'est ce qui rend
|
||||||
|
// les ALTER TABLE rejouables côté MySQL (pas de IF NOT EXISTS sur ADD COLUMN) ;
|
||||||
|
// - check(q, ctx), au niveau de la migration, est lancé avant toute écriture et peut refuser de migrer.
|
||||||
|
// sqliteForeignKeysOff : la migration reconstruit des tables (SQLite ne sait pas retirer un UNIQUE) ; les clés
|
||||||
|
// étrangères sont suspendues pendant la migration, puis PRAGMA foreign_key_check vérifie le résultat.
|
||||||
|
|
||||||
const T = 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
|
const T = 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
|
||||||
|
|
||||||
|
|
@ -204,4 +212,191 @@ export const MIGRATIONS = [
|
||||||
) ${T}`,
|
) ${T}`,
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// J2 : comptes et multi-tenant. Les données existantes sont rattachées à l'utilisateur « propriétaire »
|
||||||
|
// (première adresse de ADMIN_EMAILS). Sessions et états OAuth, éphémères, sont recréés.
|
||||||
|
name: 'comptes_multi_tenant',
|
||||||
|
sqliteForeignKeysOff: true,
|
||||||
|
check: checkOwner,
|
||||||
|
sqlite: [
|
||||||
|
`CREATE TABLE users (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
email TEXT NOT NULL COLLATE NOCASE UNIQUE,
|
||||||
|
name TEXT,
|
||||||
|
provider TEXT, -- google | apple (NULL = compte préparé par la migration, jamais connecté)
|
||||||
|
provider_sub TEXT, -- identifiant (sub) chez le fournisseur
|
||||||
|
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||||
|
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||||
|
plan TEXT NOT NULL DEFAULT 'free',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
last_login_at INTEGER,
|
||||||
|
claude_link_json TEXT, -- liaison Claude (J3)
|
||||||
|
UNIQUE(provider, provider_sub)
|
||||||
|
)`,
|
||||||
|
{ sql: "INSERT OR IGNORE INTO users(email, status, is_admin, plan, created_at) VALUES(?, 'active', 1, 'free', ?)", params: ownerParams, when: hasLegacyData },
|
||||||
|
`CREATE TABLE projects_new (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
git_url TEXT NOT NULL,
|
||||||
|
profile_json TEXT, -- fiche projet générée par Claude
|
||||||
|
profile_commit TEXT, -- commit analysé
|
||||||
|
profile_at INTEGER,
|
||||||
|
target_json TEXT, -- cible déduite (modifiable)
|
||||||
|
target_validated INTEGER NOT NULL DEFAULT 0,
|
||||||
|
smtp_enc TEXT, -- config SMTP chiffrée
|
||||||
|
db_enc TEXT, -- accès BDD chiffré (récap)
|
||||||
|
imap_enc TEXT, -- config IMAP chiffrée
|
||||||
|
inbox_json TEXT, -- état de la dernière lecture IMAP
|
||||||
|
daily_mail_cap INTEGER NOT NULL DEFAULT 30,
|
||||||
|
followup_enabled INTEGER NOT NULL DEFAULT 0,
|
||||||
|
followup_days INTEGER NOT NULL DEFAULT 7,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
UNIQUE(user_id, git_url)
|
||||||
|
)`,
|
||||||
|
{ sql: `INSERT INTO projects_new(id, user_id, name, git_url, profile_json, profile_commit, profile_at, target_json, target_validated,
|
||||||
|
smtp_enc, db_enc, imap_enc, inbox_json, daily_mail_cap, followup_enabled, followup_days, created_at)
|
||||||
|
SELECT id, (SELECT id FROM users WHERE email = ?), name, git_url, profile_json, profile_commit, profile_at, target_json, target_validated,
|
||||||
|
smtp_enc, db_enc, imap_enc, inbox_json, daily_mail_cap, followup_enabled, followup_days, created_at FROM projects`, params: ownerParams0 },
|
||||||
|
'DROP TABLE projects',
|
||||||
|
'ALTER TABLE projects_new RENAME TO projects',
|
||||||
|
`CREATE TABLE jobs_new (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
type TEXT NOT NULL, -- analyze | prospect | template | send | evolution…
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled
|
||||||
|
params_json TEXT, progress_json TEXT, result_json TEXT, error TEXT,
|
||||||
|
cost_usd REAL, tokens_in INTEGER, tokens_out INTEGER,
|
||||||
|
created_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER,
|
||||||
|
run_after INTEGER -- ne pas démarrer avant (epoch s)
|
||||||
|
)`,
|
||||||
|
{ sql: `INSERT INTO jobs_new(id, user_id, project_id, type, status, params_json, progress_json, result_json, error,
|
||||||
|
cost_usd, tokens_in, tokens_out, created_at, started_at, finished_at, run_after)
|
||||||
|
SELECT id, COALESCE((SELECT user_id FROM projects WHERE projects.id = jobs.project_id), (SELECT id FROM users WHERE email = ?)),
|
||||||
|
project_id, type, status, params_json, progress_json, result_json, error,
|
||||||
|
cost_usd, tokens_in, tokens_out, created_at, started_at, finished_at, run_after FROM jobs`, params: ownerParams0 },
|
||||||
|
'DROP TABLE jobs',
|
||||||
|
'ALTER TABLE jobs_new RENAME TO jobs',
|
||||||
|
'CREATE INDEX jobs_status ON jobs(status, id)',
|
||||||
|
'CREATE INDEX jobs_user ON jobs(user_id, status)',
|
||||||
|
`CREATE TABLE user_settings (
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
key TEXT NOT NULL,
|
||||||
|
value TEXT,
|
||||||
|
PRIMARY KEY (user_id, key)
|
||||||
|
)`,
|
||||||
|
{ sql: 'INSERT OR IGNORE INTO user_settings(user_id, key, value) SELECT u.id, s.key, s.value FROM settings s JOIN users u ON u.email = ?', params: ownerParams0 },
|
||||||
|
'DROP TABLE settings',
|
||||||
|
'DROP TABLE sessions',
|
||||||
|
`CREATE TABLE sessions (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL
|
||||||
|
)`,
|
||||||
|
'CREATE INDEX sessions_user ON sessions(user_id)',
|
||||||
|
'DROP TABLE oauth_states',
|
||||||
|
`CREATE TABLE oauth_states (
|
||||||
|
state TEXT PRIMARY KEY, provider TEXT NOT NULL, verifier TEXT NOT NULL, nonce TEXT NOT NULL,
|
||||||
|
binding TEXT NOT NULL, -- empreinte du cookie qui lie le flux au navigateur d'origine
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
)`,
|
||||||
|
],
|
||||||
|
mysql: [
|
||||||
|
`CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
name VARCHAR(255),
|
||||||
|
provider VARCHAR(20), -- google | apple (NULL = compte préparé par la migration, jamais connecté)
|
||||||
|
provider_sub VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin, -- identifiant (sub) chez le fournisseur
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'active',
|
||||||
|
is_admin TINYINT NOT NULL DEFAULT 0,
|
||||||
|
plan VARCHAR(20) NOT NULL DEFAULT 'free',
|
||||||
|
created_at BIGINT NOT NULL,
|
||||||
|
last_login_at BIGINT,
|
||||||
|
claude_link_json TEXT, -- liaison Claude (J3)
|
||||||
|
UNIQUE KEY users_email (email),
|
||||||
|
UNIQUE KEY users_provider (provider, provider_sub),
|
||||||
|
CONSTRAINT users_status CHECK (status IN ('active', 'suspended'))
|
||||||
|
) ${T}`,
|
||||||
|
{ sql: "INSERT IGNORE INTO users(email, status, is_admin, plan, created_at) VALUES(?, 'active', 1, 'free', ?)", params: ownerParams, when: hasLegacyData },
|
||||||
|
// projects : user_id, puis unicité de git_url par utilisateur
|
||||||
|
{ sql: 'ALTER TABLE projects ADD COLUMN user_id BIGINT NULL', when: colMissing('projects', 'user_id') },
|
||||||
|
{ sql: 'UPDATE projects SET user_id = (SELECT id FROM users WHERE email = ?) WHERE user_id IS NULL', params: ownerParams0 },
|
||||||
|
'ALTER TABLE projects MODIFY user_id BIGINT NOT NULL',
|
||||||
|
{ sql: 'ALTER TABLE projects ADD CONSTRAINT projects_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE', when: fkMissing('projects', 'projects_user') },
|
||||||
|
{ sql: 'ALTER TABLE projects DROP INDEX projects_git_url', when: idxExists('projects', 'projects_git_url') },
|
||||||
|
{ sql: 'ALTER TABLE projects ADD UNIQUE KEY projects_user_git_url (user_id, git_url)', when: idxMissing('projects', 'projects_user_git_url') },
|
||||||
|
// jobs : user_id dénormalisé (un job sans projet doit rester attribuable)
|
||||||
|
{ sql: 'ALTER TABLE jobs ADD COLUMN user_id BIGINT NULL', when: colMissing('jobs', 'user_id') },
|
||||||
|
'UPDATE jobs SET user_id = (SELECT user_id FROM projects WHERE projects.id = jobs.project_id) WHERE user_id IS NULL AND project_id IS NOT NULL',
|
||||||
|
{ sql: 'UPDATE jobs SET user_id = (SELECT id FROM users WHERE email = ?) WHERE user_id IS NULL', params: ownerParams0 },
|
||||||
|
'ALTER TABLE jobs MODIFY user_id BIGINT NOT NULL',
|
||||||
|
{ sql: 'ALTER TABLE jobs ADD CONSTRAINT jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE', when: fkMissing('jobs', 'jobs_user') },
|
||||||
|
{ sql: 'ALTER TABLE jobs ADD KEY jobs_user_status (user_id, status)', when: idxMissing('jobs', 'jobs_user_status') },
|
||||||
|
// réglages : globaux → par utilisateur
|
||||||
|
`CREATE TABLE IF NOT EXISTS user_settings (
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
\`key\` VARCHAR(190) NOT NULL,
|
||||||
|
value TEXT,
|
||||||
|
PRIMARY KEY (user_id, \`key\`),
|
||||||
|
CONSTRAINT user_settings_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
{ sql: 'INSERT IGNORE INTO user_settings(user_id, `key`, value) SELECT u.id, s.`key`, s.value FROM settings s JOIN users u ON u.email = ?', params: ownerParams0, when: tableExists('settings') },
|
||||||
|
'DROP TABLE IF EXISTS settings',
|
||||||
|
'DROP TABLE IF EXISTS sessions',
|
||||||
|
`CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
id VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL PRIMARY KEY,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
created_at BIGINT NOT NULL, expires_at BIGINT NOT NULL,
|
||||||
|
KEY sessions_user (user_id),
|
||||||
|
CONSTRAINT sessions_user_fk FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
'DROP TABLE IF EXISTS oauth_states',
|
||||||
|
`CREATE TABLE IF NOT EXISTS oauth_states (
|
||||||
|
state VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL PRIMARY KEY,
|
||||||
|
provider VARCHAR(20) NOT NULL,
|
||||||
|
verifier VARCHAR(255) NOT NULL, nonce VARCHAR(255) NOT NULL,
|
||||||
|
binding VARCHAR(128) NOT NULL, -- empreinte du cookie qui lie le flux au navigateur d'origine
|
||||||
|
created_at BIGINT NOT NULL
|
||||||
|
) ${T}`,
|
||||||
|
],
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// ---------- Aides de la migration 2 ----------
|
||||||
|
|
||||||
|
function ownerParams(ctx) { return [ctx.ownerEmail, ctx.now]; }
|
||||||
|
function ownerParams0(ctx) { return [ctx.ownerEmail ?? null]; }
|
||||||
|
|
||||||
|
// Des données existent-elles (une instance déjà utilisée) ? Alors elles ont besoin d'un propriétaire.
|
||||||
|
async function hasLegacyData(q) {
|
||||||
|
for (const t of ['projects', 'settings', 'jobs']) {
|
||||||
|
if ((await q(`SELECT COUNT(*) n FROM ${t}`))[0].n > 0) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkOwner(q, ctx) {
|
||||||
|
if (ctx.ownerEmail) return;
|
||||||
|
if (await hasLegacyData(q)) {
|
||||||
|
throw new Error('Migration comptes : des données existent, définis ADMIN_EMAILS (le premier email devient propriétaire de ces données).');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const infoSchema = (what) => `SELECT 1 x FROM information_schema.${what} WHERE table_schema = DATABASE() AND table_name = ?`;
|
||||||
|
function colMissing(t, c) {
|
||||||
|
return async (q) => !(await q(`${infoSchema('columns')} AND column_name = ?`, [t, c])).length;
|
||||||
|
}
|
||||||
|
function idxExists(t, i) {
|
||||||
|
return async (q) => (await q(`${infoSchema('statistics')} AND index_name = ?`, [t, i])).length > 0;
|
||||||
|
}
|
||||||
|
function idxMissing(t, i) {
|
||||||
|
return async (q) => !(await idxExists(t, i)(q));
|
||||||
|
}
|
||||||
|
function fkMissing(t, name) {
|
||||||
|
return async (q) => !(await q(`${infoSchema('table_constraints')} AND constraint_name = ? AND constraint_type = 'FOREIGN KEY'`, [t, name])).length;
|
||||||
|
}
|
||||||
|
function tableExists(t) {
|
||||||
|
return async (q) => (await q(infoSchema('tables'), [t])).length > 0;
|
||||||
|
}
|
||||||
|
|
|
||||||
103
src/users.js
Normal file
103
src/users.js
Normal file
|
|
@ -0,0 +1,103 @@
|
||||||
|
// Comptes : création à la première connexion, rôle admin (ADMIN_EMAILS), suspension, suppression.
|
||||||
|
import { rmSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { now } from './db.js';
|
||||||
|
import { HttpError } from './http.js';
|
||||||
|
import { clearRecapCache } from './services/recap.js';
|
||||||
|
|
||||||
|
export const PROVIDER_LABELS = { google: 'Google', apple: 'Apple' };
|
||||||
|
export const AI_BLOCKED_MESSAGE = 'Liaison Claude requise (bientôt disponible)';
|
||||||
|
|
||||||
|
export const normalizeEmail = (e) => String(e ?? '').trim().toLowerCase();
|
||||||
|
const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
|
const COLUMNS = 'id, email, name, provider, provider_sub, status, is_admin, plan, created_at, last_login_at';
|
||||||
|
|
||||||
|
// Forme exposée au reste de l'application (booléens, jamais claude_link_json)
|
||||||
|
function publicUser(r) {
|
||||||
|
if (!r) return null;
|
||||||
|
return {
|
||||||
|
id: Number(r.id), email: r.email, name: r.name, provider: r.provider, providerSub: r.provider_sub,
|
||||||
|
status: r.status, isAdmin: !!r.is_admin, plan: r.plan, createdAt: r.created_at, lastLoginAt: r.last_login_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUser(db, id) {
|
||||||
|
return publicUser(await db.prepare(`SELECT ${COLUMNS} FROM users WHERE id = ?`).get(Number(id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un compte actif et administrateur peut lancer un job IA avec la configuration du serveur ; personne d'autre (avant le J3). */
|
||||||
|
export const canRunAi = (user) => !!user && user.status === 'active' && user.isAdmin;
|
||||||
|
|
||||||
|
export function assertCanRunAi(user) {
|
||||||
|
if (!canRunAi(user)) throw new HttpError(403, AI_BLOCKED_MESSAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ADMIN_EMAILS fait foi : les admins sont exactement ces adresses (au démarrage et à chaque connexion). */
|
||||||
|
export async function syncAdmins(db, adminEmails) {
|
||||||
|
const list = adminEmails.map(normalizeEmail).filter(Boolean);
|
||||||
|
if (!list.length) { await db.prepare('UPDATE users SET is_admin = 0').run(); return; }
|
||||||
|
await db.prepare(`UPDATE users SET is_admin = CASE WHEN email IN (${list.map(() => '?').join(', ')}) THEN 1 ELSE 0 END`).run(...list);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trouve ou crée le compte d'une identité vérifiée par le fournisseur.
|
||||||
|
* 1. (fournisseur, sub) connu → ce compte ;
|
||||||
|
* 2. sinon même email : compte préparé par la migration (sans fournisseur) → rattaché à cette identité ;
|
||||||
|
* compte déjà lié à un autre fournisseur → refus (pas de fusion automatique de comptes) ;
|
||||||
|
* 3. sinon inscription automatique (plan gratuit). Le compte suspendu est refusé.
|
||||||
|
*/
|
||||||
|
export async function loginIdentity(db, cfg, { provider, sub, email, name }) {
|
||||||
|
email = normalizeEmail(email);
|
||||||
|
sub = String(sub || '');
|
||||||
|
if (!sub) throw new HttpError(401, 'Identité fournisseur invalide');
|
||||||
|
if (!EMAIL_SHAPE.test(email) || email.length > 255) throw new HttpError(401, 'Email invalide');
|
||||||
|
const cleanName = name ? String(name).trim().slice(0, 200) || null : null;
|
||||||
|
const t = now();
|
||||||
|
|
||||||
|
let row = await db.prepare(`SELECT ${COLUMNS} FROM users WHERE provider = ? AND provider_sub = ?`).get(provider, sub);
|
||||||
|
if (!row) {
|
||||||
|
const byEmail = await db.prepare(`SELECT ${COLUMNS} FROM users WHERE email = ?`).get(email);
|
||||||
|
if (byEmail) {
|
||||||
|
if (byEmail.provider) {
|
||||||
|
throw new HttpError(409, `Cet email est déjà associé à un compte ${PROVIDER_LABELS[byEmail.provider] || byEmail.provider} : connecte-toi avec ce fournisseur.`);
|
||||||
|
}
|
||||||
|
await db.prepare('UPDATE users SET provider = ?, provider_sub = ? WHERE id = ? AND provider IS NULL').run(provider, sub, byEmail.id);
|
||||||
|
row = { ...byEmail, provider, provider_sub: sub };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!row) {
|
||||||
|
try {
|
||||||
|
const r = await db.prepare(`INSERT INTO users(email, name, provider, provider_sub, status, is_admin, plan, created_at, last_login_at)
|
||||||
|
VALUES(?, ?, ?, ?, 'active', ?, 'free', ?, ?)`).run(email, cleanName, provider, sub, cfg.adminEmails.includes(email) ? 1 : 0, t, t);
|
||||||
|
row = await db.prepare(`SELECT ${COLUMNS} FROM users WHERE id = ?`).get(Number(r.lastInsertRowid));
|
||||||
|
} catch (e) {
|
||||||
|
// Deux premières connexions simultanées du même compte : la seconde retrouve la ligne de la première
|
||||||
|
row = await db.prepare(`SELECT ${COLUMNS} FROM users WHERE provider = ? AND provider_sub = ?`).get(provider, sub);
|
||||||
|
if (!row) throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (row.status !== 'active') throw new HttpError(403, 'Compte suspendu');
|
||||||
|
// L'identité est le (fournisseur, sub) ; le rôle suit ADMIN_EMAILS, relu à chaque connexion
|
||||||
|
await db.prepare('UPDATE users SET last_login_at = ?, is_admin = ?, name = COALESCE(?, name) WHERE id = ?')
|
||||||
|
.run(t, cfg.adminEmails.includes(normalizeEmail(row.email)) ? 1 : 0, cleanName, row.id);
|
||||||
|
return getUser(db, row.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const userRepoRoot = (cfg, userId) => join(cfg.dataDir, 'repos', String(Number(userId)));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Supprime le compte et TOUTES ses données : projets, prospects, notes, modèles, journaux d'envoi, jobs,
|
||||||
|
* métriques, réglages et sessions (cascade des clés étrangères), puis les clones git du disque.
|
||||||
|
* La liste d'opposition (blacklist) est volontairement conservée : c'est un registre d'adresses qui ont refusé
|
||||||
|
* d'être contactées, pas une donnée du compte.
|
||||||
|
*/
|
||||||
|
export async function deleteUser(app, userId) {
|
||||||
|
const { db, cfg } = app;
|
||||||
|
const user = await getUser(db, userId);
|
||||||
|
if (!user) throw new HttpError(404, 'Compte introuvable');
|
||||||
|
const projects = await db.prepare('SELECT id FROM projects WHERE user_id = ?').all(user.id);
|
||||||
|
await db.prepare('DELETE FROM users WHERE id = ?').run(user.id);
|
||||||
|
for (const p of projects) clearRecapCache(p.id);
|
||||||
|
rmSync(userRepoRoot(cfg, user.id), { recursive: true, force: true });
|
||||||
|
}
|
||||||
125
test/accounts-migration.test.js
Normal file
125
test/accounts-migration.test.js
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { now } from '../src/db.js';
|
||||||
|
import { MIGRATIONS } from '../src/migrations.js';
|
||||||
|
import { loginIdentity } from '../src/users.js';
|
||||||
|
import { testDb, USING_MYSQL } from './helpers/db.js';
|
||||||
|
|
||||||
|
// Migration 2 (comptes et multi-tenant) : une instance existante, mono-utilisateur, passe au schéma multi-utilisateur
|
||||||
|
// et ses données sont rattachées à l'utilisateur propriétaire (première adresse de ADMIN_EMAILS), sans perte.
|
||||||
|
|
||||||
|
const TABLES = ['projects', 'templates', 'prospects', 'prospect_notes', 'mail_log', 'metrics_daily', 'jobs', 'blacklist'];
|
||||||
|
|
||||||
|
/** Base à la version 1 avec des données « d'avant les comptes ». */
|
||||||
|
async function legacy() {
|
||||||
|
const db = await testDb({ upTo: 1 });
|
||||||
|
const t = now();
|
||||||
|
await db.prepare('INSERT INTO projects(id, name, git_url, smtp_enc, daily_mail_cap, created_at) VALUES(?, ?, ?, ?, ?, ?)').run(7, 'Café Été', 'https://git.x/a.git', 'v1:smtp:chiffré', 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, created_at) VALUES(?, ?, ?, ?, ?)').run(1001, 7, 'Léa', 'lea@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 mail_log(id, project_id, prospect_id, email, sent_at) VALUES(?, ?, ?, ?, ?)').run(9, 7, 1001, 'lea@x.fr', t);
|
||||||
|
await db.prepare('INSERT INTO metrics_daily(project_id, day, users) VALUES(?, ?, ?)').run(7, '2026-10-21', 10);
|
||||||
|
await db.prepare('INSERT INTO jobs(id, project_id, type, status, cost_usd, created_at) VALUES(?, ?, ?, ?, ?, ?)').run(300, 7, 'analyze', 'done', 0.5, t);
|
||||||
|
await db.prepare('INSERT INTO jobs(id, project_id, type, status, created_at) VALUES(?, NULL, ?, ?, ?)').run(301, 'send', 'done', t); // job sans projet
|
||||||
|
await db.prepare('INSERT INTO blacklist(email, reason, created_at) VALUES(?, ?, ?)').run('no@x.fr', 'unsubscribe', t);
|
||||||
|
await db.prepare('INSERT INTO settings(`key`, value) VALUES(?, ?)').run('notify_email', 'tony@x.fr');
|
||||||
|
await db.prepare('INSERT INTO settings(`key`, value) VALUES(?, ?)').run('budget_day_usd', '3');
|
||||||
|
await db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)').run('ancienne', 'tony@x.fr', t, t + 100);
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
const count = async (db, t) => (await db.prepare(`SELECT COUNT(*) n FROM \`${t}\``).get()).n;
|
||||||
|
|
||||||
|
test('rattachement : toutes les données au propriétaire (1re adresse de ADMIN_EMAILS), sans perte', async () => {
|
||||||
|
const db = await legacy();
|
||||||
|
const before = Object.fromEntries(await Promise.all(TABLES.map(async (t) => [t, await count(db, t)])));
|
||||||
|
await db.migrate({ adminEmails: ' Tony@X.fr , autre@x.fr' });
|
||||||
|
|
||||||
|
const users = await db.prepare('SELECT * FROM users').all();
|
||||||
|
assert.equal(users.length, 1, 'un seul compte créé : le propriétaire');
|
||||||
|
const owner = users[0];
|
||||||
|
assert.deepEqual({ email: owner.email, admin: owner.is_admin, status: owner.status, plan: owner.plan, provider: owner.provider, sub: owner.provider_sub },
|
||||||
|
{ email: 'tony@x.fr', admin: 1, status: 'active', plan: 'free', provider: null, sub: null });
|
||||||
|
assert.equal(owner.claude_link_json, null);
|
||||||
|
|
||||||
|
for (const t of TABLES) assert.equal(await count(db, t), before[t], `${t} : aucune ligne perdue`);
|
||||||
|
assert.deepEqual((await db.prepare('SELECT id, name, user_id, daily_mail_cap, smtp_enc FROM projects ORDER BY id').all()).map((p) => [p.id, p.name, Number(p.user_id), p.daily_mail_cap, p.smtp_enc]),
|
||||||
|
[[7, 'Café Été', owner.id, 12, 'v1:smtp:chiffré'], [42, 'Autre', owner.id, 30, null]]);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM jobs WHERE user_id = ?').get(owner.id)).n, 2, 'tous les jobs, y compris celui sans projet');
|
||||||
|
assert.equal((await db.prepare('SELECT project_id FROM jobs WHERE id = 301').get()).project_id, null);
|
||||||
|
assert.equal((await db.prepare('SELECT cost_usd FROM jobs WHERE id = 300').get()).cost_usd, 0.5);
|
||||||
|
assert.equal((await db.prepare('SELECT body FROM prospect_notes WHERE id = 5').get()).body, 'à rappeler');
|
||||||
|
|
||||||
|
// réglages globaux → réglages du propriétaire ; ancienne table supprimée ; sessions éphémères repartent de zéro
|
||||||
|
assert.deepEqual((await db.prepare('SELECT `key`, value FROM user_settings WHERE user_id = ? ORDER BY `key`').all(owner.id)).map((r) => [r.key, r.value]),
|
||||||
|
[['budget_day_usd', '3'], ['notify_email', 'tony@x.fr']]);
|
||||||
|
await assert.rejects(db.prepare('SELECT 1 FROM settings').get(), /settings/);
|
||||||
|
assert.equal(await count(db, 'sessions'), 0);
|
||||||
|
await db.prepare('INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES(?, ?, ?, ?)').run('nouvelle', owner.id, now(), now() + 10); // le nouveau format lie la session à un compte
|
||||||
|
assert.equal((await db.prepare('SELECT MAX(version) v, COUNT(*) n FROM schema_migrations').get()).v, MIGRATIONS.length);
|
||||||
|
|
||||||
|
// contraintes du nouveau schéma : unicité du dépôt PAR utilisateur, cascade depuis l'utilisateur
|
||||||
|
const other = Number((await db.prepare("INSERT INTO users(email, status, is_admin, plan, created_at) VALUES('b@x.fr', 'active', 0, 'free', ?)").run(now())).lastInsertRowid);
|
||||||
|
await assert.rejects(db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(owner.id, 'Doublon', 'https://git.x/a.git', now()));
|
||||||
|
await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(other, 'Même dépôt', 'https://git.x/a.git', now());
|
||||||
|
await assert.rejects(db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(999, 'Orphelin', 'https://git.x/z.git', now()), 'user_id doit exister');
|
||||||
|
await assert.rejects(db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('Sans propriétaire', 'https://git.x/y.git', now()), 'user_id obligatoire');
|
||||||
|
await assert.rejects(db.prepare('INSERT INTO jobs(type, created_at) VALUES(?, ?)').run('send', now()), 'jobs.user_id obligatoire');
|
||||||
|
|
||||||
|
if (db.dialect === 'sqlite') {
|
||||||
|
assert.deepEqual(await db.query('PRAGMA foreign_key_check'), [], 'aucune clé étrangère violée');
|
||||||
|
assert.equal((await db.prepare('PRAGMA foreign_keys').get()).foreign_keys, 1, 'clés étrangères réactivées après la migration');
|
||||||
|
}
|
||||||
|
await db.prepare('DELETE FROM users WHERE id = ?').run(owner.id);
|
||||||
|
for (const t of ['projects', 'templates', 'prospects', 'prospect_notes', 'mail_log', 'metrics_daily', 'user_settings']) {
|
||||||
|
const n = await count(db, t);
|
||||||
|
assert.equal(n, t === 'projects' ? 1 : 0, `${t} : supprimé avec le propriétaire (reste le projet de l'autre compte)`);
|
||||||
|
}
|
||||||
|
assert.equal(await count(db, 'jobs'), 0);
|
||||||
|
assert.equal(await count(db, 'blacklist'), 1, 'la liste d\'opposition ne dépend d\'aucun compte');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rattachement : le propriétaire se connecte et retrouve ses données par son email', async () => {
|
||||||
|
const db = await legacy();
|
||||||
|
await db.migrate({ adminEmails: ['tony@x.fr'] });
|
||||||
|
const prepared = (await db.prepare('SELECT id FROM users').get()).id;
|
||||||
|
const user = await loginIdentity(db, { adminEmails: ['tony@x.fr'] }, { provider: 'google', sub: 'g-tony', email: 'Tony@X.fr', name: 'Tony' });
|
||||||
|
assert.equal(user.id, Number(prepared), 'même compte : pas de doublon');
|
||||||
|
assert.equal(user.isAdmin, true);
|
||||||
|
assert.equal(user.provider, 'google');
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(user.id)).n, 2);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM users').get()).n, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rattachement : refusé sans ADMIN_EMAILS quand des données existent (la base reste en version 1)', async () => {
|
||||||
|
const db = await legacy();
|
||||||
|
await assert.rejects(db.migrate({}), /ADMIN_EMAILS/);
|
||||||
|
await assert.rejects(db.migrate({ adminEmails: ' , ' }), /ADMIN_EMAILS/);
|
||||||
|
assert.equal((await db.prepare('SELECT MAX(version) v FROM schema_migrations').get()).v, 1);
|
||||||
|
assert.equal(await count(db, 'projects'), 2, 'rien n\'a été touché');
|
||||||
|
if (!USING_MYSQL) await assert.rejects(db.prepare('SELECT 1 FROM users').get(), /users/);
|
||||||
|
// une fois ADMIN_EMAILS défini, la migration passe
|
||||||
|
await db.migrate({ adminEmails: 'tony@x.fr' });
|
||||||
|
assert.equal((await db.prepare('SELECT MAX(version) v FROM schema_migrations').get()).v, MIGRATIONS.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rattachement : base vide sans ADMIN_EMAILS → migration sans propriétaire, premier admin créé à sa connexion', async () => {
|
||||||
|
const db = await testDb({ upTo: 1 });
|
||||||
|
await db.migrate({});
|
||||||
|
assert.equal(await count(db, 'users'), 0);
|
||||||
|
const admin = await loginIdentity(db, { adminEmails: ['tony@x.fr'] }, { provider: 'google', sub: 'g1', email: 'tony@x.fr' });
|
||||||
|
assert.equal(admin.isAdmin, true);
|
||||||
|
const user = await loginIdentity(db, { adminEmails: ['tony@x.fr'] }, { provider: 'apple', sub: 'a1', email: 'visiteur@x.fr' });
|
||||||
|
assert.equal(user.isAdmin, false);
|
||||||
|
assert.equal(user.plan, 'free');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rattachement : la migration rejouée ne change rien (déjà appliquée)', async () => {
|
||||||
|
const db = await legacy();
|
||||||
|
await db.migrate({ adminEmails: 'tony@x.fr' });
|
||||||
|
await db.migrate({ adminEmails: 'tony@x.fr' });
|
||||||
|
assert.equal(await count(db, 'users'), 1);
|
||||||
|
assert.equal(await count(db, 'projects'), 2);
|
||||||
|
});
|
||||||
|
|
@ -2,6 +2,8 @@ import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, translate, dbConfigFromEnv, getSetting, setSetting, now } from '../src/db.js';
|
import { openDb, translate, dbConfigFromEnv, getSetting, setSetting, now } from '../src/db.js';
|
||||||
import { testDb } from './helpers/db.js';
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
import { MIGRATIONS } from '../src/migrations.js';
|
||||||
|
|
||||||
test('translate : MySQL reçoit INSERT IGNORE, ON DUPLICATE KEY, VALUES() et pas de NOCASE', () => {
|
test('translate : MySQL reçoit INSERT IGNORE, ON DUPLICATE KEY, VALUES() et pas de NOCASE', () => {
|
||||||
const up = 'INSERT INTO t(a, b) VALUES(?, ?) ON CONFLICT(a, b) DO UPDATE SET x = excluded.x, y = excluded.y';
|
const up = 'INSERT INTO t(a, b) VALUES(?, ?) ON CONFLICT(a, b) DO UPDATE SET x = excluded.x, y = excluded.y';
|
||||||
|
|
@ -25,10 +27,11 @@ test('dbConfigFromEnv : variables DB_*, port par défaut, erreur claire', () =>
|
||||||
|
|
||||||
test('shim : get / all / run asynchrones, run → changes + lastInsertRowid', async () => {
|
test('shim : get / all / run asynchrones, run → changes + lastInsertRowid', async () => {
|
||||||
const db = await testDb();
|
const db = await testDb();
|
||||||
const pending = db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('A', 'u1', now());
|
const u = await addUser(db);
|
||||||
|
const pending = db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(u, 'A', 'u1', now());
|
||||||
assert.ok(pending instanceof Promise);
|
assert.ok(pending instanceof Promise);
|
||||||
await pending;
|
await pending;
|
||||||
const r1 = await db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('B', 'u2', now());
|
const r1 = await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(u, 'B', 'u2', now());
|
||||||
assert.equal(r1.changes, 1);
|
assert.equal(r1.changes, 1);
|
||||||
assert.ok(r1.lastInsertRowid > 0);
|
assert.ok(r1.lastInsertRowid > 0);
|
||||||
assert.equal((await db.prepare('SELECT name FROM projects WHERE id = ?').get(r1.lastInsertRowid)).name, 'B');
|
assert.equal((await db.prepare('SELECT name FROM projects WHERE id = ?').get(r1.lastInsertRowid)).name, 'B');
|
||||||
|
|
@ -40,7 +43,8 @@ test('shim : get / all / run asynchrones, run → changes + lastInsertRowid', as
|
||||||
|
|
||||||
test('shim : undefined et NaN deviennent NULL', async () => {
|
test('shim : undefined et NaN deviennent NULL', async () => {
|
||||||
const db = await testDb();
|
const db = await testDb();
|
||||||
await db.prepare('INSERT INTO projects(name, git_url, created_at, profile_at) VALUES(?, ?, ?, ?)').run('A', 'u', now(), Number('abc'));
|
const u = await addUser(db);
|
||||||
|
await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at, profile_at) VALUES(?, ?, ?, ?, ?)').run(u, 'A', 'u', now(), Number('abc'));
|
||||||
await db.prepare('UPDATE projects SET profile_commit = ? WHERE git_url = ?').run(undefined, 'u');
|
await db.prepare('UPDATE projects SET profile_commit = ? WHERE git_url = ?').run(undefined, 'u');
|
||||||
const p = await db.prepare('SELECT profile_at, profile_commit FROM projects').get();
|
const p = await db.prepare('SELECT profile_at, profile_commit FROM projects').get();
|
||||||
assert.equal(p.profile_at, null);
|
assert.equal(p.profile_at, null);
|
||||||
|
|
@ -49,11 +53,14 @@ test('shim : undefined et NaN deviennent NULL', async () => {
|
||||||
|
|
||||||
test('upsert (ON CONFLICT) et INSERT OR IGNORE dans le sous-ensemble commun', async () => {
|
test('upsert (ON CONFLICT) et INSERT OR IGNORE dans le sous-ensemble commun', async () => {
|
||||||
const db = await testDb();
|
const db = await testDb();
|
||||||
await setSetting(db, 'a', '1'); await setSetting(db, 'a', '2');
|
const u = await addUser(db), v = await addUser(db);
|
||||||
assert.equal(await getSetting(db, 'a'), '2');
|
await setSetting(db, u, 'a', '1'); await setSetting(db, u, 'a', '2');
|
||||||
assert.equal(await getSetting(db, 'nope', 'x'), 'x');
|
assert.equal(await getSetting(db, u, 'a'), '2');
|
||||||
await setSetting(db, 'a', null);
|
assert.equal(await getSetting(db, u, 'nope', 'x'), 'x');
|
||||||
assert.equal(await getSetting(db, 'a', 'fallback'), null);
|
assert.equal(await getSetting(db, v, 'a', 'autre'), 'autre', 'les réglages sont propres à chaque utilisateur');
|
||||||
|
await setSetting(db, u, 'a', null);
|
||||||
|
assert.equal(await getSetting(db, u, 'a', 'fallback'), null);
|
||||||
|
await assert.rejects(setSetting(db, undefined, 'a', '1'), /utilisateur requis/);
|
||||||
|
|
||||||
const ins = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'x', ?)");
|
const ins = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'x', ?)");
|
||||||
assert.equal((await ins.run('a@b.fr', now())).changes, 1);
|
assert.equal((await ins.run('a@b.fr', now())).changes, 1);
|
||||||
|
|
@ -62,10 +69,11 @@ test('upsert (ON CONFLICT) et INSERT OR IGNORE dans le sous-ensemble commun', as
|
||||||
|
|
||||||
test('clés étrangères : supprimer un projet supprime ses dépendances (CASCADE)', async () => {
|
test('clés étrangères : supprimer un projet supprime ses dépendances (CASCADE)', async () => {
|
||||||
const db = await testDb();
|
const db = await testDb();
|
||||||
const { lastInsertRowid: pid } = await db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('A', 'u', now());
|
const u = await addUser(db);
|
||||||
|
const { lastInsertRowid: pid } = await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(u, 'A', 'u', now());
|
||||||
const { lastInsertRowid: prid } = await db.prepare('INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)').run(pid, 'C', 'c@d.fr', now());
|
const { lastInsertRowid: prid } = await db.prepare('INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)').run(pid, 'C', 'c@d.fr', now());
|
||||||
await db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prid, 'n', now());
|
await db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prid, 'n', now());
|
||||||
await db.prepare('INSERT INTO jobs(project_id, type, created_at) VALUES(?, ?, ?)').run(pid, 'analyze', now());
|
await db.prepare('INSERT INTO jobs(user_id, project_id, type, created_at) VALUES(?, ?, ?, ?)').run(u, pid, 'analyze', now());
|
||||||
await db.prepare('DELETE FROM projects WHERE id = ?').run(pid);
|
await db.prepare('DELETE FROM projects WHERE id = ?').run(pid);
|
||||||
for (const t of ['prospects', 'prospect_notes', 'jobs']) assert.equal((await db.prepare(`SELECT COUNT(*) n FROM ${t}`).get()).n, 0, t);
|
for (const t of ['prospects', 'prospect_notes', 'jobs']) assert.equal((await db.prepare(`SELECT COUNT(*) n FROM ${t}`).get()).n, 0, t);
|
||||||
});
|
});
|
||||||
|
|
@ -109,11 +117,12 @@ test('migrations idempotentes : rouvrir une base déjà migrée ne casse rien (S
|
||||||
try {
|
try {
|
||||||
const file = join(dir, 't.sqlite');
|
const file = join(dir, 't.sqlite');
|
||||||
const a = await openDb({ driver: 'sqlite', file });
|
const a = await openDb({ driver: 'sqlite', file });
|
||||||
await setSetting(a, 'k', 'v');
|
const u = await addUser(a);
|
||||||
|
await setSetting(a, u, 'k', 'v');
|
||||||
await a.close();
|
await a.close();
|
||||||
const b = await openDb({ driver: 'sqlite', file });
|
const b = await openDb({ driver: 'sqlite', file });
|
||||||
assert.equal(await getSetting(b, 'k'), 'v');
|
assert.equal(await getSetting(b, u, 'k'), 'v');
|
||||||
assert.equal((await b.prepare('SELECT COUNT(*) n FROM schema_migrations').get()).n, 1);
|
assert.equal((await b.prepare('SELECT COUNT(*) n FROM schema_migrations').get()).n, MIGRATIONS.length);
|
||||||
await b.close();
|
await b.close();
|
||||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -24,14 +24,14 @@ export function testDbConfig() {
|
||||||
return dbConfigFromEnv(process.env, 'TEST_DB_');
|
return dbConfigFromEnv(process.env, 'TEST_DB_');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Base vide, schéma migré. */
|
/** Base vide, schéma migré. `opts` : { upTo, adminEmails } (voir openDb), pour tester les migrations. */
|
||||||
export async function testDb() {
|
export async function testDb(opts = {}) {
|
||||||
if (!USING_MYSQL) return openDb(':memory:');
|
if (!USING_MYSQL) return openDb(':memory:', opts);
|
||||||
const cfg = { ...testDbConfig(), connectionLimit: 4 };
|
const cfg = { ...testDbConfig(), connectionLimit: 4 };
|
||||||
const raw = await openDb(cfg);
|
const raw = await openDb(cfg, { upTo: 0 });
|
||||||
await wipe(raw);
|
await wipe(raw);
|
||||||
await raw.close();
|
await raw.close();
|
||||||
const db = await openDb(cfg);
|
const db = await openDb(cfg, opts);
|
||||||
opened.push(db);
|
opened.push(db);
|
||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
18
test/helpers/users.js
Normal file
18
test/helpers/users.js
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
// Comptes de test
|
||||||
|
let seq = 0;
|
||||||
|
|
||||||
|
/** Crée un compte et renvoie son id. Admin et actif par défaut (les tests historiques lancent des jobs IA). */
|
||||||
|
export async function addUser(db, { email, admin = true, status = 'active', provider = 'google', sub, name = null } = {}) {
|
||||||
|
seq++;
|
||||||
|
const r = await db.prepare(`INSERT INTO users(email, name, provider, provider_sub, status, is_admin, plan, created_at)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, 'free', ?)`).run(email || `user${seq}@test.fr`, name, provider, sub || `sub-${seq}`, status, admin ? 1 : 0, 1_700_000_000);
|
||||||
|
return Number(r.lastInsertRowid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Projet minimal d'un utilisateur. */
|
||||||
|
export async function addProject(db, userId, { name = 'p', gitUrl } = {}) {
|
||||||
|
seq++;
|
||||||
|
const r = await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)')
|
||||||
|
.run(userId, name, gitUrl || `https://git.test/u/${seq}.git`, 1_700_000_000);
|
||||||
|
return Number(r.lastInsertRowid);
|
||||||
|
}
|
||||||
|
|
@ -16,11 +16,26 @@ function splitTop(s) {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tables, colonnes et clés étrangères déclarées par une liste d'instructions CREATE TABLE
|
// Tables, colonnes et clés étrangères déclarées par la suite d'instructions des migrations : CREATE TABLE,
|
||||||
|
// puis DROP TABLE, RENAME TO, ADD COLUMN et ADD CONSTRAINT ... FOREIGN KEY rejoués dans l'ordre (état final).
|
||||||
function parseDdl(statements) {
|
function parseDdl(statements) {
|
||||||
const tables = new Map();
|
const tables = new Map();
|
||||||
for (const raw of statements) {
|
const cascade = (item) => [...item.matchAll(/REFERENCES\s+`?(\w+)`?\s*\([^)]*\)\s*ON DELETE CASCADE/gi)].map((r) => r[1]);
|
||||||
const sql = raw.replace(/--[^\n]*/g, '');
|
for (const st of statements) {
|
||||||
|
const sql = (typeof st === 'string' ? st : st.sql).replace(/--[^\n]*/g, '').trim();
|
||||||
|
let a;
|
||||||
|
if ((a = /^DROP TABLE (?:IF EXISTS )?`?(\w+)`?/i.exec(sql))) { tables.delete(a[1]); continue; }
|
||||||
|
if ((a = /^ALTER TABLE `?(\w+)`? RENAME TO `?(\w+)`?/i.exec(sql))) { tables.set(a[2], tables.get(a[1])); tables.delete(a[1]); continue; }
|
||||||
|
if ((a = /^ALTER TABLE `?(\w+)`? ADD COLUMN `?(\w+)`?/i.exec(sql))) {
|
||||||
|
const t = tables.get(a[1]);
|
||||||
|
t.columns.add(a[2]); t.refs = [...t.refs, ...cascade(sql)].sort();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ((a = /^ALTER TABLE `?(\w+)`? ADD CONSTRAINT/i.exec(sql))) {
|
||||||
|
const t = tables.get(a[1]);
|
||||||
|
t.refs = [...t.refs, ...cascade(sql)].sort();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const m = /CREATE TABLE (?:IF NOT EXISTS )?`?(\w+)`?\s*\(/i.exec(sql);
|
const m = /CREATE TABLE (?:IF NOT EXISTS )?`?(\w+)`?\s*\(/i.exec(sql);
|
||||||
if (!m) continue;
|
if (!m) continue;
|
||||||
let depth = 1, i = m.index + m[0].length;
|
let depth = 1, i = m.index + m[0].length;
|
||||||
|
|
@ -28,7 +43,7 @@ function parseDdl(statements) {
|
||||||
for (; i < sql.length && depth > 0; i++) { if (sql[i] === '(') depth++; else if (sql[i] === ')') depth--; }
|
for (; i < sql.length && depth > 0; i++) { if (sql[i] === '(') depth++; else if (sql[i] === ')') depth--; }
|
||||||
const columns = new Set(), refs = [];
|
const columns = new Set(), refs = [];
|
||||||
for (const item of splitTop(sql.slice(start, i - 1)).map((x) => x.trim())) {
|
for (const item of splitTop(sql.slice(start, i - 1)).map((x) => x.trim())) {
|
||||||
for (const r of item.matchAll(/REFERENCES\s+`?(\w+)`?\s*\([^)]*\)\s*ON DELETE CASCADE/gi)) refs.push(r[1]);
|
refs.push(...cascade(item));
|
||||||
if (/^(?:PRIMARY\s+KEY|UNIQUE|KEY\s+\w+\s*\(|INDEX|CONSTRAINT|FOREIGN\s+KEY|CHECK)/i.test(item)) continue;
|
if (/^(?:PRIMARY\s+KEY|UNIQUE|KEY\s+\w+\s*\(|INDEX|CONSTRAINT|FOREIGN\s+KEY|CHECK)/i.test(item)) continue;
|
||||||
columns.add(item.match(/^`?(\w+)`?/)[1]);
|
columns.add(item.match(/^`?(\w+)`?/)[1]);
|
||||||
}
|
}
|
||||||
|
|
@ -38,6 +53,9 @@ function parseDdl(statements) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const ddl = (dialect) => parseDdl(MIGRATIONS.flatMap((m) => m[dialect]));
|
const ddl = (dialect) => parseDdl(MIGRATIONS.flatMap((m) => m[dialect]));
|
||||||
|
|
||||||
|
// Tables volontairement hors du périmètre d'un utilisateur : liste d'opposition (RGPD) et états OAuth éphémères
|
||||||
|
const NOT_OWNED = new Set(['blacklist', 'oauth_states', 'users']);
|
||||||
const shape = (tables) => Object.fromEntries([...tables].map(([t, v]) => [t, { columns: [...v.columns].sort(), refs: v.refs }]));
|
const shape = (tables) => Object.fromEntries([...tables].map(([t, v]) => [t, { columns: [...v.columns].sort(), refs: v.refs }]));
|
||||||
|
|
||||||
test('schémas SQLite et MySQL : mêmes tables et mêmes colonnes', () => {
|
test('schémas SQLite et MySQL : mêmes tables et mêmes colonnes', () => {
|
||||||
|
|
@ -53,6 +71,25 @@ test('schémas : mêmes clés étrangères ON DELETE CASCADE des deux côtés',
|
||||||
for (const t of Object.keys(s)) assert.deepEqual(m[t].refs, s[t].refs, `FK de ${t}`);
|
for (const t of Object.keys(s)) assert.deepEqual(m[t].refs, s[t].refs, `FK de ${t}`);
|
||||||
assert.deepEqual(m.prospects.refs, ['projects']);
|
assert.deepEqual(m.prospects.refs, ['projects']);
|
||||||
assert.deepEqual(m.prospect_notes.refs, ['prospects']);
|
assert.deepEqual(m.prospect_notes.refs, ['prospects']);
|
||||||
|
assert.deepEqual(m.projects.refs, ['users']);
|
||||||
|
assert.deepEqual(m.jobs.refs, ['projects', 'users']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('multi-tenant : toute table métier descend d\'un utilisateur par cascade (donc la suppression de compte efface tout)', () => {
|
||||||
|
for (const dialect of ['sqlite', 'mysql']) {
|
||||||
|
const tables = ddl(dialect);
|
||||||
|
const owned = (t, seen = new Set()) => {
|
||||||
|
if (seen.has(t)) return false;
|
||||||
|
seen.add(t);
|
||||||
|
return tables.get(t).refs.some((p) => p === 'users' || owned(p, seen));
|
||||||
|
};
|
||||||
|
for (const t of tables.keys()) {
|
||||||
|
if (NOT_OWNED.has(t)) continue;
|
||||||
|
assert.ok(owned(t), `${dialect} : ${t} n'est rattachée à aucun utilisateur`);
|
||||||
|
}
|
||||||
|
assert.ok(!tables.has('settings'), 'plus de réglages globaux');
|
||||||
|
assert.ok(tables.get('user_settings').columns.has('user_id'));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('MySQL : InnoDB, utf8mb4, migrations rejouables', () => {
|
test('MySQL : InnoDB, utf8mb4, migrations rejouables', () => {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue