poad 2.21.0 → 2.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/project/db/diff.js +13 -4
- package/utils/compact.js +118 -0
- package/utils/migrations.js +9 -4
package/package.json
CHANGED
package/project/db/diff.js
CHANGED
|
@@ -44,16 +44,25 @@ module.exports = async (args = {}) => {
|
|
|
44
44
|
return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) forgotten ${chalk.grey('(still in the database)')}.`);
|
|
45
45
|
}
|
|
46
46
|
if (!name) {
|
|
47
|
-
|
|
47
|
+
const byId = new Map(c.entries.map((e) => [e.id, e]));
|
|
48
|
+
console.log(chalk.bold(`${c.units.length} structure change(s) not in a migration`));
|
|
48
49
|
console.log(' ');
|
|
49
|
-
for (const
|
|
50
|
+
for (const u of c.units) {
|
|
51
|
+
const e = byId.get(u.keep.length ? u.keep[u.keep.length - 1] : u.ids[u.ids.length - 1]);
|
|
50
52
|
const when = new Date(e.at).toLocaleString();
|
|
51
|
-
|
|
52
|
-
console.log(
|
|
53
|
+
const group = u.effect === 'merged' ? chalk.cyanBright(` · ${u.ids.length} changes → ${u.result}`) : u.effect === 'none' ? chalk.yellowBright(` · ${u.ids.length} changes, no effect`) : '';
|
|
54
|
+
console.log(chalk.grey(`-- ${when} · ${e.role_name}${e.application ? ' · ' + e.application : ''} · ${(e.commands || []).join(', ')}`) + group);
|
|
55
|
+
if (u.effect === 'none') console.log(chalk.grey(`-- ${u.target}: nothing to write`));
|
|
56
|
+
for (const id of u.keep) console.log(String(byId.get(id).statement).trim().replace(/;?\s*$/, ';'));
|
|
53
57
|
console.log(' ');
|
|
54
58
|
}
|
|
55
59
|
return console.log(chalk.grey(' "poad db diff <name>" writes them to poad/migrations (not replayed); "poad db diff --discard" forgets them.'));
|
|
56
60
|
}
|
|
61
|
+
if (!c.sql.trim()) {
|
|
62
|
+
// Que des changements qui s'annulent : rien à écrire
|
|
63
|
+
await migrations.discardChanges(client, c.upTo);
|
|
64
|
+
return console.log(`${chalk.greenBright('✔')} ${c.entries.length} change(s) with no net effect: nothing to write, journal cleared.`);
|
|
65
|
+
}
|
|
57
66
|
const file = await migrations.saveChanges(root, client, name, c.sql, c.upTo);
|
|
58
67
|
console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), file))} ${chalk.grey(`(${c.entries.length} change(s), already applied here)`)}`);
|
|
59
68
|
console.log(chalk.grey(' Review it, then commit it with your branch.'));
|
package/utils/compact.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Copie de infra/services/meta/src/compact.ts (compilée en CommonJS) : garder
|
|
2
|
+
// les deux identiques, la console et poad db diff regroupent pareil.
|
|
3
|
+
"use strict";
|
|
4
|
+
// Regroupement des changements du journal avant d'en faire une migration.
|
|
5
|
+
//
|
|
6
|
+
// Pour les objets qui n'ont qu'un état (présent / absent, activé / désactivé),
|
|
7
|
+
// une suite de changements se résume à son effet net :
|
|
8
|
+
// extension activer, désactiver, activer -> le dernier create
|
|
9
|
+
// activer, désactiver -> sans effet
|
|
10
|
+
// RLS d'une table enable, disable, enable -> le dernier enable
|
|
11
|
+
// enable, disable -> sans effet
|
|
12
|
+
// politique, index create, alter, drop -> sans effet
|
|
13
|
+
// drop, create -> drop puis create (remplacement)
|
|
14
|
+
// create, alter -> gardés tels quels
|
|
15
|
+
// Tout le reste (tables, colonnes, fonctions, renommages…) est gardé tel quel,
|
|
16
|
+
// dans l'ordre : deviner y ferait perdre une intention ou des données.
|
|
17
|
+
//
|
|
18
|
+
// Un changement n'est regroupé que s'il ne touche qu'un objet, et un groupe
|
|
19
|
+
// n'est résumé que si rien ne s'intercale entre ses entrées (sauf des
|
|
20
|
+
// politiques ou du RLS, dont rien ne dépend) : activer vector, créer une table
|
|
21
|
+
// qui l'utilise, la supprimer, désactiver vector garde tout, sinon la table
|
|
22
|
+
// serait créée sans son extension. Les entrées
|
|
23
|
+
// écartées (superseded) restent dans le journal jusqu'à ce que la migration
|
|
24
|
+
// les emporte (ids) ; seules celles de keep écrivent du SQL.
|
|
25
|
+
//
|
|
26
|
+
// Même code dans le CLI (utils/compact.js) : poad db diff regroupe pareil.
|
|
27
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
+
exports.compact = exports.classify = void 0;
|
|
29
|
+
const RLS_RE = /^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(.+?)\s+(enable|disable)\s+row\s+level\s+security\s*;?\s*$/is;
|
|
30
|
+
/** Objet unique et opération d'une entrée, ou null si elle n'est pas regroupable */
|
|
31
|
+
const classify = (e) => {
|
|
32
|
+
const objs = e.objects.filter((o) => Boolean(o));
|
|
33
|
+
if (e.commands.length !== 1 || objs.length !== 1)
|
|
34
|
+
return null;
|
|
35
|
+
const [cmd] = e.commands;
|
|
36
|
+
const target = objs[0];
|
|
37
|
+
const by = {
|
|
38
|
+
'CREATE EXTENSION': ['extension', 'on'],
|
|
39
|
+
'DROP EXTENSION': ['extension', 'off'],
|
|
40
|
+
'CREATE POLICY': ['policy', 'on'],
|
|
41
|
+
'ALTER POLICY': ['policy', 'alter'],
|
|
42
|
+
'DROP POLICY': ['policy', 'off'],
|
|
43
|
+
'CREATE INDEX': ['index', 'on'],
|
|
44
|
+
'DROP INDEX': ['index', 'off'],
|
|
45
|
+
};
|
|
46
|
+
if (by[cmd])
|
|
47
|
+
return { kind: by[cmd][0], target, op: by[cmd][1] };
|
|
48
|
+
if (cmd === 'ALTER TABLE') {
|
|
49
|
+
const m = RLS_RE.exec(e.statement);
|
|
50
|
+
if (m)
|
|
51
|
+
return { kind: 'rls', target, op: m[2].toLowerCase() === 'enable' ? 'on' : 'off' };
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
};
|
|
55
|
+
exports.classify = classify;
|
|
56
|
+
const RESULT = {
|
|
57
|
+
extension: ['activée', 'désactivée'],
|
|
58
|
+
rls: ['RLS activé', 'RLS désactivé'],
|
|
59
|
+
policy: ['créée', 'supprimée'],
|
|
60
|
+
index: ['créé', 'supprimé'],
|
|
61
|
+
};
|
|
62
|
+
/** Effet net d'une suite d'opérations sur un même objet */
|
|
63
|
+
const net = (kind, items) => {
|
|
64
|
+
const ops = items.map((i) => i.op);
|
|
65
|
+
const before = ops[0] === 'on' ? 'off' : 'on'; // create : l'objet n'existait pas
|
|
66
|
+
const after = ops.at(-1) === 'off' ? 'off' : 'on';
|
|
67
|
+
const lastOff = ops.lastIndexOf('off');
|
|
68
|
+
const lastOn = ops.lastIndexOf('on');
|
|
69
|
+
const stateOnly = kind === 'extension' || kind === 'rls';
|
|
70
|
+
let keep;
|
|
71
|
+
if (before === 'off' && after === 'off')
|
|
72
|
+
keep = [];
|
|
73
|
+
else if (before === 'off')
|
|
74
|
+
keep = items.slice(lastOn).map((i) => i.id); // le dernier create et ce qui le suit
|
|
75
|
+
else if (after === 'off')
|
|
76
|
+
keep = [items[lastOff].id]; // un seul drop
|
|
77
|
+
else if (lastOff < 0)
|
|
78
|
+
keep = items.map((i) => i.id); // que des alter
|
|
79
|
+
else if (stateOnly)
|
|
80
|
+
keep = []; // désactivé puis réactivé : comme avant
|
|
81
|
+
else
|
|
82
|
+
keep = items.slice(lastOff).map((i) => i.id); // remplacement : drop puis create
|
|
83
|
+
const effect = items.length === 1 ? 'one' : keep.length ? 'merged' : 'none';
|
|
84
|
+
return { keep, effect, result: effect === 'merged' ? RESULT[kind][after === 'on' ? 0 : 1] : null };
|
|
85
|
+
};
|
|
86
|
+
/** Unités à présenter, dans l'ordre du journal (position de leur dernière entrée gardée) */
|
|
87
|
+
const compact = (entries) => {
|
|
88
|
+
const groups = new Map();
|
|
89
|
+
const units = [];
|
|
90
|
+
for (const e of entries) {
|
|
91
|
+
const c = (0, exports.classify)(e);
|
|
92
|
+
if (!c) {
|
|
93
|
+
units.push({ ids: [e.id], keep: [e.id], kind: null, target: null, effect: 'one', result: null, at: e.id });
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const key = `${c.kind}:${c.target}`;
|
|
97
|
+
const g = groups.get(key) ?? { kind: c.kind, target: c.target, items: [] };
|
|
98
|
+
g.items.push({ id: e.id, op: c.op });
|
|
99
|
+
groups.set(key, g);
|
|
100
|
+
}
|
|
101
|
+
const kindOf = new Map(entries.map((e) => [e.id, (0, exports.classify)(e)?.kind ?? null]));
|
|
102
|
+
for (const g of groups.values()) {
|
|
103
|
+
const ids = g.items.map((i) => i.id);
|
|
104
|
+
const mine = new Set(ids);
|
|
105
|
+
const between = entries.filter((e) => e.id > ids[0] && e.id < ids.at(-1) && !mine.has(e.id));
|
|
106
|
+
const free = between.every((e) => kindOf.get(e.id) === 'policy' || kindOf.get(e.id) === 'rls');
|
|
107
|
+
if (!free) {
|
|
108
|
+
// Des changements dépendent peut-être des états intermédiaires : tout est gardé
|
|
109
|
+
for (const id of ids)
|
|
110
|
+
units.push({ ids: [id], keep: [id], kind: g.kind, target: g.target, effect: 'one', result: null, at: id });
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const n = net(g.kind, g.items);
|
|
114
|
+
units.push({ ids, keep: n.keep, kind: g.kind, target: g.target, effect: n.effect, result: n.result, at: n.keep.at(-1) ?? ids.at(-1) });
|
|
115
|
+
}
|
|
116
|
+
return units.sort((a, b) => a.at - b.at).map(({ at: _at, ...u }) => u);
|
|
117
|
+
};
|
|
118
|
+
exports.compact = compact;
|
package/utils/migrations.js
CHANGED
|
@@ -233,17 +233,22 @@ async function snapshot(client) {
|
|
|
233
233
|
if (await hasJournal(client)) await client.query('select poad_migrations.snapshot()');
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
-
/** Changements non enregistrés : { supported, entries, upTo, drift, sql } */
|
|
236
|
+
/** Changements non enregistrés : { supported, entries, units, upTo, drift, sql } (sql : regroupé) */
|
|
237
237
|
async function changes(client) {
|
|
238
238
|
if (!(await hasJournal(client))) return { supported: false, entries: [], upTo: null, drift: false, sql: '' };
|
|
239
239
|
const { rows } = await client.query('select id, at, statement, commands, objects, role_name, application from poad_migrations.journal order by id');
|
|
240
240
|
const st = (await client.query('select poad_migrations.status() as s')).rows[0].s || {};
|
|
241
|
+
// Effet net par objet (extension activée puis désactivée…) : utils/compact.js
|
|
242
|
+
const entries = rows.map((r) => ({ ...r, id: Number(r.id) }));
|
|
243
|
+
const units = require('./compact').compact(entries);
|
|
244
|
+
const kept = new Set(units.flatMap((u) => u.keep));
|
|
241
245
|
return {
|
|
242
246
|
supported: true,
|
|
243
|
-
entries
|
|
244
|
-
|
|
247
|
+
entries,
|
|
248
|
+
units,
|
|
249
|
+
upTo: entries.length ? entries[entries.length - 1].id : null,
|
|
245
250
|
drift: Boolean(st.drift) && rows.length === 0,
|
|
246
|
-
sql:
|
|
251
|
+
sql: entries.filter((r) => kept.has(r.id)).map((r) => String(r.statement).trim().replace(/;?\s*$/, ';')).join('\n\n'),
|
|
247
252
|
};
|
|
248
253
|
}
|
|
249
254
|
|